use of javax.websocket.server.ServerContainer in project jetty.project by eclipse.
the class PongContextListener method contextInitialized.
@Override
public void contextInitialized(ServletContextEvent sce) {
ServerContainer container = (ServerContainer) sce.getServletContext().getAttribute(ServerContainer.class.getName());
try {
Configurator config = new Config();
container.addEndpoint(ServerEndpointConfig.Builder.create(PongMessageEndpoint.class, "/ping").configurator(config).build());
container.addEndpoint(ServerEndpointConfig.Builder.create(PongMessageEndpoint.class, "/pong").configurator(config).build());
container.addEndpoint(ServerEndpointConfig.Builder.create(PongSocket.class, "/ping-socket").build());
container.addEndpoint(ServerEndpointConfig.Builder.create(PongSocket.class, "/pong-socket").build());
} catch (DeploymentException e) {
throw new RuntimeException("Unable to add endpoint directly", e);
}
}
use of javax.websocket.server.ServerContainer in project che by eclipse.
the class ServerContainerInitializeListener method contextInitialized.
@Override
public final void contextInitialized(ServletContextEvent sce) {
final ServletContext servletContext = sce.getServletContext();
websocketContext = MoreObjects.firstNonNull(servletContext.getInitParameter("org.everrest.websocket.context"), "");
websocketEndPoint = MoreObjects.firstNonNull(servletContext.getInitParameter("org.eclipse.che.websocket.endpoint"), "");
eventBusEndPoint = MoreObjects.firstNonNull(servletContext.getInitParameter("org.eclipse.che.eventbus.endpoint"), "");
webApplicationDeclaredRoles = new WebApplicationDeclaredRoles(servletContext);
everrestConfiguration = (EverrestConfiguration) servletContext.getAttribute(EVERREST_CONFIG_ATTRIBUTE);
if (everrestConfiguration == null) {
everrestConfiguration = new EverrestConfiguration();
}
final ServerContainer serverContainer = (ServerContainer) servletContext.getAttribute("javax.websocket.server.ServerContainer");
try {
wsServerEndpointConfig = createWsServerEndpointConfig(servletContext);
eventbusServerEndpointConfig = createEventbusServerEndpointConfig(servletContext);
serverContainer.addEndpoint(wsServerEndpointConfig);
serverContainer.addEndpoint(eventbusServerEndpointConfig);
} catch (DeploymentException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
use of javax.websocket.server.ServerContainer in project nutzboot by nutzam.
the class JettyStarter method init.
public void init() throws Exception {
// 创建基础服务器
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setIdleTimeout(getThreadPoolIdleTimeout());
threadPool.setMinThreads(getMinThreads());
threadPool.setMaxThreads(getMaxThreads());
server = new Server(threadPool);
HttpConfiguration httpConfig = conf.make(HttpConfiguration.class, "jetty.httpConfig.");
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
ServerConnector connector = new ServerConnector(server, httpFactory);
connector.setHost(getHost());
connector.setPort(getPort());
connector.setIdleTimeout(getIdleTimeout());
server.setConnectors(new Connector[] { connector });
// 设置应用上下文
wac = new WebAppContext();
wac.setContextPath(getContextPath());
// wac.setExtractWAR(false);
// wac.setCopyWebInf(true);
// wac.setProtectedTargets(new String[]{"/java", "/javax", "/org",
// "/net", "/WEB-INF", "/META-INF"});
wac.setTempDirectory(new File("temp"));
wac.setClassLoader(classLoader);
wac.setConfigurationDiscovered(true);
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
wac.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
}
List<Resource> resources = new ArrayList<>();
for (String resourcePath : Arrays.asList("static/", "webapp/")) {
File f = new File(resourcePath);
if (f.exists()) {
resources.add(Resource.newResource(f));
}
Enumeration<URL> urls = appContext.getClassLoader().getResources(resourcePath);
while (urls.hasMoreElements()) {
resources.add(Resource.newResource(urls.nextElement()));
}
}
if (conf.has(PROP_STATIC_PATH_LOCAL)) {
File f = new File(conf.get(PROP_STATIC_PATH_LOCAL));
if (f.exists()) {
log.debug("found static local path, add it : " + f.getAbsolutePath());
resources.add(Resource.newResource(f));
} else {
log.debug("static local path not exist, skip it : " + f.getPath());
}
}
wac.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()])) {
@Override
public Resource addPath(String path) throws IOException, MalformedURLException {
// TODO 为啥ResourceCollection读取WEB-INF的时候返回null
// 从而导致org.eclipse.jetty.webapp.WebAppContext.getWebInf()抛NPE
// 先临时hack吧
Resource resource = super.addPath(path);
if (resource == null && "WEB-INF/".equals(path)) {
return Resource.newResource(new File("XXXX"));
}
return resource;
}
});
server.setHandler(wac);
List<String> list = Configuration.ClassList.serverDefault(server);
list.add("org.eclipse.jetty.annotations.AnnotationConfiguration");
wac.setConfigurationClasses(list);
wac.getServletContext().setExtendedListenerTypes(true);
wac.getSessionHandler().setMaxInactiveInterval(conf.getInt(PROP_SESSION_TIMEOUT, 30) * 60);
// 设置一下额外的东西
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", getMaxFormContentSize());
server.setDumpAfterStart(false);
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
addNutzSupport();
ServerContainer sc = WebSocketServerContainerInitializer.configureContext(wac);
for (Class<?> klass : Scans.me().scanPackage(appContext.getPackage())) {
if (klass.getAnnotation(ServerEndpoint.class) != null) {
sc.addEndpoint(klass);
}
}
}
use of javax.websocket.server.ServerContainer in project zeppelin by apache.
the class TerminalThread method run.
public void run() {
ServerConnector connector = new ServerConnector(jettyServer);
connector.setPort(port);
jettyServer.addConnector(connector);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/terminal/");
// We look for a file, as ClassLoader.getResource() is not
// designed to look for directories (we resolve the directory later)
ClassLoader clazz = TerminalThread.class.getClassLoader();
URL url = clazz.getResource("html");
if (url == null) {
throw new RuntimeException("Unable to find resource directory");
}
ResourceHandler resourceHandler = new ResourceHandler();
// Resolve file to directory
String webRootUri = url.toExternalForm();
LOGGER.info("WebRoot is " + webRootUri);
// debug
// webRootUri = "/home/hadoop/zeppelin-current/interpreter/sh";
resourceHandler.setResourceBase(webRootUri);
HandlerCollection handlers = new HandlerCollection(context, resourceHandler);
jettyServer.setHandler(handlers);
try {
ServerContainer container = WebSocketServerContainerInitializer.configureContext(context);
container.addEndpoint(TerminalSocket.class);
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
use of javax.websocket.server.ServerContainer in project component-runtime by Talend.
the class WebSocketBroadcastSetup method contextInitialized.
@Override
public void contextInitialized(final ServletContextEvent sce) {
final ServerContainer container = ServerContainer.class.cast(sce.getServletContext().getAttribute(ServerContainer.class.getName()));
final JAXRSServiceFactoryBean factory = JAXRSServiceFactoryBean.class.cast(bus.getExtension(ServerRegistry.class).getServers().iterator().next().getEndpoint().get(JAXRSServiceFactoryBean.class.getName()));
final String appBase = StreamSupport.stream(Spliterators.spliteratorUnknownSize(applications.iterator(), Spliterator.IMMUTABLE), false).filter(a -> a.getClass().isAnnotationPresent(ApplicationPath.class)).map(a -> a.getClass().getAnnotation(ApplicationPath.class)).map(ApplicationPath::value).findFirst().map(s -> !s.startsWith("/") ? "/" + s : s).orElse("/api/v1");
final String version = appBase.replaceFirst("/api", "");
final DestinationRegistry registry;
try {
final HTTPTransportFactory transportFactory = HTTPTransportFactory.class.cast(bus.getExtension(DestinationFactoryManager.class).getDestinationFactory("http://cxf.apache.org/transports/http" + "/configuration"));
registry = transportFactory.getRegistry();
} catch (final BusException e) {
throw new IllegalStateException(e);
}
final ServletContext servletContext = sce.getServletContext();
final WebSocketRegistry webSocketRegistry = new WebSocketRegistry(registry);
final ServletController controller = new ServletController(webSocketRegistry, new ServletConfig() {
@Override
public String getServletName() {
return "Talend Component Kit Websocket Transport";
}
@Override
public ServletContext getServletContext() {
return servletContext;
}
@Override
public String getInitParameter(final String s) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return emptyEnumeration();
}
}, new ServiceListGeneratorServlet(registry, bus));
webSocketRegistry.controller = controller;
Stream.concat(factory.getClassResourceInfo().stream().flatMap(cri -> cri.getMethodDispatcher().getOperationResourceInfos().stream()).map(ori -> {
final String uri = ori.getClassResourceInfo().getURITemplate().getValue() + ori.getURITemplate().getValue();
return ServerEndpointConfig.Builder.create(Endpoint.class, "/websocket" + version + "/" + String.valueOf(ori.getHttpMethod()).toLowerCase(ENGLISH) + uri).configurator(new ServerEndpointConfig.Configurator() {
@Override
public <T> T getEndpointInstance(final Class<T> clazz) throws InstantiationException {
final Map<String, List<String>> headers = new HashMap<>();
if (!ori.getProduceTypes().isEmpty()) {
headers.put(HttpHeaders.CONTENT_TYPE, singletonList(ori.getProduceTypes().iterator().next().toString()));
}
if (!ori.getConsumeTypes().isEmpty()) {
headers.put(HttpHeaders.ACCEPT, singletonList(ori.getConsumeTypes().iterator().next().toString()));
}
return (T) new JAXRSEndpoint(appBase, controller, servletContext, ori.getHttpMethod(), uri, headers);
}
}).build();
}), Stream.of(ServerEndpointConfig.Builder.create(Endpoint.class, "/websocket" + version + "/bus").configurator(new ServerEndpointConfig.Configurator() {
@Override
public <T> T getEndpointInstance(final Class<T> clazz) throws InstantiationException {
return (T) new JAXRSEndpoint(appBase, controller, servletContext, "GET", "/", emptyMap());
}
}).build())).sorted(Comparator.comparing(ServerEndpointConfig::getPath)).peek(e -> log.info("Deploying WebSocket(path={})", e.getPath())).forEach(config -> {
try {
container.addEndpoint(config);
} catch (final DeploymentException e) {
throw new IllegalStateException(e);
}
});
}
Aggregations