Example usage for org.springframework.http.client ClientHttpResponse getStatusCode

List of usage examples for org.springframework.http.client ClientHttpResponse getStatusCode

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpResponse getStatusCode.

Prototype

HttpStatus getStatusCode() throws IOException;

Source Link

Document

Return the HTTP status code as an HttpStatus enum value.

Usage

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java

/**
 * {@inheritDoc}// w  w w.  j av a  2 s.c  o  m
 */
@Override
public void deleteByReference(final EnricherJob job, final String field, final String[] documents)
        throws Exception {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    XContentBuilder builder = XContentFactory.jsonBuilder(outputStream);

    try {
        builder.startObject();

        builder.startObject("bool");
        builder.startArray("should");

        for (String document : documents) {
            builder.startObject();

            builder.startObject("match");
            builder.field(field, document);
            builder.endObject();

            builder.endObject();
        }

        builder.endArray();
        builder.endObject();

        builder.endObject();

        builder.flush();

        // Then post the result

        String queryUri = format("http://%s/%s/%s/_query", getElasticSearchUri(), job.getDatabaseName(),
                job.getDatabaseType());

        HttpStatus status = operations.execute(queryUri, HttpMethod.DELETE, new RequestCallback() {
            @Override
            public void doWithRequest(final ClientHttpRequest request) throws IOException {
                request.getBody().write(outputStream.toByteArray());
            }
        }, new ResponseExtractor<HttpStatus>() {
            @Override
            public HttpStatus extractData(final ClientHttpResponse response) throws IOException {
                return response.getStatusCode();
            }
        }, null);

        if (status.value() == HttpStatus.OK.value())
            logger.info(format("Successfully removed document(s) from ElasticSearch"));
        else
            logger.error(
                    format("Failed to delete document(s) from ElasticSearch %s", status.getReasonPhrase()));
    } finally {
        builder.close();
    }
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java

/**
 * {@inheritDoc}//www  .ja  v a2 s  . c o m
 */
@Override
public void upload(final EnricherJob job, final GeneratorResult result) throws Exception {
    String indexCollection = job.getDatabaseName();

    // Create a new update request

    List<Map<String, Object>> documents = ((MultiGeneratorResult<Map<String, Object>>) result).getDocuments();

    // Set a collection in case of a (resolvable) composite database name

    if (StringUtils.hasText(job.getDatabaseNameComposition())) {
        String compositeDatabaseName = determineAlternateDatabaseName(job.getDatabaseName(),
                job.getDatabaseNameComposition(), job.getDatabaseNamePrerequisitesExpression(),
                ((MultiGeneratorResult<Map<String, Object>>) result).getDocuments());

        if (compositeDatabaseName != null) {
            if (logger.isDebugEnabled())
                logger.debug(
                        format("Composite database name resolved to collection '%s'", compositeDatabaseName));

            indexCollection = compositeDatabaseName;
        } else {
            if (logger.isDebugEnabled())
                logger.debug(format(
                        "Composite database name could not be (completely) resolved - will use default collection '%s'",
                        job.getDatabaseName()));
        }
    }

    // Now perform the request

    String elasticSearchUri = getElasticSearchUri();

    ElasticSearchDomainConverter converter = new ElasticSearchDomainConverter(
            retrieveMetaData(elasticSearchUri, job));

    // Bulk it all together

    for (Map<String, Object> document : documents) {
        Map<String, Object> actualDocument = converter.convert(document);

        // Then add it to the index

        final String id = getReference(actualDocument);

        String encodedId = URLEncoder.encode(getReference(actualDocument), "UTF-8");
        String formattedUri = format("http://%s/%s/%s/%s", elasticSearchUri, indexCollection,
                job.getDatabaseType(), encodedId);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            XContentBuilder builder = XContentFactory.jsonBuilder(outputStream);

            try {
                builder.map(actualDocument);

                builder.flush();

                // Now send it on its way

                final String content = new String(outputStream.toByteArray(), "UTF-8");

                if (logger.isTraceEnabled())
                    logger.trace(format("Posting document to URL %s ... %s", formattedUri, content));

                HttpStatus status = operations.execute(formattedUri, HttpMethod.PUT, new RequestCallback() {
                    @Override
                    public void doWithRequest(final ClientHttpRequest request) throws IOException {
                        request.getBody().write(content.getBytes());
                    }
                }, new ResponseExtractor<HttpStatus>() {
                    @Override
                    public HttpStatus extractData(final ClientHttpResponse response) throws IOException {
                        return response.getStatusCode();
                    }
                });

                if (status.equals(HttpStatus.OK) || status.equals(HttpStatus.CREATED))
                    logger.info(format("Successfully added document %s to ElasticSearch index %s", id,
                            indexCollection));
                else
                    logger.error(
                            format("Failed to add document %s to ElasticSearch index %s", id, indexCollection));
            } finally {
                builder.close();
            }
        } catch (RestClientException e) {
            logger.error(format("Failed to add document %s to ElasticSearch index %s", id, indexCollection), e);
        } catch (ElasticSearchException e) {
            logger.error(format("Failed to add document %s to ElasticSearch index %s", id, indexCollection), e);
        }
    }

    // Perform direct notification now that the document(s) have been uploaded

    notifier.process(result);
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

public RemoteUaaController(Environment environment, RestTemplate restTemplate) {

    // The default java.net client doesn't allow you to handle 4xx responses
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override/*w w w .j a  v  a  2  s  .c om*/
        public HttpClient getHttpClient() {
            return HttpClientBuilder.create().useSystemProperties().disableCookieManagement().build();
        }
    });
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            HttpStatus statusCode = response.getStatusCode();
            return statusCode.series() == HttpStatus.Series.SERVER_ERROR;
        }
    });
    this.environment = environment;
    defaultTemplate = restTemplate;
    initProperties();
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

