Commits

Andy Moncsek committed 03b41d4

SSE twitter web-example finished

Comments (0)

Files changed (7)

EJB/src/main/java/org/jacp/jee/beans/SimpleMessageBean.java

 import org.jacp.jee.api.MessageEJBInterface;
 import org.jacp.jee.entity.ClientMessage;
 
-@Stateless(mappedName = "SimpleMessagingBean", name="SimpleMessagingBean")
+@Stateless
 @Remote(MessageEJBInterface.class)
 public class SimpleMessageBean implements MessageEJBInterface {
     @PersistenceContext

JacpFXWebsocketChatClient/src/main/java/org/jacp/chat/main/Paint.java

+package org.jacp.chat.main;
+
+import javafx.application.Application;
+import javafx.event.EventHandler;
+import javafx.scene.Group;
+import javafx.scene.Scene;
+import javafx.scene.input.MouseEvent;
+import javafx.scene.paint.Color;
+import javafx.scene.shape.LineTo;
+import javafx.scene.shape.MoveTo;
+import javafx.scene.shape.Path;
+import javafx.stage.Stage;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: ady
+ * Date: 07.03.13
+ * Time: 14:28
+ * To change this template use File | Settings | File Templates.
+ */
+public class Paint extends Application {
+    Path path;
+
+    public static void main(String[] args) {
+        launch(args);
+    }
+
+    @Override
+    public void start(Stage primaryStage) {
+        Group root = new Group();
+        Scene scene = new Scene(root, 300, 250);
+
+        path = new Path();
+        path.setStrokeWidth(1);
+        path.setStroke(Color.BLACK);
+
+        scene.setOnMouseClicked(mouseHandler);
+        scene.setOnMouseDragged(mouseHandler);
+        scene.setOnMouseEntered(mouseHandler);
+        scene.setOnMouseExited(mouseHandler);
+        scene.setOnMouseMoved(mouseHandler);
+        scene.setOnMousePressed(mouseHandler);
+        scene.setOnMouseReleased(mouseHandler);
+
+        root.getChildren().add(path);
+        primaryStage.setScene(scene);
+        primaryStage.show();
+    }
+
+    EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
+
+        @Override
+        public void handle(MouseEvent mouseEvent) {
+            if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
+                path.getElements().clear();
+                path.getElements()
+                        .add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
+            } else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED) {
+                System.out.println(mouseEvent.getX()+" : "+mouseEvent.getY());
+                path.getElements()
+                        .add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
+            }
+
+        }
+
+    };
+
+}

WebClient-SSE/src/main/java/org/jacp/sse/SSEResource.java

+package org.jacp.sse;
+
+import org.glassfish.jersey.media.sse.EventOutput;
+import org.glassfish.jersey.media.sse.OutboundEvent;
+import org.glassfish.jersey.media.sse.SseFeature;
+
+import javax.ejb.Singleton;
+import javax.inject.Named;
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import java.io.IOException;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: ady
+ * Date: 07.03.13
+ * Time: 16:04
+ * To change this template use File | Settings | File Templates.
+ */
+@Path("twittersse")
+@Singleton
+@Named
+public class SSEResource {
+    private EventOutput eventOutput = new EventOutput();
+
+    @GET
+    @Produces(SseFeature.SERVER_SENT_EVENTS)
+    public EventOutput getMessage() {
+        return eventOutput;
+    }
+
+
+    @POST
+    @Consumes(MediaType.TEXT_PLAIN)
+    public void sendMessage(String message) throws IOException {
+        eventOutput.write(new OutboundEvent.Builder().name("custom-message").data(String.class, message).build());
+    }
+}

WebClient-SSE/src/main/java/org/jacp/sse/WebClient.java

