javax.websocket.ClientEndpointConfig.Configurator Java Examples

The following examples show how to use javax.websocket.ClientEndpointConfig.Configurator. 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: WebsocketClient.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public WebsocketClient(String uri, final String sessionID, MessageHandler.Whole<String> messageHandler)
    throws IOException {

// add session ID so the request gets through LAMS security
Builder configBuilder = ClientEndpointConfig.Builder.create();
configBuilder.configurator(new Configurator() {
    @Override
    public void beforeRequest(Map<String, List<String>> headers) {
	headers.put("Cookie", Arrays.asList("JSESSIONID=" + sessionID));
    }
});
ClientEndpointConfig clientConfig = configBuilder.build();
this.websocketEndpoint = new WebsocketEndpoint(messageHandler);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
    container.connectToServer(websocketEndpoint, clientConfig, new URI(uri));
} catch (DeploymentException | URISyntaxException e) {
    throw new IOException("Error while connecting to websocket server", e);
}
   }
 
Example #2
Source File: TestWebSocketFrameClient.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterFirehoseServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    // BZ 62596
    final StringBuilder dummyValue = new StringBuilder(4000);
    for (int i = 0; i < 4000; i++) {
        dummyValue.append('A');
    }
    ClientEndpointConfig clientEndpointConfig =
            ClientEndpointConfig.Builder.create().configurator(new Configurator() {
                @Override
                public void beforeRequest(Map<String, List<String>> headers) {
                    headers.put("Dummy", Collections.singletonList(dummyValue.toString()));
                    super.beforeRequest(headers);
                }
            }).build();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            clientEndpointConfig,
            new URI("ws://localhost:" + getPort() +
                    TesterFirehoseServer.Config.PATH));
    CountDownLatch latch =
            new CountDownLatch(TesterFirehoseServer.MESSAGE_COUNT);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText("Hello");

    System.out.println("Sent Hello message, waiting for data");

    // Ignore the latch result as the message count test below will tell us
    // if the right number of messages arrived
    handler.getLatch().await(TesterFirehoseServer.WAIT_TIME_MILLIS,
            TimeUnit.MILLISECONDS);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(
            TesterFirehoseServer.MESSAGE_COUNT, messages.size());
    for (String message : messages) {
        Assert.assertEquals(TesterFirehoseServer.MESSAGE, message);
    }
}
 
Example #3
Source File: StandardWebSocketClient.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private ClientEndpointConfig createEndpointConfig(Configurator configurator, List<String> subProtocols) {
	return ClientEndpointConfig.Builder.create()
			.configurator(configurator)
			.preferredSubprotocols(subProtocols)
			.build();
}
 
Example #4
Source File: EndpointConnectionManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public void setConfigurator(Configurator configurator) {
	this.configBuilder.configurator(configurator);
}
 
Example #5
Source File: FHIRNotificationServiceClientEndpoint.java    From FHIR with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int limit = 5;
    int timeout = 5;
    TimeUnit timeUnit = TimeUnit.MINUTES;

    System.out.println("Connecting to server...");
    System.out.println("");

    FHIRNotificationServiceClientEndpoint endpoint =
            new FHIRNotificationServiceClientEndpoint();

    ClientEndpointConfig config =
            ClientEndpointConfig.Builder.create().configurator(new Configurator() {
                public void beforeRequest(Map<String, List<String>> headers) {
                    String encoding =
                            Base64.getEncoder().encodeToString("fhiruser:change-password".getBytes());
                    List<String> values = new ArrayList<String>();
                    values.add("Basic " + encoding);
                    headers.put("Authorization", values);
                }
            }).build();

    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    container.connectToServer(endpoint, config, new URI("ws://localhost:9080/fhir-server/api/v4/notification"));
    System.out.println("");
    System.out.println("Connected.");
    System.out.println("");

    String text = "event";
    if (limit > 1) {
        text += "s";
    }

    String unit = timeUnit.toString().toLowerCase();
    unit = unit.substring(0, unit.length() - 1);

    System.out.println("Waiting for " + limit + " " + text + " or " + timeout + " " + unit
            + " timeout period...");
    System.out.println("");

    boolean result = endpoint.getLatch().await(timeout, timeUnit);
    if (result) {
        System.out.println("");
        System.out.println("Disconnected.");
        System.out.println("");
    } else {
        System.out.println(timeout + " " + unit + " timeout period expired.");
        System.out.println("");
    }

    List<String> events = endpoint.getEvents();

    if (events.size() == 0) {
        text = "no events.";
    } else if (events.size() == 1) {
        text = "the following event:";
    } else {
        text = "the following " + events.size() + " events:";
    }

    System.out.println("Client received " + text);
    System.out.println("");
    for (String event : events) {
        FHIRNotificationEvent notifyEvent = FHIRNotificationUtil.toNotificationEvent(event);
        System.out.println("    location:      " + notifyEvent.getLocation());
        System.out.println("    operationType: " + notifyEvent.getOperationType());
        System.out.println("    lastUpdated:   " + notifyEvent.getLastUpdated());
        System.out.println("    resourceId:    " + notifyEvent.getResourceId());
        System.out.println("");
    }
}
 
