List of usage examples for javax.websocket.server ServerContainer addEndpoint
public abstract void addEndpoint(ServerEndpointConfig sec) throws DeploymentException;
From source file:io.tempra.AppServer.java
public static void main(String[] args) throws Exception { try {//ww w . j a v a 2s. co m // String dir = getProperty("storageLocal");// // System.getProperty("user.home"); String arch = "Win" + System.getProperty("sun.arch.data.model"); System.out.println("sun.arch.data.model " + arch); // Sample to force java load dll or so on a filesystem // InputStream in = AppServer.class.getResourceAsStream("/dll/" + // arch + "/RechargeRPC.dll"); // // File jCliSiTefI = new File(dir + "/" + "RechargeRPC.dll"); // System.out.println("Writing dll to: " + // jCliSiTefI.getAbsolutePath()); // OutputStream os = new FileOutputStream(jCliSiTefI); // byte[] buffer = new byte[4096]; // int length; // while ((length = in.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // os.close(); // in.close(); // System.load(jCliSiTefI.toString()); // addLibraryPath(dir); } catch (Exception e) { e.printStackTrace(); } ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); Server jettyServer = new Server(Integer.parseInt(getProperty("localport"))); // security configuration // FilterHolder holder = new FilterHolder(CrossOriginFilter.class); // holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, // "*"); // holder.setInitParameter("allowCredentials", "true"); // holder.setInitParameter( // CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, // "GET,POST,HEAD"); // holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, // "X-Requested-With,Content-Type,Accept,Origin"); // holder.setName("cross-origin"); // context.addFilter(holder, fm); ResourceHandler resource_handler = new ResourceHandler(); // add application on embedded server boolean servApp = true; boolean quioskMode = false; // if (System.getProperty("noServApp") != null ) // if (System.getProperty("noServApp").equalsIgnoreCase("true")) // servApp = false; if (servApp) { // ProtectionDomain domain = AppServer.class.getProtectionDomain(); String webDir = AppServer.class.getResource("/webapp").toExternalForm(); System.out.println("Jetty WEB DIR >>>>" + webDir); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); resource_handler.setResourceBase(webDir); // // "C:/git/tsAgenciaVirtual/www/"); // resource_handler.setResourceBase("C:/git/tsAgenciaVirtual/www/"); // copyJarResourceToFolder((JarURLConnection) AppServer.class // .getResource("/app").openConnection(), createTempDir("app")); // resource_handler.setResourceBase(System // .getProperty("java.io.tmpdir") + "/app"); } // sample to add rest services on container context.addServlet(FileUploadServlet.class, "/upload"); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/services/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", RestServices.class.getCanonicalName() + "," + RestServices.class.getCanonicalName()); HandlerList handlers = new HandlerList(); // context.addFilter(holder, "/*", EnumSet.of(DispatcherType.REQUEST)); handlers.setHandlers(new Handler[] { resource_handler, context, // wscontext, new DefaultHandler() }); jettyServer.setHandler(handlers); try { // Initialize javax.websocket layer ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.setDefaultMaxSessionIdleTimeout(TimeUnit.HOURS.toMillis(1000)); // Add WebSocket endpoint to javax.websocket layer wscontainer.addEndpoint(FileUpload.class); } catch (Throwable t) { t.printStackTrace(System.err); } // try { jettyServer.start(); jettyServer.dump(System.err); if (servApp && quioskMode) { try { Process process = new ProcessBuilder( "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "--kiosk", "--kiosk-printing", "--auto", "--disable-pinch", "--incognito", "--disable-session-crashed-bubble", "--overscroll-history-navigation=0", "http://localhost:" + getProperty("localport")).start(); // Process process = // Runtime.getRuntime().exec(" -kiosk http://localhost:8080"); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf("Output of running %s is:", Arrays.toString(args)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } // } finally { // jettyServer.destroy(); // }//} jettyServer.join(); }
From source file:io.cettia.ProtocolTest.java
@Test public void protocol() throws Exception { final DefaultServer server = new DefaultServer(); server.onsocket(new Action<ServerSocket>() { @Override/* ww w. j a v a 2 s.c o m*/ public void on(final ServerSocket socket) { log.debug("socket.uri() is {}", socket.uri()); socket.on("abort", new VoidAction() { @Override public void on() { socket.close(); } }).on("echo", new Action<Object>() { @Override public void on(Object data) { socket.send("echo", data); } }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() { @Override public void on(Reply<Map<String, Object>> reply) { Map<String, Object> data = reply.data(); switch ((String) data.get("type")) { case "resolved": reply.resolve(data.get("data")); break; case "rejected": reply.reject(data.get("data")); break; } } }).on("/reply/outbound", new Action<Map<String, Object>>() { @Override public void on(Map<String, Object> data) { switch ((String) data.get("type")) { case "resolved": socket.send("test", data.get("data"), new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; case "rejected": socket.send("test", data.get("data"), null, new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; } } }); } }); final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server); final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server); org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(jetty); jetty.addConnector(connector); connector.setPort(8000); ServletContextHandler handler = new ServletContextHandler(); jetty.setHandler(handler); handler.addEventListener(new ServletContextListener() { @Override @SuppressWarnings("serial") public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Map<String, String[]> params = req.getParameterMap(); if (params.containsKey("heartbeat")) { server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0])); } if (params.containsKey("_heartbeat")) { server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0])); } } }); regSetup.addMapping("/setup"); // For HTTP transport Servlet servlet = new AsityServlet().onhttp(httpTransportServer); ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet); reg.setAsyncSupported(true); reg.addMapping("/cettia"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }); // For WebSocket transport ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia") .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer)); } }).build(); container.addEndpoint(config); jetty.start(); CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node") .addArgument("./src/test/resources/runner").addArgument("--cettia.transports") .addArgument("websocket,httpstream,httplongpoll"); DefaultExecutor executor = new DefaultExecutor(); // The exit value of mocha is the number of failed tests. executor.execute(cmdLine); jetty.stop(); }
From source file:org.wso2.carbon.integration.test.client.WebSocketServer.java
public void start(int port) { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port);/* w ww.ja v a2 s.c om*/ server.addConnector(connector); // Setup the basic application "context" for this application at "/" // This is also known as the handler tree (in jetty speak) ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); try { // Initialize javax.websocket layer ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); // Add WebSocket endpoint to javax.websocket layer wscontainer.addEndpoint(EventSocket.class); new Thread(new Runnable() { @Override public void run() { try { server.start(); server.join(); } catch (Exception e) { log.error(e); } } }).start(); } catch (Throwable t) { log.error(t); } }
From source file:org.wso2.carbon.sample.websocket.WebSocketServer.java
public void start(int port, String host) { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port);// w ww . j a va 2 s .com connector.setHost(host); server.addConnector(connector); // Setup the basic application "context" for this application at "/" // This is also known as the handler tree (in jetty speak) ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); try { // Initialize javax.websocket layer ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context); // Add WebSocket endpoint to javax.websocket layer wscontainer.addEndpoint(EventSocket.class); new Thread(new Runnable() { @Override public void run() { try { server.start(); server.join(); } catch (Exception e) { log.error(e); } } }).start(); } catch (Throwable t) { log.error(t); } }