Search in sources :

Example 36 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat by apache.

the class WsServerContainer method addEndpoint.

/**
     * Published the provided endpoint implementation at the specified path with
     * the specified configuration. {@link #WsServerContainer(ServletContext)}
     * must be called before calling this method.
     *
     * @param sec   The configuration to use when creating endpoint instances
     * @throws DeploymentException if the endpoint cannot be published as
     *         requested
     */
@Override
public void addEndpoint(ServerEndpointConfig sec) throws DeploymentException {
    if (enforceNoAddAfterHandshake && !addAllowed) {
        throw new DeploymentException(sm.getString("serverContainer.addNotAllowed"));
    }
    if (servletContext == null) {
        throw new DeploymentException(sm.getString("serverContainer.servletContextMissing"));
    }
    String path = sec.getPath();
    // Add method mapping to user properties
    PojoMethodMapping methodMapping = new PojoMethodMapping(sec.getEndpointClass(), sec.getDecoders(), path);
    if (methodMapping.getOnClose() != null || methodMapping.getOnOpen() != null || methodMapping.getOnError() != null || methodMapping.hasMessageHandlers()) {
        sec.getUserProperties().put(org.apache.tomcat.websocket.pojo.Constants.POJO_METHOD_MAPPING_KEY, methodMapping);
    }
    UriTemplate uriTemplate = new UriTemplate(path);
    if (uriTemplate.hasParameters()) {
        Integer key = Integer.valueOf(uriTemplate.getSegmentCount());
        SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key);
        if (templateMatches == null) {
            // Ensure that if concurrent threads execute this block they
            // both end up using the same TreeSet instance
            templateMatches = new TreeSet<>(TemplatePathMatchComparator.getInstance());
            configTemplateMatchMap.putIfAbsent(key, templateMatches);
            templateMatches = configTemplateMatchMap.get(key);
        }
        if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) {
            // Duplicate uriTemplate;
            throw new DeploymentException(sm.getString("serverContainer.duplicatePaths", path, sec.getEndpointClass(), sec.getEndpointClass()));
        }
    } else {
        // Exact match
        ServerEndpointConfig old = configExactMatchMap.put(path, sec);
        if (old != null) {
            // Duplicate path mappings
            throw new DeploymentException(sm.getString("serverContainer.duplicatePaths", path, old.getEndpointClass(), sec.getEndpointClass()));
        }
    }
    endpointsRegistered = true;
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DeploymentException(javax.websocket.DeploymentException) PojoMethodMapping(org.apache.tomcat.websocket.pojo.PojoMethodMapping)

Example 37 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat70 by apache.

the class WsSci method onStartup.

