Search in sources :

Example 1 with MessageSerDe

use of com.kixeye.chassis.transport.serde.MessageSerDe in project chassis by Kixeye.

the class WebSocketTransportConfiguration method webSocketServer.

@Bean(initMethod = "start", destroyMethod = "stop")
@Order(0)
public Server webSocketServer(@Value("${websocket.enabled:false}") boolean websocketEnabled, @Value("${websocket.hostname:}") String websocketHostname, @Value("${websocket.port:-1}") int websocketPort, @Value("${secureWebsocket.enabled:false}") boolean secureWebsocketEnabled, @Value("${secureWebsocket.hostname:}") String secureWebsocketHostname, @Value("${secureWebsocket.port:-1}") int secureWebsocketPort, @Value("${secureWebsocket.selfSigned:false}") boolean selfSigned, @Value("${secureWebsocket.mutualSsl:false}") boolean mutualSsl, @Value("${secureWebsocket.keyStorePath:}") String keyStorePath, @Value("${secureWebsocket.keyStoreData:}") String keyStoreData, @Value("${secureWebsocket.keyStorePassword:}") String keyStorePassword, @Value("${secureWebsocket.keyManagerPassword:}") String keyManagerPassword, @Value("${secureWebsocket.trustStorePath:}") String trustStorePath, @Value("${secureWebsocket.trustStoreData:}") String trustStoreData, @Value("${secureWebsocket.trustStorePassword:}") String trustStorePassword, @Value("${securewebsocket.excludedCipherSuites:}") String[] excludedCipherSuites) throws Exception {
    // set up servlets
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });
    for (final MessageSerDe serDe : serDes) {
        // create the websocket creator
        final WebSocketCreator webSocketCreator = new WebSocketCreator() {

            public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
                // this will have spring construct a new one for every session
                ActionInvokingWebSocket webSocket = forwardingWebSocket();
                webSocket.setSerDe(serDe);
                webSocket.setUpgradeRequest(req);
                webSocket.setUpgradeResponse(resp);
                return webSocket;
            }
        };
        // configure the websocket servlet
        ServletHolder webSocketServlet = new ServletHolder(new WebSocketServlet() {

            private static final long serialVersionUID = -3022799271546369505L;

            @Override
            public void configure(WebSocketServletFactory factory) {
                factory.setCreator(webSocketCreator);
            }
        });
        Map<String, String> webSocketProperties = new HashMap<>();
        AbstractConfiguration config = ConfigurationManager.getConfigInstance();
        Iterator<String> webSocketPropertyKeys = config.getKeys("websocket");
        while (webSocketPropertyKeys.hasNext()) {
            String key = webSocketPropertyKeys.next();
            webSocketProperties.put(key.replaceFirst(Pattern.quote("websocket."), ""), config.getString(key));
        }
        webSocketServlet.setInitParameters(webSocketProperties);
        context.addServlet(webSocketServlet, "/" + serDe.getMessageFormatName() + "/*");
    }
    // create the server
    Server server;
    if (metricRegistry == null || !monitorThreadpool) {
        server = new Server();
        server.setHandler(context);
    } else {
        server = new Server(new InstrumentedQueuedThreadPool(metricRegistry));
        InstrumentedHandler instrumented = new InstrumentedHandler(metricRegistry);
        instrumented.setHandler(context);
        server.setHandler(instrumented);
    }
    // set up connectors
    if (websocketEnabled) {
        InetSocketAddress address = StringUtils.isBlank(websocketHostname) ? new InetSocketAddress(websocketPort) : new InetSocketAddress(websocketHostname, websocketPort);
        JettyConnectorRegistry.registerHttpConnector(server, address);
    }
    if (secureWebsocketEnabled) {
        InetSocketAddress address = StringUtils.isBlank(secureWebsocketHostname) ? new InetSocketAddress(secureWebsocketPort) : new InetSocketAddress(secureWebsocketHostname, secureWebsocketPort);
        JettyConnectorRegistry.registerHttpsConnector(server, address, selfSigned, mutualSsl, keyStorePath, keyStoreData, keyStorePassword, keyManagerPassword, trustStorePath, trustStoreData, trustStorePassword, excludedCipherSuites);
    }
    return server;
}
Also used : InstrumentedHandler(com.kixeye.chassis.transport.http.InstrumentedHandler) WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) InetSocketAddress(java.net.InetSocketAddress) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketServlet(org.eclipse.jetty.websocket.servlet.WebSocketServlet) ServletUpgradeResponse(org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse) AbstractConfiguration(org.apache.commons.configuration.AbstractConfiguration) InstrumentedQueuedThreadPool(com.codahale.metrics.jetty9.InstrumentedQueuedThreadPool) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServletUpgradeRequest(org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest) Order(org.springframework.core.annotation.Order) Bean(org.springframework.context.annotation.Bean)

