javax.websocket.DeploymentException Java Examples

The following examples show how to use javax.websocket.DeploymentException. 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: WsServerContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private static void validateEncoders(Class<? extends Encoder>[] encoders)
        throws DeploymentException {

    for (Class<? extends Encoder> encoder : encoders) {
        // Need to instantiate decoder to ensure it is valid and that
        // deployment can be failed if it is not
        @SuppressWarnings("unused")
        Encoder instance;
        try {
            encoder.getConstructor().newInstance();
        } catch(ReflectiveOperationException e) {
            throw new DeploymentException(sm.getString(
                    "serverContainer.encoderFail", encoder.getName()), e);
        }
    }
}
 
Example #2
Source File: TestConnectionLimit.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void run() {
    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    int count = 0;

    try {
        while (true) {
            wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
                    Builder.create().build(), uri);
            count = counter.incrementAndGet();
            if (count % 100 == 0) {
                System.out.println(count + " and counting...");
            }
        }
    } catch (IOException | DeploymentException ioe) {
        // Let thread die
    }
}
 
Example #3
Source File: TesterEndpointConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute(
            Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

    try {
        ServerEndpointConfig sec = getServerEndpointConfig();
        if (sec == null) {
            sc.addEndpoint(getEndpointClass());
        } else {
            sc.addEndpoint(sec);
        }
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: ServerEndpointExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void registerEndpoint(Class<?> endpointClass) {
	ServerContainer serverContainer = getServerContainer();
	Assert.state(serverContainer != null,
			"No ServerContainer set. Most likely the server's own WebSocket ServletContainerInitializer " +
			"has not run yet. Was the Spring ApplicationContext refreshed through a " +
			"org.springframework.web.context.ContextLoaderListener, " +
			"i.e. after the ServletContext has been fully initialized?");
	try {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering @ServerEndpoint class: " + endpointClass);
		}
		serverContainer.addEndpoint(endpointClass);
	}
	catch (DeploymentException ex) {
		throw new IllegalStateException("Failed to register @ServerEndpoint class: " + endpointClass, ex);
	}
}
 
Example #5
Source File: EncodingFactory.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private static Class<?> findEncodeMethod(final Class<? extends Encoder> encoder, final Class<?> returnType, Class<?>... otherParameters) throws DeploymentException {
    for (Method method : encoder.getMethods()) {
        if (method.getName().equals("encode") && !method.isBridge() &&
                method.getParameterCount() == 1 + otherParameters.length &&
                method.getReturnType() == returnType) {
            boolean ok = true;
            for (int i = 1; i < method.getParameterCount(); ++i) {
                if (method.getParameterTypes()[i] != otherParameters[i - 1]) {
                    ok = false;
                    break;
                }
            }
            if (ok) {
                return method.getParameterTypes()[0];
            }
        }
    }
    throw JsrWebSocketMessages.MESSAGES.couldNotDetermineTypeOfEncodeMethodForClass(encoder);
}
 
Example #6
Source File: TestCloseBug58624.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute(
            Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

    ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(
            Bug58624ServerEndpoint.class, PATH).build();

    try {
        sc.addEndpoint(sec);
    } catch (DeploymentException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: Util.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public static List<DecoderEntry> getDecoders(
        List<Class<? extends Decoder>> decoderClazzes)
                throws DeploymentException{

    List<DecoderEntry> result = new ArrayList<>();
    if (decoderClazzes != null) {
        for (Class<? extends Decoder> decoderClazz : decoderClazzes) {
            // Need to instantiate decoder to ensure it is valid and that
            // deployment can be failed if it is not
            @SuppressWarnings("unused")
            Decoder instance;
            try {
                instance = decoderClazz.getConstructor().newInstance();
            } catch (ReflectiveOperationException e) {
                throw new DeploymentException(
                        sm.getString("pojoMethodMapping.invalidDecoder",
                                decoderClazz.getName()), e);
            }
            DecoderEntry entry = new DecoderEntry(
                    Util.getDecoderType(decoderClazz), decoderClazz);
            result.add(entry);
        }
    }

    return result;
}
 
Example #8
Source File: ServerEndpointExporter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void registerEndpoint(Class<?> endpointClass) {
	ServerContainer serverContainer = getServerContainer();
	Assert.state(serverContainer != null,
			"No ServerContainer set. Most likely the server's own WebSocket ServletContainerInitializer " +
			"has not run yet. Was the Spring ApplicationContext refreshed through a " +
			"org.springframework.web.context.ContextLoaderListener, " +
			"i.e. after the ServletContext has been fully initialized?");
	try {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering @ServerEndpoint class: " + endpointClass);
		}
		serverContainer.addEndpoint(endpointClass);
	}
	catch (DeploymentException ex) {
		throw new IllegalStateException("Failed to register @ServerEndpoint class: " + endpointClass, ex);
	}
}
 
Example #9
Source File: WsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private int parseStatus(String line) throws DeploymentException {
    // This client only understands HTTP 1.
    // RFC2616 is case specific
    String[] parts = line.trim().split(" ");
    // CONNECT for proxy may return a 1.0 response
    if (parts.length < 2 || !("HTTP/1.0".equals(parts[0]) || "HTTP/1.1".equals(parts[0]))) {
        throw new DeploymentException(sm.getString(
                "wsWebSocketContainer.invalidStatus", line));
    }
    try {
        return Integer.parseInt(parts[1]);
    } catch (NumberFormatException nfe) {
        throw new DeploymentException(sm.getString(
                "wsWebSocketContainer.invalidStatus", line));
    }
}
 
Example #10
Source File: TestWsWebSocketContainerGetOpenSessions.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);

    try {
        sc.addEndpoint(PojoEndpointA.class);
        sc.addEndpoint(PojoEndpointB.class);
        sc.addEndpoint(ServerEndpointConfig.Builder.create(
                ServerEndpointA.class, "/progA").build());
        sc.addEndpoint(ServerEndpointConfig.Builder.create(
                ServerEndpointB.class, "/progB").build());
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #11
Source File: WsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public Session connectToServer(Class<? extends Endpoint> clazz,
        ClientEndpointConfig clientEndpointConfiguration, URI path)
        throws DeploymentException {

    Endpoint endpoint;
    try {
        endpoint = clazz.getConstructor().newInstance();
    } catch (ReflectiveOperationException e) {
        throw new DeploymentException(sm.getString(
                "wsWebSocketContainer.endpointCreateFail", clazz.getName()),
                e);
    }

    return connectToServer(endpoint, clientEndpointConfiguration, path);
}
 
Example #12
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(ServerEndpointConfig.Builder.create(
                ConstantTxEndpoint.class, PATH).build());
        if (TestWsWebSocketContainer.timeoutOnContainer) {
            sc.setAsyncSendTimeout(TIMEOUT_MS);
        }
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #13
Source File: WsRemoteEndpointImplBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected void setEncoders(EndpointConfig endpointConfig)
        throws DeploymentException {
    encoderEntries.clear();
    for (Class<? extends Encoder> encoderClazz :
            endpointConfig.getEncoders()) {
        Encoder instance;
        try {
            instance = encoderClazz.getConstructor().newInstance();
            instance.init(endpointConfig);
        } catch (ReflectiveOperationException e) {
            throw new DeploymentException(
                    sm.getString("wsRemoteEndpoint.invalidEncoder",
                            encoderClazz.getName()), e);
        }
        EncoderEntry entry = new EncoderEntry(
                Util.getEncoderType(encoderClazz), instance);
        encoderEntries.add(entry);
    }
}
 
Example #14
Source File: AbstractTyrusRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #15
Source File: AbstractTyrusRequestUpgradeStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Object createEndpoint(ServerEndpointRegistration registration, ComponentProviderService provider,
		WebSocketContainer container, TyrusWebSocketEngine engine) throws DeploymentException {

	DirectFieldAccessor accessor = new DirectFieldAccessor(engine);
	Object sessionListener = accessor.getPropertyValue("sessionListener");
	Object clusterContext = accessor.getPropertyValue("clusterContext");
	try {
		if (constructorWithBooleanArgument) {
			// Tyrus 1.11+
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null, Boolean.TRUE);
		}
		else {
			return constructor.newInstance(registration.getEndpoint(), registration, provider, container,
					"/", registration.getConfigurator(), sessionListener, clusterContext, null);
		}
	}
	catch (Exception ex) {
		throw new HandshakeFailureException("Failed to register " + registration, ex);
	}
}
 
Example #16
Source File: TesterEchoServer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServerContainer sc =
            (ServerContainer) sce.getServletContext().getAttribute(
                    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
        sc.addEndpoint(Async.class);
        sc.addEndpoint(Basic.class);
        sc.addEndpoint(BasicLimitLow.class);
        sc.addEndpoint(BasicLimitHigh.class);
        sc.addEndpoint(WriterError.class);
        sc.addEndpoint(RootEcho.class);
    } catch (DeploymentException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #17
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #18
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Session connectToServer(final Endpoint endpointInstance, final ClientEndpointConfig config, final URI path) throws DeploymentException, IOException {
    if (closed) {
        throw new ClosedChannelException();
    }
    ClientEndpointConfig cec = config != null ? config : ClientEndpointConfig.Builder.create().build();

    SSLContext ssl = null;
    if (path.getScheme().equals("wss")) {
        for (WebsocketClientSslProvider provider : clientSslProviders) {
            ssl = provider.getSsl(eventLoopSupplier.get(), endpointInstance, cec, path);
            if (ssl != null) {
                break;
            }
        }
        if (ssl == null) {
            try {
                ssl = SSLContext.getDefault();
            } catch (NoSuchAlgorithmException e) {
                //ignore
            }
        }
    }
    //in theory we should not be able to connect until the deployment is complete, but the definition of when a deployment is complete is a bit nebulous.
    ClientNegotiation clientNegotiation = new ClientNegotiation(cec.getPreferredSubprotocols(), toExtensionList(cec.getExtensions()), cec);


    WebsocketConnectionBuilder connectionBuilder = new WebsocketConnectionBuilder(path, eventLoopSupplier.get())
            .setSsl(ssl)
            .setBindAddress(clientBindAddress)
            .setClientNegotiation(clientNegotiation);

    return connectToServer(endpointInstance, config, connectionBuilder);
}
 
Example #19
Source File: AbstractWebsocketClientEndpoint.java    From alpaca-java with MIT License 5 votes vote down vote up
/**
 * Connect.
 *
 * @throws DeploymentException the deployment exception
 * @throws IOException         Signals that an I/O exception has occurred.
 */
public void connect() throws DeploymentException, IOException {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    LOGGER.info("Connecting to " + endpointURI);

    container.connectToServer(this, endpointURI);
}
 
Example #20
Source File: MockServerContainer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Endpoint endpointInstance, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Endpoint, ClientEndpointConfig, URI)");
}
 
