List of usage examples for org.springframework.http HttpStatus equals
public boolean equals(Object obj)
From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java
/** * {@inheritDoc}// w ww.j a va 2 s . com */ @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.apache.fineract.restwebservice.PlatformRestClient.java
/** * Executes a HTTP request using the spring framework RestTemplate * //from www . j ava2s.c o m * @param url the URL * @param method the HTTP method (GET, POST, etc) * @param requestEntity the entity (headers and/or body) to write to the request, may be null * @param responseType the type of the return value * @return the response as entity * @throws InterruptedException * @throws RestClientException */ public <T> ResponseEntity<T> executeHttpRequest(final URI url, final HttpMethod method, final HttpEntity<?> requestEntity, final Class<T> responseType) { final RestTemplate restTemplate = new RestTemplate(); HttpStatus statusCode = null; ResponseEntity<T> responseEntity = null; // increment the number of request attempts by 1 this.numberOfHttpRequestAttempts++; try { // execute the HTTP request responseEntity = restTemplate.exchange(url, method, requestEntity, responseType); statusCode = responseEntity.getStatusCode(); // catch all server HTTP error exceptions } catch (HttpServerErrorException exception) { statusCode = exception.getStatusCode(); // if HTTP status is 503 or 504, sleep for 5 seconds and retry if ((statusCode.equals(HttpStatus.SERVICE_UNAVAILABLE) || statusCode.equals(HttpStatus.GATEWAY_TIMEOUT)) && (this.numberOfHttpRequestAttempts < this.numberOfHttpRequestRetries)) { logger.info("Server returned an error response with status: " + statusCode + ", retrying again in 5 seconds"); logger.info("Number of attempts: " + this.numberOfHttpRequestAttempts); try { // sleep for 5 seconds and try again Thread.sleep(5000); } catch (InterruptedException interruptedException) { logger.error(interruptedException.getMessage(), interruptedException); } // execute HTTP request again this.executeHttpRequest(url, method, requestEntity, responseType); } else { // in other cases, throw back the exception throw exception; } } return responseEntity; }
From source file:org.springframework.social.linkedin.api.impl.LinkedInErrorHandler.java
@Override public void handleError(ClientHttpResponse response) throws IOException { Map<String, Object> errorDetails = extractErrorDetailsFromResponse(response); String message = (String) errorDetails.get("message"); HttpStatus statusCode = response.getStatusCode(); if (statusCode.equals(HttpStatus.UNAUTHORIZED)) { throw new NotAuthorizedException("linkedIn", message); } else if (statusCode.equals(HttpStatus.FORBIDDEN)) { if (message.contains("Throttle")) { throw new RateLimitExceededException("linkedin"); } else {//from w ww . j a v a 2s . com throw new InsufficientPermissionException("linkedin"); } } else if (statusCode.equals(HttpStatus.NOT_FOUND)) { throw new ResourceNotFoundException("linkedin", message); } handleUncategorizedError(response); }
From source file:org.venice.beachfront.bfapi.services.PiazzaService.java
/** * Gets the status of the Piazza Job with the specified Job ID * /* ww w .ja v a 2 s. com*/ * @param jobId * The Job ID * @return The status of the Job, as returned by Piazza */ public StatusMetadata getJobStatus(String jobId) throws UserException { String piazzaJobUrl = String.format("%s/job/%s", PIAZZA_URL, jobId); piazzaLogger.log(String.format("Checking Piazza Job Status for Job %s", jobId), Severity.INFORMATIONAL); HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY); HttpEntity<String> request = new HttpEntity<>(headers); // Execute the Request ResponseEntity<String> response = null; try { response = restTemplate.exchange(URI.create(piazzaJobUrl), HttpMethod.GET, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { HttpStatus recommendedErrorStatus = exception.getStatusCode(); if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) { recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't // want that } String message = String.format("There was an error fetching Job Status from Piazza. (%d) id=%s", exception.getStatusCode().value(), jobId); throw new UserException(message, exception.getMessage(), recommendedErrorStatus); } // Parse out the Status from the Response try { JsonNode responseJson = objectMapper.readTree(response.getBody()); StatusMetadata status = new StatusMetadata(responseJson.get("data").get("status").asText()); // Parse additional information depending on status if (status.isStatusSuccess()) { // If the status is complete, attach the Data ID of the shoreline detection status.setDataId(responseJson.get("data").get("result").get("dataId").asText()); } else if (status.isStatusError()) { // If the status is errored, then attach the error information JsonNode messageNode = responseJson.get("data").get("message"); if (messageNode != null) { status.setErrorMessage(messageNode.asText()); } else { status.setErrorMessage( "The Job contained an Error status but the cause was unable to be parsed from the response object."); } // If there is a detailed error message available in the Result field Data ID, fetch that ID. JsonNode resultNode = responseJson.get("data").get("result"); if (resultNode != null && resultNode.get("dataId") != null) { status.setDataId(resultNode.get("dataId").asText()); } } return status; } catch (IOException | NullPointerException exception) { String error = String .format("There was an error parsing the Piazza response when Requesting Job %s Status.", jobId); piazzaLogger.log(error, Severity.ERROR); throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:org.venice.beachfront.bfapi.services.PiazzaService.java
/** * Returns the list of all algorithm services that have been registed with the Beachfront Piazza API Key * /*www. jav a 2s . c o m*/ * @return List of algorithms available for use in Beachfront */ public List<Algorithm> getRegisteredAlgorithms() throws UserException { String piazzaServicesUrl = String.format("%s/service/me", PIAZZA_URL); piazzaLogger.log("Checking Piazza Registered Algorithms.", Severity.INFORMATIONAL); HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY); HttpEntity<String> request = new HttpEntity<>(headers); // Execute the Request ResponseEntity<String> response = null; try { response = restTemplate.exchange(URI.create(piazzaServicesUrl), HttpMethod.GET, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { piazzaLogger.log(String.format("Error fetching Algorithms from Piazza with Code %s, Response was %s", exception.getStatusText(), exception.getResponseBodyAsString()), Severity.ERROR); HttpStatus recommendedErrorStatus = exception.getStatusCode(); if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) { recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't // want that } String message = String.format("There was an error fetching Algorithm List from Piazza. (%d)", exception.getStatusCode().value()); throw new UserException(message, exception.getMessage(), recommendedErrorStatus); } // Ensure the response succeeded if (!response.getStatusCode().is2xxSuccessful()) { // Error occurred - report back to the user throw new UserException("Piazza returned a non-OK status when requesting registered Algorithm List.", response.getStatusCode().toString(), response.getStatusCode()); } // Parse out the Algorithms from the Response try { JsonNode responseJson = objectMapper.readTree(response.getBody()); JsonNode algorithmJsonArray = responseJson.get("data"); List<Algorithm> algorithms = new ArrayList<>(); for (JsonNode algorithmJson : algorithmJsonArray) { // For each Registered Service, wrap it in the Algorithm Object and add to the list algorithms.add(getAlgorithmFromServiceNode(algorithmJson)); } piazzaLogger.log( String.format("Returning full Piazza algorithm list. Found %s Algorithms.", algorithms.size()), Severity.INFORMATIONAL); return algorithms; } catch (IOException exception) { String error = "There was an error parsing the Piazza response when Requesting registered Algorithm List."; piazzaLogger.log(error, Severity.ERROR); throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:org.venice.beachfront.bfapi.services.PiazzaService.java
/** * Gets the registered algorithm from Piazza based on the Service ID. This can return services that are not owned by * the currently configured Piazza API Key * // w w w .jav a2 s. c o m * @param serviceId * Service ID to fetch * @return The Service */ public Algorithm getRegisteredAlgorithm(String serviceId) throws UserException { String piazzaServiceUrl = String.format("%s/service/%s", PIAZZA_URL, serviceId); piazzaLogger.log(String.format("Checking Piazza Registered Algorithm %s.", serviceId), Severity.INFORMATIONAL); HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY); HttpEntity<String> request = new HttpEntity<>(headers); // Execute the Request ResponseEntity<String> response = null; try { response = restTemplate.exchange(URI.create(piazzaServiceUrl), HttpMethod.GET, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { piazzaLogger.log( String.format("Error fetching Algorithm %s from Piazza with Code %s, Response was %s", serviceId, exception.getStatusText(), exception.getResponseBodyAsString()), Severity.ERROR); HttpStatus recommendedErrorStatus = exception.getStatusCode(); if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) { recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't // want that } String message = String.format("There was an error fetching Algorithm from Piazza. (%d) id=%s", exception.getStatusCode().value(), serviceId); throw new UserException(message, exception.getMessage(), recommendedErrorStatus); } // Ensure the response succeeded if (!response.getStatusCode().is2xxSuccessful()) { // Error occurred - report back to the user throw new UserException(String .format("Piazza returned a non-OK status when requesting registered Algorithm %s.", serviceId), response.getStatusCode().toString(), response.getStatusCode()); } // Parse out the Algorithms from the Response try { JsonNode responseJson = objectMapper.readTree(response.getBody()); JsonNode algorithmJson = responseJson.get("data"); return getAlgorithmFromServiceNode(algorithmJson); } catch (IOException exception) { String error = String.format( "There was an error parsing the Piazza response when Requesting registered Algorithm %s.", serviceId); piazzaLogger.log(error, Severity.ERROR); throw new UserException(error, exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:org.venice.beachfront.bfapi.services.PiazzaService.java
/** * Calls the data/file endpoint to download data from Piazza for the specified Data ID. * <p>// w w w . java2s . com * Piazza Data IDs for a successful job are the raw GeoJSON of the shoreline detection vectors for a successful Job * execution. * <p> * Piazza Data IDs for an unsuccessful job will contain the detailed JSON information for an error message on an * algorithm execution. This contains the stack trace and other information from the algorithm itself that details * the errors. * * @param dataId * Data ID * @return The bytes of the ingested data */ public byte[] downloadData(String dataId) throws UserException { String piazzaDataUrl = String.format("%s/file/%s", PIAZZA_URL, dataId); piazzaLogger.log(String.format("Requesting data %s bytes from Piazza at %s", dataId, piazzaDataUrl), Severity.INFORMATIONAL); HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY); HttpEntity<String> request = new HttpEntity<>(headers); // Execute the Request ResponseEntity<String> response = null; try { response = restTemplate.exchange(URI.create(piazzaDataUrl), HttpMethod.GET, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { piazzaLogger.log( String.format( "Error downloading Data Bytes for Data %s from Piazza. Failed with Code %s and Body %s", dataId, exception.getStatusText(), exception.getResponseBodyAsString()), Severity.ERROR); HttpStatus recommendedErrorStatus = exception.getStatusCode(); if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) { recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't // want that } String message = String.format( "There was an upstream error fetching data bytes from Piazza. (%d) id=%s", exception.getStatusCode().value(), dataId); throw new UserException(message, exception.getMessage(), recommendedErrorStatus); } byte[] data = response.getBody().getBytes(); piazzaLogger.log(String.format("Successfully retrieved Bytes for Data %s from Piazza. File size was %s", dataId, data.length), Severity.INFORMATIONAL); return data; }
From source file:org.venice.beachfront.bfapi.services.PiazzaService.java
/** * Returns all of the Statistics for the Beachfront Algorithm as reported by the Piazza Task-Managed service. * /*w ww . j av a 2s . c om*/ * @return JSON block containing statistics. This contains, at least, the number of jobs in that algorithms queue. */ public JsonNode getAlgorithmStatistics(String algorithmId) throws UserException { String piazzaTaskUrl = String.format("%s/service/%s/task/metadata", PIAZZA_URL, algorithmId); piazzaLogger.log( String.format("Fetching Algorithm Tasks Metadata for %s at URL %s", algorithmId, piazzaTaskUrl), Severity.INFORMATIONAL); HttpHeaders headers = createPiazzaHeaders(PIAZZA_API_KEY); HttpEntity<String> request = new HttpEntity<>(headers); // Execute the Request ResponseEntity<String> response = null; try { response = restTemplate.exchange(URI.create(piazzaTaskUrl), HttpMethod.GET, request, String.class); } catch (HttpClientErrorException | HttpServerErrorException exception) { HttpStatus recommendedErrorStatus = exception.getStatusCode(); if (recommendedErrorStatus.equals(HttpStatus.UNAUTHORIZED)) { recommendedErrorStatus = HttpStatus.BAD_REQUEST; // 401 Unauthorized logs out the client, and we don't // want that } String message = String.format("There was an error fetching Service Metadata from Piazza (%d) id=%s", exception.getStatusCode().value(), algorithmId); throw new UserException(message, exception.getMessage(), recommendedErrorStatus); } try { return objectMapper.readTree(response.getBody()); } catch (IOException exception) { String error = String.format("There was an error parsing the Service Metadata for service %s.", algorithmId); piazzaLogger.log(error, Severity.ERROR); throw new UserException(error, exception, HttpStatus.INTERNAL_SERVER_ERROR); } }