@Override
public void onStartup(Set<Class<?>> clazzes, ServletContext ctx) throws ServletException {
    if (!isJava7OrLater()) {
        // it if Java 7 is not available.
        if (!logMessageWritten) {
            logMessageWritten = true;
            log.info(sm.getString("sci.noWebSocketSupport"));
        }
        return;
    }
    WsServerContainer sc = init(ctx, true);
    if (clazzes == null || clazzes.size() == 0) {
        return;
    }
    // Group the discovered classes by type
    Set<ServerApplicationConfig> serverApplicationConfigs = new HashSet<ServerApplicationConfig>();
    Set<Class<? extends Endpoint>> scannedEndpointClazzes = new HashSet<Class<? extends Endpoint>>();
    Set<Class<?>> scannedPojoEndpoints = new HashSet<Class<?>>();
    try {
        // wsPackage is "javax.websocket."
        String wsPackage = ContainerProvider.class.getName();
        wsPackage = wsPackage.substring(0, wsPackage.lastIndexOf('.') + 1);
        for (Class<?> clazz : clazzes) {
            int modifiers = clazz.getModifiers();
            if (!Modifier.isPublic(modifiers) || Modifier.isAbstract(modifiers)) {
                // Non-public or abstract - skip it.
                continue;
            }
            // Protect against scanning the WebSocket API JARs
            if (clazz.getName().startsWith(wsPackage)) {
                continue;
            }
            if (ServerApplicationConfig.class.isAssignableFrom(clazz)) {
                serverApplicationConfigs.add((ServerApplicationConfig) clazz.newInstance());
            }
            if (Endpoint.class.isAssignableFrom(clazz)) {
                @SuppressWarnings("unchecked") Class<? extends Endpoint> endpoint = (Class<? extends Endpoint>) clazz;
                scannedEndpointClazzes.add(endpoint);
            }
            if (clazz.isAnnotationPresent(ServerEndpoint.class)) {
                scannedPojoEndpoints.add(clazz);
            }
        }
    } catch (InstantiationException e) {
        throw new ServletException(e);
    } catch (IllegalAccessException e) {
        throw new ServletException(e);
    }
    // Filter the results
    Set<ServerEndpointConfig> filteredEndpointConfigs = new HashSet<ServerEndpointConfig>();
    Set<Class<?>> filteredPojoEndpoints = new HashSet<Class<?>>();
    if (serverApplicationConfigs.isEmpty()) {
        filteredPojoEndpoints.addAll(scannedPojoEndpoints);
    } else {
        for (ServerApplicationConfig config : serverApplicationConfigs) {
            Set<ServerEndpointConfig> configFilteredEndpoints = config.getEndpointConfigs(scannedEndpointClazzes);
            if (configFilteredEndpoints != null) {
                filteredEndpointConfigs.addAll(configFilteredEndpoints);
            }
            Set<Class<?>> configFilteredPojos = config.getAnnotatedEndpointClasses(scannedPojoEndpoints);
            if (configFilteredPojos != null) {
                filteredPojoEndpoints.addAll(configFilteredPojos);
            }
        }
    }
    try {
        // Deploy endpoints
        for (ServerEndpointConfig config : filteredEndpointConfigs) {
            sc.addEndpoint(config);
        }
        // Deploy POJOs
        for (Class<?> clazz : filteredPojoEndpoints) {
            sc.addEndpoint(clazz);
        }
    } catch (DeploymentException e) {
        throw new ServletException(e);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServerApplicationConfig(javax.websocket.server.ServerApplicationConfig) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) ServletException(javax.servlet.ServletException) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) DeploymentException(javax.websocket.DeploymentException) HashSet(java.util.HashSet)

Example 38 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat70 by apache.

the class WsServerContainer method addEndpoint.

/**
 * Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)}
 * for publishing plain old java objects (POJOs) that have been annotated as
 * WebSocket endpoints.
 *
 * @param pojo   The annotated POJO
 */
@Override
public void addEndpoint(Class<?> pojo) throws DeploymentException {
    ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class);
    if (annotation == null) {
        throw new DeploymentException(sm.getString("serverContainer.missingAnnotation", pojo.getName()));
    }
    String path = annotation.value();
    // Validate encoders
    validateEncoders(annotation.encoders());
    // ServerEndpointConfig
    ServerEndpointConfig sec;
    Class<? extends Configurator> configuratorClazz = annotation.configurator();
    Configurator configurator = null;
    if (!configuratorClazz.equals(Configurator.class)) {
        try {
            configurator = annotation.configurator().newInstance();
        } catch (InstantiationException e) {
            throw new DeploymentException(sm.getString("serverContainer.configuratorFail", annotation.configurator().getName(), pojo.getClass().getName()), e);
        } catch (IllegalAccessException e) {
            throw new DeploymentException(sm.getString("serverContainer.configuratorFail", annotation.configurator().getName(), pojo.getClass().getName()), e);
        }
    }
    sec = ServerEndpointConfig.Builder.create(pojo, path).decoders(Arrays.asList(annotation.decoders())).encoders(Arrays.asList(annotation.encoders())).subprotocols(Arrays.asList(annotation.subprotocols())).configurator(configurator).build();
    addEndpoint(sec);
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) Configurator(javax.websocket.server.ServerEndpointConfig.Configurator) DeploymentException(javax.websocket.DeploymentException) ServerEndpoint(javax.websocket.server.ServerEndpoint)