Example #21
Source File: ServerWebSocketContainer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void addEndpoint(final ServerEndpointConfig endpoint) throws DeploymentException {
    if (deploymentComplete) {
        throw JsrWebSocketMessages.MESSAGES.cannotAddEndpointAfterDeployment();
    }
    JsrWebSocketLogger.ROOT_LOGGER.addingProgramaticEndpoint(endpoint.getEndpointClass(), endpoint.getPath());
    final PathTemplate template = PathTemplate.create(endpoint.getPath());
    if (seenPaths.contains(template)) {
        PathTemplate existing = null;
        for (PathTemplate p : seenPaths) {
            if (p.compareTo(template) == 0) {
                existing = p;
                break;
            }
        }
        throw JsrWebSocketMessages.MESSAGES.multipleEndpointsWithOverlappingPaths(template, existing);
    }
    seenPaths.add(template);
    EncodingFactory encodingFactory = EncodingFactory.createFactory(classIntrospecter, endpoint.getDecoders(), endpoint.getEncoders());

    AnnotatedEndpointFactory annotatedEndpointFactory = null;
    if (!Endpoint.class.isAssignableFrom(endpoint.getEndpointClass())) {
        // We may want to check that the path in @ServerEndpoint matches the specified path, and throw if they are not equivalent
        annotatedEndpointFactory = AnnotatedEndpointFactory.create(endpoint.getEndpointClass(), encodingFactory, template.getParameterNames());
    }
    ConfiguredServerEndpoint confguredServerEndpoint = new ConfiguredServerEndpoint(endpoint, null, template, encodingFactory, annotatedEndpointFactory, endpoint.getExtensions());
    configuredServerEndpoints.add(confguredServerEndpoint);
    handleAddingFilterMapping();
}
 