private void verifyAuthorizationPage(OAuth2RestTemplate restTemplate, String location) {
    final AtomicReference<String> confirmationPage = new AtomicReference<String>();
    AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider() {
        @Override//w  ww.  j a  va2s  .  c om
        protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
            return new ResponseExtractor<ResponseEntity<Void>>() {
                public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
                    confirmationPage
                            .set(StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")));
                    return new ResponseEntity<Void>(response.getHeaders(), response.getStatusCode());
                }
            };
        }
    };
    try {
        provider.obtainAuthorizationCode(restTemplate.getResource(),
                restTemplate.getOAuth2ClientContext().getAccessTokenRequest());
    } catch (UserApprovalRequiredException e) {
        // ignore
    }
    String page = confirmationPage.get();
    verifyAuthorizationPage(page);
}

From source file:com.gooddata.dataload.processes.ProcessService.java

/**
 * Run given execution under given process
 *
 * @param execution to run//from   ww  w  .  java 2 s .  co  m
 * @return result of the execution
 * @throws com.gooddata.dataload.processes.ProcessExecutionException in case process can't be executed
 */
public FutureResult<ProcessExecutionDetail> executeProcess(ProcessExecution execution) {
    notNull(execution, "execution");
    ProcessExecutionTask executionTask;
    try {
        executionTask = restTemplate.postForObject(execution.getExecutionsUri(), execution,
                ProcessExecutionTask.class);
    } catch (GoodDataException | RestClientException e) {
        throw new ProcessExecutionException("Cannot execute process", e);
    }

    if (executionTask == null) {
        throw new ProcessExecutionException("Cannot find started execution.");
    }

    final String detailLink = executionTask.getDetailUri();

    return new PollResult<>(this, new AbstractPollHandler<Void, ProcessExecutionDetail>(
            executionTask.getPollUri(), Void.class, ProcessExecutionDetail.class) {
        @Override
        public boolean isFinished(ClientHttpResponse response) throws IOException {
            return HttpStatus.NO_CONTENT.equals(response.getStatusCode());
        }

        @Override
        public void handlePollResult(Void pollResult) {
            final ProcessExecutionDetail executionDetail = getProcessExecutionDetailByUri(detailLink);
            if (!executionDetail.isSuccess()) {
                throw new ProcessExecutionException("Execution was not successful", executionDetail);
            } else {
                setResult(executionDetail);
            }
        }

        @Override
        public void handlePollException(final GoodDataRestException e) {
            ProcessExecutionDetail detail = null;
            try {
                detail = getProcessExecutionDetailByUri(detailLink);
            } catch (GoodDataException ignored) {
            }
            throw new ProcessExecutionException("Can't execute " + e.getText(), detail, e);
        }

        private ProcessExecutionDetail getProcessExecutionDetailByUri(final String uri) {
            try {
                return restTemplate.getForObject(uri, ProcessExecutionDetail.class);
            } catch (GoodDataException | RestClientException e) {
                throw new ProcessExecutionException("Execution finished, but cannot get its result.", e, uri);
            }
        }

    });
}

From source file:org.intermine.app.net.ServerErrorHandler.java

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    InputStream inputStream = response.getBody();
    String body = Strs.nullToEmpty(IOUtils.toString(inputStream, DEFAULT_ENCODING));
    String errorMessage = null;/*from  ww w.  j a v a2  s . c  o m*/

    try {
        Map<String, String> map = mMapper.fromJson(body, Map.class);

        if (null != map) {
            errorMessage = map.get(ERROR_KEY);
        }
    } catch (JsonSyntaxException ex) {
    }

    HttpNetworkException e = new HttpNetworkException(response.getStatusText());
    e.setErrorMessage(Strs.isNullOrEmpty(errorMessage) ? body : errorMessage);
    e.setHeaders(response.getHeaders());
    e.setStatusCode(response.getStatusCode());
    throw e;
}

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

private byte[] receiveDataBuffered(long page) {
    final String dataUrl = url + this.tunnelInfo.get("path_out") + "/" + page;
    byte[] responseBytes;
    try {/* ww  w.  j  av a2s  .  c  o m*/
        responseBytes = restOperations.execute(dataUrl, HttpMethod.GET, new RequestCallback() {
            public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                clientHttpRequest.getHeaders().set("Auth-Token", auth);
            }
        }, new ResponseExtractor<byte[]>() {
            public byte[] extractData(ClientHttpResponse clientHttpResponse) throws IOException {
                if (logger.isDebugEnabled()) {
                    logger.debug("HEADER: " + clientHttpResponse.getHeaders().toString());
                }
                InputStream stream = clientHttpResponse.getBody();
                byte[] data = readContentData(stream);
                if (logger.isDebugEnabled()) {
                    logger.debug("[" + data.length + " bytes] GET from " + dataUrl + " resulted in: "
                            + clientHttpResponse.getStatusCode());
                }
                return data;
            }
        });
    } catch (HttpStatusCodeException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("GET from " + dataUrl + " resulted in: " + e.getStatusCode().value());
        }
        throw e;
    }
    return responseBytes;
}

From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java

private void assertContent(String scheme, String url, int port, Object expected) throws Exception {

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);/*  www  . jav  a 2  s .  co m*/
    ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url),
            HttpMethod.GET);
    try {
        ClientHttpResponse response = request.execute();
        if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
            throw new FileNotFoundException();
        }
        try {
            String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
            if (expected instanceof Matcher) {
                assertThat(actual).is(Matched.by((Matcher<?>) expected));
            } else {
                assertThat(actual).isEqualTo(expected);
            }
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        if (expected == null) {
            if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
                return;
            }
        }
        throw ex;
    }
}