Example 2 with MessageSerDe

use of com.kixeye.chassis.transport.serde.MessageSerDe in project chassis by Kixeye.

the class HttpTransportTest method testHttpServiceWithProtobuf.

@Test
public void testHttpServiceWithProtobuf() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);
    try {
        context.refresh();
        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);
        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {

            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));
        TestObject response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        ResponseEntity<ServiceError> error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/headerRequired"), null, ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) IOException(java.io.IOException) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Example 3 with MessageSerDe

use of com.kixeye.chassis.transport.serde.MessageSerDe in project chassis by Kixeye.

the class SharedTest method testAdminLinks.

@Test
public void testAdminLinks() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("admin.enabled", "true");
    properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("admin.hostname", "localhost");
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(MetricsConfiguration.class);
    RestTemplate httpClient = new RestTemplate();
    try {
        context.refresh();
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);
        ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/admin/index.html"), String.class);
        logger.info("Got response: [{}]", response);
        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/ping\">Ping</a>"));
        Assert.assertTrue(response.getBody().contains("<a href=\"/healthcheck\">Healthcheck</a>"));
        Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/metrics?pretty=true\">Metrics</a>"));
        Assert.assertTrue(response.getBody().contains("<a href=\"/admin/properties\">Properties</a>"));
        Assert.assertTrue(response.getBody().contains("<a href=\"/metrics/threads\">Threads</a>"));
        Assert.assertTrue(response.getBody().contains("<a href=\"/admin/classpath\">Classpath</a>"));
    } finally {
        context.close();
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Example 4 with MessageSerDe

use of com.kixeye.chassis.transport.serde.MessageSerDe in project chassis by Kixeye.

the class SharedTest method testSwagger.

@Test
public void testSwagger() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("admin.enabled", "true");
    properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("admin.hostname", "localhost");
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(MetricsConfiguration.class);
    RestTemplate httpClient = new RestTemplate();
    try {
        context.refresh();
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);
        ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/swagger/index.html"), String.class);
        logger.info("Got response: [{}]", response);
        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertTrue(response.getBody().contains("<title>Swagger UI</title>"));
    } finally {
        context.close();
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Example 5 with MessageSerDe

use of com.kixeye.chassis.transport.serde.MessageSerDe in project chassis by Kixeye.

the class SharedTest method testHealthcheck.

@Test
public void testHealthcheck() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("admin.enabled", "true");
    properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("admin.hostname", "localhost");
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(MetricsConfiguration.class);
    RestTemplate httpClient = new RestTemplate();
    try {
        context.refresh();
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);
        ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("admin.port") + "/healthcheck"), String.class);
        logger.info("Got response: [{}]", response);
        Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
        Assert.assertEquals("OK", response.getBody());
    } finally {
        context.close();
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Test(org.junit.Test)

Aggregations

MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)22 HashMap (java.util.HashMap)22 URI (java.net.URI)21 Test (org.junit.Test)21 MapPropertySource (org.springframework.core.env.MapPropertySource)21 StandardEnvironment (org.springframework.core.env.StandardEnvironment)21 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)21 ProtobufMessageSerDe (com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe)15 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)14 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)14 XmlMessageSerDe (com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe)14 YamlJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe)14 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)13 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)13 RestTemplate (org.springframework.web.client.RestTemplate)13 QueuingWebSocketListener (com.kixeye.chassis.transport.websocket.QueuingWebSocketListener)9 WebSocketMessageRegistry (com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry)9 WebSocketClient (org.eclipse.jetty.websocket.client.WebSocketClient)9 WebSocketSession (org.eclipse.jetty.websocket.common.WebSocketSession)8 Envelope (com.kixeye.chassis.transport.dto.Envelope)7