Example #22
Source File: BinaryEndpointServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig c) throws ServletException {
    String websocketPath = "/partial";
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(BinaryPartialEndpoint.class, websocketPath).build();
    ServerContainer serverContainer = (ServerContainer) c.getServletContext().getAttribute("javax.websocket.server.ServerContainer");
    try {
        serverContainer.addEndpoint(config);
    } catch (DeploymentException ex) {
        throw new ServletException("Error deploying websocket endpoint:", ex);
    }
}
 
Example #23
Source File: PolygonWebsocketClient.java    From alpaca-java with MIT License 5 votes vote down vote up
@Override
public void connect() {
    LOGGER.info("Connecting...");

    try {
        polygonWebsocketClientEndpoint = new PolygonWebsocketClientEndpoint(this, new URI(websocketURL));
        polygonWebsocketClientEndpoint.connect();

        LOGGER.info("Connected.");
    } catch (URISyntaxException | DeploymentException | IOException e) {
        LOGGER.throwing(e);
    }
}
 
Example #24
Source File: MockServerContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)");
}
 
Example #25
Source File: BoundMethod.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
BoundMethod(final Method method, final Class<?> messageType, final boolean decoderRequired, long maxMessageSize, BoundParameter... params) throws DeploymentException {
    this.method = method;
    this.messageType = messageType;
    this.decoderRequired = decoderRequired;
    this.maxMessageSize = maxMessageSize;
    final Set<Integer> allParams = new HashSet<>();
    for (int i = 0; i < method.getParameterCount(); ++i) {
        allParams.add(i);
        paramTypes.add(method.getParameterTypes()[i]);
    }
    for (BoundParameter param : params) {
        parameters.add(param);
        allParams.removeAll(param.positions());
    }
    if (!allParams.isEmpty()) {
        //first check to see if the user has accidentally used the wrong PathParam annotation
        //and if so throw a more informative error message
        boolean wrongAnnotation = false;
        for (int i = 0; i < method.getParameterAnnotations().length; ++i) {
            for (int j = 0; j < method.getParameterAnnotations()[i].length; ++j) {
                Annotation annotation = method.getParameterAnnotations()[i][j];
                if (annotation.annotationType().getName().equals("javax.ws.rs.PathParam")) {
                    wrongAnnotation = true;
                }
            }
        }
        if (wrongAnnotation) {
            throw JsrWebSocketMessages.MESSAGES.invalidParametersWithWrongAnnotation(method, allParams);
        } else {
            throw JsrWebSocketMessages.MESSAGES.invalidParameters(method, allParams);
        }
    }
    method.setAccessible(true);
}
 
