javax.websocket.server.ServerEndpoint Java Examples

The following examples show how to use javax.websocket.server.ServerEndpoint. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerEndpointExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Actually register the endpoints. Called by {@link #afterSingletonsInstantiated()}.
 */
protected void registerEndpoints() {
	Set<Class<?>> endpointClasses = new LinkedHashSet<>();
	if (this.annotatedEndpointClasses != null) {
		endpointClasses.addAll(this.annotatedEndpointClasses);
	}

	ApplicationContext context = getApplicationContext();
	if (context != null) {
		String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
		for (String beanName : endpointBeanNames) {
			endpointClasses.add(context.getType(beanName));
		}
	}

	for (Class<?> endpointClass : endpointClasses) {
		registerEndpoint(endpointClass);
	}

	if (context != null) {
		Map<String, ServerEndpointConfig> endpointConfigMap = context.getBeansOfType(ServerEndpointConfig.class);
		for (ServerEndpointConfig endpointConfig : endpointConfigMap.values()) {
			registerEndpoint(endpointConfig);
		}
	}
}
 
Example #2
Source File: ServerEndpointExporter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Actually register the endpoints. Called by {@link #afterSingletonsInstantiated()}.
 */
protected void registerEndpoints() {
	Set<Class<?>> endpointClasses = new LinkedHashSet<>();
	if (this.annotatedEndpointClasses != null) {
		endpointClasses.addAll(this.annotatedEndpointClasses);
	}

	ApplicationContext context = getApplicationContext();
	if (context != null) {
		String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
		for (String beanName : endpointBeanNames) {
			endpointClasses.add(context.getType(beanName));
		}
	}

	for (Class<?> endpointClass : endpointClasses) {
		registerEndpoint(endpointClass);
	}

	if (context != null) {
		Map<String, ServerEndpointConfig> endpointConfigMap = context.getBeansOfType(ServerEndpointConfig.class);
		for (ServerEndpointConfig endpointConfig : endpointConfigMap.values()) {
			registerEndpoint(endpointConfig);
		}
	}
}
 
Example #3
Source File: ServerEndpointExporter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Actually register the endpoints. Called by {@link #afterSingletonsInstantiated()}.
 */
protected void registerEndpoints() {
	Set<Class<?>> endpointClasses = new LinkedHashSet<Class<?>>();
	if (this.annotatedEndpointClasses != null) {
		endpointClasses.addAll(this.annotatedEndpointClasses);
	}

	ApplicationContext context = getApplicationContext();
	if (context != null) {
		String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
		for (String beanName : endpointBeanNames) {
			endpointClasses.add(context.getType(beanName));
		}
	}

	for (Class<?> endpointClass : endpointClasses) {
		registerEndpoint(endpointClass);
	}

	if (context != null) {
		Map<String, ServerEndpointConfig> endpointConfigMap = context.getBeansOfType(ServerEndpointConfig.class);
		for (ServerEndpointConfig endpointConfig : endpointConfigMap.values()) {
			registerEndpoint(endpointConfig);
		}
	}
}
 
Example #4
Source File: AppConfig.java    From jetty-web-sockets-jsr356 with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws DeploymentException {
	container = ( ServerContainer )context.getServletContext().getAttribute( javax.websocket.server.ServerContainer.class.getName() );
	
	container.addEndpoint( 
		new AnnotatedServerEndpointConfig( BroadcastServerEndpoint.class, BroadcastServerEndpoint.class.getAnnotation( ServerEndpoint.class )  ) {
			@Override
			public Configurator getConfigurator() {
				return configurator();
			}
		}
	);
}
 
Example #5
Source File: CustomInitTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(final ServletContextHandler context) {
  try {
    ServerContainer container = context.getBean(ServerContainer.class);

    container.addEndpoint(ServerEndpointConfig.Builder
        .create(
            WSEndpoint.class,
            WSEndpoint.class.getAnnotation(ServerEndpoint.class).value()
        ).build());
  } catch (Exception e) {
    fail("Invalid test");
  }
}
 
Example #6
Source File: SaslTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Override
protected void registerWebSocketEndpoints(final ServerContainer container) {
  try {
    container.addEndpoint(ServerEndpointConfig.Builder
        .create(
            WSEndpoint.class,
            WSEndpoint.class.getAnnotation(ServerEndpoint.class).value()
        ).build());
  } catch (DeploymentException e) {
    fail("Invalid test");
  }
}
 
Example #7
Source File: WebSocketPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public InitState initialize(InitContext initContext) {
    if (isEnabled()) {
        serverEndpointClasses.addAll(initContext.scannedClassesByAnnotationClass().get(ServerEndpoint.class));
        clientEndpointClasses.addAll(initContext.scannedClassesByAnnotationClass().get(ClientEndpoint.class));
    }
    return InitState.INITIALIZED;
}
 
Example #8
Source File: WebSocketPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Collection<ClasspathScanRequest> classpathScanRequests() {
    if (isEnabled()) {
        return classpathScanRequestBuilder().annotationType(ServerEndpoint.class).annotationType(
                ClientEndpoint.class).build();
    } else {
        return super.classpathScanRequests();
    }
}
 
Example #9
Source File: WebsocketBundle.java    From dropwizard-websockets with MIT License 5 votes vote down vote up
public void addEndpoint(Class<?> clazz) {
    ServerEndpoint anno = clazz.getAnnotation(ServerEndpoint.class);
    if(anno == null){
        throw new RuntimeException(clazz.getCanonicalName()+" does not have a "+ServerEndpoint.class.getCanonicalName()+" annotation");
    }
    ServerEndpointConfig.Builder bldr =  ServerEndpointConfig.Builder.create(clazz, anno.value());
    if(defaultConfigurator != null){
        bldr = bldr.configurator(defaultConfigurator);
    }
    endpointConfigs.add(bldr.build());
    if (starting)
        throw new RuntimeException("can't add endpoint after starting lifecycle");
}
 
Example #10
Source File: InstJsrServerEndpointImpl.java    From dropwizard-websockets with MIT License 5 votes vote down vote up
@Override
public EventDriver create(Object websocket, WebSocketPolicy policy) throws Throwable {
    if (!(websocket instanceof EndpointInstance)) {
        throw new IllegalStateException(String.format("Websocket %s must be an %s", websocket.getClass().getName(), EndpointInstance.class.getName()));
    }

    EndpointInstance ei = (EndpointInstance) websocket;
    AnnotatedServerEndpointMetadata metadata = (AnnotatedServerEndpointMetadata) ei.getMetadata();
    JsrEvents<ServerEndpoint, ServerEndpointConfig> events = new JsrEvents<>(metadata);

    // Handle @OnMessage maxMessageSizes
    int maxBinaryMessage = getMaxMessageSize(policy.getMaxBinaryMessageSize(), metadata.onBinary, metadata.onBinaryStream);
    int maxTextMessage = getMaxMessageSize(policy.getMaxTextMessageSize(), metadata.onText, metadata.onTextStream);

    policy.setMaxBinaryMessageSize(maxBinaryMessage);
    policy.setMaxTextMessageSize(maxTextMessage);

    //////// instrumentation is here
    JsrAnnotatedEventDriver driver = new InstJsrAnnotatedEventDriver(policy, ei, events, metrics);
    ////////
    
    // Handle @PathParam values
    ServerEndpointConfig config = (ServerEndpointConfig) ei.getConfig();
    if (config instanceof PathParamServerEndpointConfig) {
        PathParamServerEndpointConfig ppconfig = (PathParamServerEndpointConfig) config;
        driver.setPathParameters(ppconfig.getPathParamMap());
    }

    return driver;
}
 
Example #11
Source File: EndpointDispatcher.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the endpoint against the {@link ServerEndpoint} since without {@link ServerEndpoint} definition
 * there can't be a WebSocket endpoint.
 * @param websocketEndpoint endpoint which should be validated.
 */
public boolean validateEndpointUri(Object websocketEndpoint) {
    if (websocketEndpoint != null) {
        return websocketEndpoint.getClass().isAnnotationPresent(ServerEndpoint.class);
    }
    return false;
}
 
Example #12
Source File: WebSocketServer.java    From apollo with Apache License 2.0 5 votes vote down vote up
private ServerEndpointConfig createEndpointConfig(Class<?> endpointClass) throws DeploymentException {
    ServerEndpoint annotation = endpointClass.getAnnotation(ServerEndpoint.class);
    if (annotation == null) {
        throw new InvalidWebSocketException("Unsupported WebSocket object, missing @" +
                ServerEndpoint.class + " annotation");
    }

    return ServerEndpointConfig.Builder.create(endpointClass, annotation.value())
            .subprotocols(Arrays.asList(annotation.subprotocols()))
            .decoders(Arrays.asList(annotation.decoders()))
            .encoders(Arrays.asList(annotation.encoders()))
            .configurator(configurator)
            .build();
}
 
Example #13
Source File: WsLoader.java    From mercury with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent event) {
    /*
     * This loader is not implemented using Spring's ServletContextInitializer
     * because it does not provide websocket compliant ServerContainer.
     *
     * ServletContextEvent would expose javax.websocket.server.ServerContainer correctly.
     */
    ServletContext context = event.getServletContext();
    SimpleClassScanner scanner = SimpleClassScanner.getInstance();
    Set<String> packages = scanner.getPackages(true);
    Object sc = context.getAttribute("javax.websocket.server.ServerContainer");
    if (sc instanceof ServerContainer) {
        ServerContainer container = (ServerContainer) sc;
        int total = 0;
        for (String p : packages) {
            List<Class<?>> endpoints = scanner.getAnnotatedClasses(p, ServerEndpoint.class);
            for (Class<?> cls : endpoints) {
                if (!Feature.isRequired(cls)) {
                    continue;
                }
                try {
                    container.addEndpoint(cls);
                    ServerEndpoint ep = cls.getAnnotation(ServerEndpoint.class);
                    total++;
                    log.info("{} registered as WEBSOCKET DISPATCHER {}", cls.getName(), Arrays.asList(ep.value()));
                } catch (DeploymentException e) {
                    log.error("Unable to deploy websocket endpoint {} - {}", cls, e.getMessage());
                }
            }
        }
        if (total > 0) {
            log.info("Total {} Websocket server endpoint{} registered (JSR-356)", total, total == 1 ? " is" : "s are");
        }
    } else {
        log.error("Unable to register any ServerEndpoints because javax.websocket.server.ServerContainer is not available");
    }
}
 
Example #14
Source File: KsqlRestApplication.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
@Override
protected void registerWebSocketEndpoints(ServerContainer container) {
  try {
    final ListeningScheduledExecutorService exec = MoreExecutors.listeningDecorator(
        Executors.newScheduledThreadPool(
            config.getInt(KsqlRestConfig.KSQL_WEBSOCKETS_NUM_THREADS),
            new ThreadFactoryBuilder()
                .setDaemon(true)
                .setNameFormat("websockets-query-thread-%d")
                .build()
        )
    );
    final ObjectMapper mapper = getJsonMapper();
    final StatementParser statementParser = new StatementParser(ksqlEngine);

    container.addEndpoint(
        ServerEndpointConfig.Builder
            .create(
                WSQueryEndpoint.class,
                WSQueryEndpoint.class.getAnnotation(ServerEndpoint.class).value()
            )
            .configurator(new Configurator() {
              @Override
              @SuppressWarnings("unchecked")
              public <T> T getEndpointInstance(Class<T> endpointClass) {
                return (T) new WSQueryEndpoint(
                    mapper,
                    statementParser,
                    ksqlEngine,
                    exec
                );
              }
            })
            .build()
    );
  } catch (DeploymentException e) {
    log.error("Unable to create websockets endpoint", e);
  }
}
 
Example #15
Source File: InstJsrAnnotatedEventDriver.java    From dropwizard-websockets with MIT License 4 votes vote down vote up
public InstJsrAnnotatedEventDriver(WebSocketPolicy policy, EndpointInstance ei, JsrEvents<ServerEndpoint, ServerEndpointConfig> events, MetricRegistry metrics) {
    super(policy, ei, events);
    this.edm = new EventDriverMetrics(metadata.getEndpointClass(), metrics);
}
 
Example #16
Source File: EndpointValidator.java    From msf4j with Apache License 2.0 4 votes vote down vote up
private boolean validateURI(Object webSocketEndpoint) throws WebSocketEndpointAnnotationException {
    if (webSocketEndpoint.getClass().isAnnotationPresent(ServerEndpoint.class)) {
        return true;
    }
    throw new WebSocketEndpointAnnotationException("Server Endpoint is not defined.");
}
 
Example #17
Source File: UndertowWebSocketExtension.java    From hammock with Apache License 2.0 4 votes vote down vote up
public void findWebSocketServers(@Observes @WithAnnotations(ServerEndpoint.class)ProcessAnnotatedType<?> pat) {
    endpointClasses.add(pat.getAnnotatedType().getJavaClass());
}
 
Example #18
Source File: EndpointDispatcher.java    From msf4j with Apache License 2.0 2 votes vote down vote up
/**
 * Extract the URI from the endpoint.
 * <b>Note that it is better use validateEndpointUri method to validate the endpoint uri
 * before getting it out if needed. Otherwise it will cause issues. Use this method only and only if
 * it is sure that endpoint contains {@link ServerEndpoint} defined.</b>
 *
 * @param webSocketEndpoint WebSocket endpoint which the URI should be extracted.
 * @return the URI of the Endpoint as a String.
 */
public String getUri(Object webSocketEndpoint) {
    return webSocketEndpoint.getClass().getAnnotation(ServerEndpoint.class).value();
}