+package org.jacp.sse;
+
+import net.sf.json.JSONArray;
+import net.sf.json.JSONObject;
+import org.glassfish.jersey.media.sse.EventSource;
+import org.glassfish.jersey.media.sse.InboundEvent;
+
+import javax.servlet.AsyncContext;
+import javax.servlet.AsyncEvent;
+import javax.servlet.AsyncListener;
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.core.MediaType;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.URI;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: ady
+ * Date: 08.03.13
+ * Time: 09:30
+ * To change this template use File | Settings | File Templates.
+ */
+@WebServlet(name = "WebClient", urlPatterns = {"/WebClient"} ,asyncSupported=true)
+public class WebClient extends HttpServlet {
+
+    private final static String TARGET_URI = "http://localhost:8080/WebClient-SSE/twittersse";
+
+    @Override
+    public void init() throws ServletException {
+
+    }
+
+    /**
+     * Processes requests for both HTTP
+     * <code>GET</code> and
+     * <code>POST</code> methods.
+     *
+     * @param request servlet request
+     * @param response servlet response
+     * @throws ServletException if a servlet-specific error occurs
+     * @throws java.io.IOException if an I/O error occurs
+     */
+    @Override
+    protected void service(final HttpServletRequest request, final HttpServletResponse response)
+            throws ServletException, IOException {
+        response.setContentType("text/html;charset=UTF-8");
+
+        try {
+
+            final AsyncContext asyncContext = request.startAsync();
+            asyncContext.setTimeout(600000);
+            asyncContext.addListener(new AsyncListener() {
+
+                @Override
+                public void onComplete(AsyncEvent event) throws IOException {
+                }
+
+                @Override
+                public void onTimeout(AsyncEvent event) throws IOException {
+                    System.out.println("Timeout" + event.toString());
+                }
+
+                @Override
+                public void onError(AsyncEvent event) throws IOException {
+                    System.out.println("Error" + event.toString());
+                }
+
+                @Override
+                public void onStartAsync(AsyncEvent event) throws IOException {
+                }
+            });
+
+
+            Thread t = new Thread(new AsyncRequestProcessor(asyncContext));
+            t.start();
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+
+    /**
+     * This class will create the EventSource
+     * and when the SSE are received will print the data
+     * from the Inbound events
+     */
+    class AsyncRequestProcessor implements Runnable {
+
+        private final AsyncContext context;
+
+        public AsyncRequestProcessor(AsyncContext context) {
+            this.context = context;
+        }
+
+        @Override
+        public void run() {
+            Client client = ClientBuilder.newClient();
+            context.getResponse().setContentType("text/html");
+            final javax.ws.rs.client.WebTarget webTarget;
+            try {
+                final PrintWriter out = context.getResponse().getWriter();
+                webTarget = client.target(new URI(TARGET_URI));
+                out.println("<html>");
+                out.println("<head>");
+                out.println("<title>Glassfish SSE TestClient</title>");
+                out.println("</head>");
+                out.println("<body>");
+                out.println("<h1>");
+                out.println("All good tweets");
+                out.println("</h1>");
+
+                EventSource eventSource = new EventSource(webTarget) {
+                    @Override
+                    public void onEvent(InboundEvent inboundEvent) {
+                        try {
+                            //get the JSON data and parse it
+                            JSONObject jsonObject = JSONObject.fromObject( inboundEvent.getData(String.class,
+                                    MediaType.APPLICATION_JSON_TYPE ));
+                            JSONArray jsonArray = (((JSONArray) (jsonObject.get("results"))));
+                            for (int i = 0; i <jsonArray.size(); i++) {
+                                JSONObject o = ((JSONObject)jsonArray.get(i)) ;
+                                out.println( o.get("text"));
+                                out.println("<br>");
+                                out.println("Created at " + o.get("created_at"));
+                                out.println("<br>");
+
+                            }
+                            out.println("</p>");
+                            out.flush();
+
+                        } catch (IOException e) {
+                            e.printStackTrace();
+                        }
+                    }
+                };
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+
+        }
+    }
+}

WebClient-SSE/src/main/java/org/jacp/sse/application/JerseyApplication.java

+package org.jacp.sse.application;
+
+import org.glassfish.jersey.media.sse.OutboundEventWriter;
+import org.jacp.sse.SSEResource;
+
+import javax.ws.rs.core.Application;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: ady
+ * Date: 07.03.13
+ * Time: 16:08
+ * To change this template use File | Settings | File Templates.
+ */
+public class JerseyApplication extends Application {
+
+    Set<Class<?>> classes = new HashSet<Class<?>>() {
+        { add(SSEResource.class);
+            add(OutboundEventWriter.class);
+        }};
+
+    @Override
+    public Set<Class<?>> getClasses() {
+        return classes;
+    }
+}

WebClient-SSE/src/main/java/org/jacp/sse/beans/TwitterTimerBean.java

+package org.jacp.sse.beans;
+
+import javax.ejb.Schedule;
+import javax.ejb.Stateless;
+import javax.inject.Named;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: ady
+ * Date: 07.03.13
+ * Time: 16:06
+ * To change this template use File | Settings | File Templates.
+ */
+@Stateless
+@Named
+public class TwitterTimerBean {
+
+    private final static String TARGET_URI= "http://localhost:8080/WebClient-SSE";
+
+    @Schedule(hour="*", minute="*", second="*/10")
+    public void sendTweets() {
+
+        Client client = ClientBuilder.newClient();
+        try {
+            WebTarget webTarget= client.target(new URI(TARGET_URI)) ;
+            List<String> list = new ArrayList<String>();
+            list.add("glassfish");
+            list.add("gf_jersey");
+            list.add("websockets");
+            list.add("java");
+            list.add("MasoudKalali");
+            Random rg = new Random();
+            String randomElement;
+            int listSize = list.size();
+            randomElement = list.get(rg.nextInt(listSize));
+            System.out.println("String" +randomElement);
+            String message = getFeedData(randomElement);
+            System.out.println("Posting message");
+            webTarget.path("twittersse").request().post(Entity.text(message));
+        } catch (URISyntaxException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    private  String getFeedData(String input) {
+        StringBuilder sb = new StringBuilder();
+        String searchURL ="http://search.twitter.com/search.json?q="+input+"&rpp=5&include_entities=true" +
+                "&with_twitter_user_id=true&result_type=mixed";
+        try {
+            URL twitter = new URL(searchURL);
+            URLConnection yc = null;
+
+            yc = twitter.openConnection();
+
+
+            BufferedReader in = new BufferedReader(
+                    new InputStreamReader(
+                            yc.getInputStream()));
+            String inputLine;
+
+            while ((inputLine = in.readLine()) != null) {
+                System.out.println("Input line" + inputLine);
+                sb.append(inputLine)  ;
+
+            }
+            in.close();
+
+            return sb.toString();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return new String("Error in getting data from the feeds ") ;
+    }
+
+
+}
             <id>java.net-promoted</id>
             <url>https://maven.java.net/content/groups/promoted/</url>
         </repository>
+        <repository>
+            <id>prime-repo</id>
+            <name>PrimeFacesMaven Repository</name>
+            <url>http://repository.primefaces.org</url>
+            <layout>default</layout>
+        </repository>
     </repositories>
     <profiles>
         <profile>
                 <module>EJBClient</module>
                 <module>EJB</module>
                 <module>WebClient-Websocket</module>
+				<module>WebClient-SSE</module>
                 <module>EAR-Websocket</module>
+				<module>EAR-SSE</module>
                 <module>JavaClient</module>
                 <module>JacpFXWebsocketChatClient</module>
             </modules>
                 <module>JacpFXWebsocketChatClient</module>
             </modules>
         </profile>
+		<profile>
+            <id>twitter</id>
+            <modules>
+                <module>Domain</module>
+                <module>EJBClient</module>
+                <module>EJB</module>
+				<module>WebClient-SSE</module>
+				<module>EAR-SSE</module>
+                <module>JavaClient</module>
+            </modules>
+        </profile>
     </profiles>
     <modules>
         <module>Domain</module>
         <module>EJBClient</module>
         <module>EJB</module>
         <module>WebClient-Websocket</module>
+		<module>WebClient-SSE</module>
         <module>EAR-Websocket</module>
+		<module>EAR-SSE</module>
         <module>JavaClient</module>
         <module>JacpFXWebsocketChatClient</module>
     </modules>
     <properties>
         <javax.persistence.version>2.0.0</javax.persistence.version>
         <jee.version>7.0-b77</jee.version>
+        <glassfish.version>4.0-b77</glassfish.version>
+        <jersey.version>2.0-m12-1</jersey.version>
         <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
         <junit.version>4.11</junit.version>
        <!-- <tyrusWebsocket.version>1.0-b12</tyrusWebsocket.version>-->
         <javafx.version>2.2</javafx.version>
         <jacp.version>1.2</jacp.version>
         <spring.version>3.1.1.RELEASE</spring.version>
+        <primefaces.version>2.2.1</primefaces.version>
     </properties>
     <dependencyManagement>
         <dependencies>
                 <version>${project.version}</version>
                 <type>war</type>
             </dependency>
+			<dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>WebClient-SSE</artifactId>
+                <version>${project.version}</version>
+                <type>war</type>
+            </dependency>
             <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>EAR-Websocket</artifactId>
                 <version>${project.version}</version>
                 <type>ear</type>
             </dependency>
+			 <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>EAR-SSE</artifactId>
+                <version>${project.version}</version>
+                <type>ear</type>
+            </dependency>
             <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>JavaClient</artifactId>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.