Example #6
Source File: FHIRServerTestBase.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and returns an "endpoint" to be used to receive notifications via a
 * websocket.
 */
protected FHIRNotificationServiceClientEndpoint getWebsocketClientEndpoint() {
    try {
        FHIRNotificationServiceClientEndpoint endpoint = new FHIRNotificationServiceClientEndpoint();
        ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(new Configurator() {
            @Override
            public void beforeRequest(Map<String, List<String>> headers) {
                String userpw = getFhirUser() + ":" + getFhirPassword();
                String encoding = Base64.getEncoder().encodeToString(userpw.getBytes());
                List<String> values = new ArrayList<String>();
                values.add("Basic " + encoding);
                headers.put("Authorization", values);
            }
        }).build();

        String webSocketURL = getWebSocketURL();
        if (webSocketURL.startsWith("wss")) {
            String tsLoc = getAbsoluteFilename(getTsLocation());
            if (tsLoc == null) {
                throw new FileNotFoundException("Truststore file not found: " + getTsLocation());
            }

            String ksLoc = getAbsoluteFilename(getKsLocation());
            if (ksLoc == null) {
                throw new FileNotFoundException("Keystore file not found: " + getKsLocation());
            }

            System.getProperties().put(SslContextConfigurator.KEY_STORE_FILE, ksLoc);
            System.getProperties().put(SslContextConfigurator.KEY_STORE_PASSWORD, getKsPassword());
            System.getProperties().put(SslContextConfigurator.TRUST_STORE_FILE, tsLoc);
            System.getProperties().put(SslContextConfigurator.TRUST_STORE_PASSWORD, getTsPassword());

            final SslContextConfigurator defaultConfig = new SslContextConfigurator();
            defaultConfig.retrieve(System.getProperties());
            SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(defaultConfig, true, false,
                    false);
            sslEngineConfigurator.setHostVerificationEnabled(false);
            config.getUserProperties().put(PROPNAME_SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator);

        }
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        Session session = container.connectToServer(endpoint, config, new URI(webSocketURL));

        // Add a Delay
        int count = 10;
        while ( !session.isOpen() && count > 0) {
            System.out.println(">>> " + count + " waiting");
            Thread.sleep(1000l);
            count--;
        }

        endpoint.setSession(session);
        return endpoint;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #7
Source File: StandardWebSocketClient.java    From java-technology-stack with MIT License 4 votes vote down vote up
private ClientEndpointConfig createEndpointConfig(Configurator configurator, List<String> subProtocols) {
	return ClientEndpointConfig.Builder.create()
			.configurator(configurator)
			.preferredSubprotocols(subProtocols)
			.build();
}
 
Example #8
Source File: EndpointConnectionManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
public void setConfigurator(Configurator configurator) {
	this.configBuilder.configurator(configurator);
}
 
Example #9
Source File: EndpointConnectionManager.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public void setConfigurator(Configurator configurator) {
	this.configBuilder.configurator(configurator);
}