Example 39 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat70 by apache.

the class WsServerContainer method findMapping.

public WsMappingResult findMapping(String path) {
    // been made to use one
    if (addAllowed) {
        addAllowed = false;
    }
    // Check an exact match. Simple case as there are no templates.
    ServerEndpointConfig sec = configExactMatchMap.get(path);
    if (sec != null) {
        return new WsMappingResult(sec, Collections.<String, String>emptyMap());
    }
    // No exact match. Need to look for template matches.
    UriTemplate pathUriTemplate = null;
    try {
        pathUriTemplate = new UriTemplate(path);
    } catch (DeploymentException e) {
        // Path is not valid so can't be matched to a WebSocketEndpoint
        return null;
    }
    // Number of segments has to match
    Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount());
    SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key);
    if (templateMatches == null) {
        // no matches
        return null;
    }
    // List is in alphabetical order of normalised templates.
    // Correct match is the first one that matches.
    Map<String, String> pathParams = null;
    for (TemplatePathMatch templateMatch : templateMatches) {
        pathParams = templateMatch.getUriTemplate().match(pathUriTemplate);
        if (pathParams != null) {
            sec = templateMatch.getConfig();
            break;
        }
    }
    if (sec == null) {
        // No match
        return null;
    }
    return new WsMappingResult(sec, pathParams);
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) DeploymentException(javax.websocket.DeploymentException)

Example 40 with ServerEndpointConfig

use of javax.websocket.server.ServerEndpointConfig in project tomcat70 by apache.

the class PojoEndpointServer method onOpen.

@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
    ServerEndpointConfig sec = (ServerEndpointConfig) endpointConfig;
    Object pojo;
    try {
        pojo = sec.getConfigurator().getEndpointInstance(sec.getEndpointClass());
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(sm.getString("pojoEndpointServer.getPojoInstanceFail", sec.getEndpointClass().getName()), e);
    }
    setPojo(pojo);
    @SuppressWarnings("unchecked") Map<String, String> pathParameters = (Map<String, String>) sec.getUserProperties().get(POJO_PATH_PARAM_KEY);
    setPathParameters(pathParameters);
    PojoMethodMapping methodMapping = (PojoMethodMapping) sec.getUserProperties().get(POJO_METHOD_MAPPING_KEY);
    setMethodMapping(methodMapping);
    doOnOpen(session, endpointConfig);
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) Map(java.util.Map)

Aggregations

ServerEndpointConfig (javax.websocket.server.ServerEndpointConfig)49 DeploymentException (javax.websocket.DeploymentException)17 ServerEndpoint (javax.websocket.server.ServerEndpoint)14 Test (org.junit.Test)13 ServletException (javax.servlet.ServletException)10 TesterServletContext (org.apache.tomcat.unittest.TesterServletContext)10 WebSocketBaseTest (org.apache.tomcat.websocket.WebSocketBaseTest)10 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)7 Endpoint (javax.websocket.Endpoint)6 ServerContainer (javax.websocket.server.ServerContainer)6 Server (org.eclipse.jetty.server.Server)6 ServerConnector (org.eclipse.jetty.server.ServerConnector)6 IOException (java.io.IOException)5 EndpointInstance (org.eclipse.jetty.websocket.jsr356.endpoints.EndpointInstance)5 Before (org.junit.Before)5 HandshakeResponse (javax.websocket.HandshakeResponse)4 HandshakeRequest (javax.websocket.server.HandshakeRequest)4 WebSocketDeploymentInfo (io.undertow.websockets.jsr.WebSocketDeploymentInfo)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3