Example #26
Source File: ServerEndpointExporter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void registerEndpoint(ServerEndpointConfig endpointConfig) {
	ServerContainer serverContainer = getServerContainer();
	Assert.state(serverContainer != null, "No ServerContainer set");
	try {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering ServerEndpointConfig: " + endpointConfig);
		}
		serverContainer.addEndpoint(endpointConfig);
	}
	catch (DeploymentException ex) {
		throw new IllegalStateException("Failed to register ServerEndpointConfig: " + endpointConfig, ex);
	}
}
 
Example #27
Source File: TestWsWebSocketContainerGetOpenSessions.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private Session createSession(WebSocketContainer wsContainer, Endpoint client,
        String clientName, String server)
        throws DeploymentException, IOException, URISyntaxException {

    Session s = wsContainer.connectToServer(client,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://localhost:" + getPort() + server));
    Tracker.addRecord(clientName, s.getOpenSessions().size());
    s.getBasicRemote().sendText("X");
    return s;
}
 
Example #28
Source File: MockServerContainer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Session connectToServer(Class<? extends Endpoint> endpointClass, ClientEndpointConfig cec, URI path)
		throws DeploymentException, IOException {

	throw new UnsupportedOperationException(
			"MockServerContainer does not support connectToServer(Class, ClientEndpointConfig, URI)");
}
 
Example #29
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointNoHost() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #30
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test(expected = DeploymentException.class)
public void testDuplicatePaths24() throws Exception {
    WsServerContainer sc = new WsServerContainer(new TesterServletContext());

    ServerEndpointConfig configA = ServerEndpointConfig.Builder.create(
            Object.class, "/foo/{a}").build();

    sc.addEndpoint(PojoTemplate.class, true);
    sc.addEndpoint(configA);
}