Example usage for org.springframework.core.env StandardEnvironment StandardEnvironment

List of usage examples for org.springframework.core.env StandardEnvironment StandardEnvironment

Introduction

In this page you can find the example usage for org.springframework.core.env StandardEnvironment StandardEnvironment.

Prototype

StandardEnvironment

Source Link

Usage

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPS() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    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 {/*from ww w.  ja v a  2 s. c o  m*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new X509HostnameVerifier() {
                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }

                    @Override
                    public void verify(String host, X509Certificate cert) throws SSLException {
                    }

                    @Override
                    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    }

                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        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("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.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("https://localhost:" + properties.get("https.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("https://localhost:" + properties.get("https.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);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.shared.SharedTest.java

@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 {//from  w w w . j av a  2s  .c o m
        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();
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);//from ww w.j a v a  2s. co m
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));

    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(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry,
                context.getBean(WebSocketPskFrameProcessor.class));

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() 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("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    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 {//w  w  w  . j  av a2s .c  o  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new X509HostnameVerifier() {
                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }

                    @Override
                    public void verify(String host, X509Certificate cert) throws SSLException {
                    }

                    @Override
                    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    }

                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory()).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        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("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.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("https://localhost:" + properties.get("https.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("https://localhost:" + properties.get("https.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);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        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);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJsonWithWss() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("secureWebsocket.enabled", "true");
    properties.put("secureWebsocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("secureWebsocket.hostname", "localhost");
    properties.put("secureWebsocket.selfSigned", "true");

    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(TestWebSocketService.class);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustAll(true);

    WebSocketClient wsClient = new WebSocketClient(sslContextFactory);

    try {/* w ww .  j ava 2s.c om*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

        Session session = wsClient.connect(webSocket, new URI("wss://localhost:"
                + properties.get("secureWebsocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithProtobuf() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    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(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {//from  www .jav  a2  s  .  c om
        context.refresh();

        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
            while (context.isActive()) {
                Thread.sleep(100);
            }
        }
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@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 {/*from  www  .j a  va2  s . c  o m*/
        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();
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithXml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    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(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {/* w  w  w  .ja  va 2 s.c  o  m*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(XmlMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5000, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
            while (context.isActive()) {
                Thread.sleep(100);
            }
        }
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithXml() 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", "false");
    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 {//from   w ww  .ja va  2  s.  co m
        context.refresh();

        final MessageSerDe serDe = context.getBean(XmlMessageSerDe.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);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithYaml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    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(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {//from  ww  w .j a  v a 2 s.c o m
        context.refresh();

        final MessageSerDe serDe = context.getBean(YamlJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
            while (context.isActive()) {
                Thread.sleep(100);
            }
        }
    }
}