Example usage for org.springframework.http.converter StringHttpMessageConverter StringHttpMessageConverter

List of usage examples for org.springframework.http.converter StringHttpMessageConverter StringHttpMessageConverter

Introduction

In this page you can find the example usage for org.springframework.http.converter StringHttpMessageConverter StringHttpMessageConverter.

Prototype

public StringHttpMessageConverter(Charset defaultCharset) 

Source Link

Document

A constructor accepting a default charset to use if the requested content type does not specify one.

Usage

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 ww . j a v  a  2  s .  c om
        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.playhaven.android.req.PlayHavenRequest.java

public void send(final Context context) {
    final StringHttpMessageConverter stringHttpMessageConverter;

    try {//from ww  w . j  a v  a2 s.c  o  m
        /**
        * Charset.availableCharsets() called by StringHttpMessageConverter constructor is not multi-thread safe.
        * Calling it on the main thread to avoid a possible crash.
        * More details here: https://code.google.com/p/android/issues/detail?id=42769
        */
        stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName(UTF8));
    } catch (Exception e) {
        handleResponse(new PlayHavenException(e.getMessage()));
        return;
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /**
                 * First, check if we are mocking the URL
                 */
                String mockJsonResponse = getMockJsonResponse();
                if (mockJsonResponse != null) {
                    /**
                     * Mock the response
                     */
                    PlayHaven.v("Mock Response: %s", mockJsonResponse);
                    handleResponse(mockJsonResponse);
                    return;
                }

                /**
                 * Not mocking the response. Do an actual server call.
                 */
                String url = getUrl(context);
                PlayHaven.v("Request(%s) %s: %s", PlayHavenRequest.this.getClass().getSimpleName(), restMethod,
                        url);

                // Add the gzip Accept-Encoding header
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

                // Create our REST handler
                RestTemplate rest = new RestTemplate();
                rest.setErrorHandler(new ServerErrorHandler());

                // Capture the JSON for signature verification
                rest.getMessageConverters().add(stringHttpMessageConverter);

                ResponseEntity<String> entity = null;

                switch (restMethod) {
                case POST:
                    SharedPreferences pref = PlayHaven.getPreferences(context);
                    String apiServer = getString(pref, APIServer)
                            + context.getResources().getString(getApiPath(context));
                    url = url.replace(apiServer, "");
                    if (url.startsWith("?") && url.length() > 1)
                        url = url.substring(1);

                    requestHeaders.setContentType(new MediaType("application", "x-www-form-urlencoded"));
                    entity = rest.exchange(apiServer, restMethod, new HttpEntity<>(url, requestHeaders),
                            String.class);
                    break;
                default:
                    entity = rest.exchange(url, restMethod, new HttpEntity<>(requestHeaders), String.class);
                    break;
                }

                String json = entity.getBody();

                List<String> digests = entity.getHeaders().get("X-PH-DIGEST");
                String digest = (digests == null || digests.size() == 0) ? null : digests.get(0);

                validateSignatures(context, digest, json);

                HttpStatus statusCode = entity.getStatusCode();
                PlayHaven.v("Response (%s): %s", statusCode, json);

                serverSuccess(context);
                handleResponse(json);
            } catch (PlayHavenException e) {
                handleResponse(e);
            } catch (IOException e2) {
                handleResponse(new PlayHavenException(e2));
            } catch (Exception e3) {
                handleResponse(new PlayHavenException(e3.getMessage()));
            }
        }
    }).start();
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);

    HttpClient httpClient = null;/* www. j a  va2s .  com*/
    if (livyURL.startsWith("https:")) {
        String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
        String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            RequestConfig reqConfig = new RequestConfig() {
                @Override
                public boolean isAuthenticationEnabled() {
                    return true;
                }
            };
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            Credentials credentials = new Credentials() {
                @Override
                public String getPassword() {
                    return null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return null;
                }
            };
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            if (isSpnegoEnabled) {
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder
                        .<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }

    RestTemplate restTemplate = null;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static Map<String, Object> getPasswordToken(String baseUrl, String clientId, String clientSecret,
        String username, String password, String scopes) throws Exception {
    RestTemplate template = new RestTemplate();
    template.getMessageConverters().add(0,
            new StringHttpMessageConverter(java.nio.charset.Charset.forName("UTF-8")));
    template.setRequestFactory(new StatelessRequestFactory());
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("grant_type", "password");
    formData.add("client_id", clientId);
    formData.add("username", username);
    formData.add("password", password);
    formData.add("response_type", "token id_token");
    if (StringUtils.hasText(scopes)) {
        formData.add("scope", scopes);
    }//from  w  ww . java  2  s  .c  o m
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes())));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = template.exchange(baseUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity(formData, headers), Map.class);

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
    return response.getBody();
}