Example usage for org.springframework.web.client HttpStatusCodeException getStatusCode

List of usage examples for org.springframework.web.client HttpStatusCodeException getStatusCode

Introduction

In this page you can find the example usage for org.springframework.web.client HttpStatusCodeException getStatusCode.

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code.

Usage

From source file:eu.cloudwave.wp5.feedbackhandler.metricsources.AbstractMetricSourceClient.java

/**
 * This method can be used by subclass for error handling. It directly handles 404 Errors and general errors that are
 * not treated specially and calls the hook {@link #handleHttpServerException(HttpServerErrorException)} for errors
 * that have to be treated specially by subclasses. By implementing the hook methods subclasses can handles those
 * errors individually./*  w w  w  . j a v a2  s . co  m*/
 * 
 * @param throwable
 *          the exception
 * @throws MetricSourceClientException
 *           for errors that do not have to be treated specially by subclasses
 */
protected final void handleException(final Throwable throwable) throws MetricSourceClientException {
    if (throwable instanceof HttpStatusCodeException) {
        final HttpStatusCodeException httpError = (HttpStatusCodeException) throwable;

        // handle errors individually by subclasses
        try {
            handleHttpServerException(httpError);
        } catch (final IOException e) {
            /**
             * This error can occur while trying to identify the cause for the original error. It is ignored and the
             * original error is thrown instead.
             */
        }

        // handle 404 NOT FOUND errors
        if (httpError.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw new MetricSourceClientException(ErrorType.METRIC_SOURCE_NOT_AVAILABLE, httpError);
        }
    }

    // if no precise cause could be identified, throw the original exception
    throw new MetricSourceClientException(ErrorType.NEW_RELIC__GENERAL, throwable);
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

/**
 * Kill job based on given job ID./*from   w  w  w .j  a  v  a  2  s.c o m*/
 *
 * @param id            id for job to kill
 * @param forwardedFrom The host this request was forwarded from if present
 * @param request       the servlet request
 * @param response      the servlet response
 * @throws GenieException   For any error
 * @throws IOException      on redirect error
 * @throws ServletException when trying to handle the request
 */
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.ACCEPTED)
public void killJob(@PathVariable("id") final String id,
        @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) final String forwardedFrom,
        final HttpServletRequest request, final HttpServletResponse response)
        throws GenieException, IOException, ServletException {
    log.info("[killJob] Called for job id: {}. Forwarded from: {}", id, forwardedFrom);

    // If forwarded from is null this request hasn't been forwarded at all. Check we're on the right node
    if (this.jobsProperties.getForwarding().isEnabled() && forwardedFrom == null) {
        final String jobHostname = this.jobSearchService.getJobHost(id);
        if (!this.hostName.equals(jobHostname)) {
            log.info("Job {} is not on this node. Forwarding kill request to {}", id, jobHostname);
            final String forwardUrl = buildForwardURL(request, jobHostname);
            try {
                //Need to forward job
                restTemplate.execute(forwardUrl, HttpMethod.DELETE,
                        forwardRequest -> copyRequestHeaders(request, forwardRequest),
                        (final ClientHttpResponse forwardResponse) -> {
                            response.setStatus(HttpStatus.ACCEPTED.value());
                            copyResponseHeaders(response, forwardResponse);
                            return null;
                        });
            } catch (HttpStatusCodeException e) {
                log.error("Failed killing job on {}. Error: {}", forwardUrl, e.getMessage());
                response.sendError(e.getStatusCode().value(), e.getStatusText());
            } catch (Exception e) {
                log.error("Failed killing job on {}. Error: {}", forwardUrl, e.getMessage());
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }

            // No need to do anything on this node
            return;
        }
    }

    log.info("Job {} is on this node. Attempting to kill.", id);
    // Job is on this node so try to kill it
    this.jobCoordinatorService.killJob(id);
    response.setStatus(HttpStatus.ACCEPTED.value());
}

From source file:access.controller.AccessController.java

/**
 * Deletes a Deployment Group from Piazza, and from the corresponding GeoServer.
 * /*from w w w . j av a 2 s.  c  om*/
 * @param deploymentGroupId
 *            The Id of the deployment Group to delete.
 * @return Appropriate response
 */
@RequestMapping(value = "/deployment/group/{deploymentGroupId}", method = RequestMethod.DELETE, produces = "application/json")
public ResponseEntity<PiazzaResponse> deleteDeploymentGroup(
        @PathVariable(value = "deploymentGroupId") String deploymentGroupId) {
    try {
        if ((deploymentGroupId == null) || (deploymentGroupId.isEmpty())) {
            return new ResponseEntity<>(
                    new ErrorResponse("DeploymentGroup Id not specified.", ACCESS_COMPONENT_NAME),
                    HttpStatus.BAD_REQUEST);
        }
        // Delete the DeploymentGroup from GeoServer, and remove it from
        // the Piazza DB persistence
        DeploymentGroup deploymentGroup = accessor.getDeploymentGroupById(deploymentGroupId);
        if (deploymentGroup == null) {
            return new ResponseEntity<>(
                    new ErrorResponse("DeploymentGroup does not exist.", ACCESS_COMPONENT_NAME),
                    HttpStatus.NOT_FOUND);
        }
        groupDeployer.deleteDeploymentGroup(deploymentGroup);
        return new ResponseEntity<>(new SuccessResponse("Group Deleted.", ACCESS_COMPONENT_NAME),
                HttpStatus.OK);
    } catch (HttpStatusCodeException httpException) {
        // Return the HTTP Error code from GeoServer
        String error = String.format(
                "Could not delete DeploymentGroup. Response from GeoServer returned code %s with reason %s",
                httpException.getStatusCode().toString(), httpException.getMessage());
        LOGGER.error(error, httpException);
        pzLogger.log(error, Severity.ERROR,
                new AuditElement(ACCESS, "errorDeletingDeploymentGroup", deploymentGroupId));
        return new ResponseEntity<>(new ErrorResponse(error, ACCESS_COMPONENT_NAME),
                httpException.getStatusCode());
    } catch (Exception exception) {
        // Return the 500 Internal error
        String error = String.format("Could not delete DeploymentGroup. An unexpected error occurred: %s",
                exception.getMessage());
        LOGGER.error(error, exception);
        pzLogger.log(error, Severity.ERROR,
                new AuditElement(ACCESS, "errorDeletingDeploymentGroup", deploymentGroupId));
        return new ResponseEntity<>(new ErrorResponse(error, ACCESS_COMPONENT_NAME),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestService.java

/**
 * Call bioportal.//  w ww  .j  a v a  2  s  .com
 *
 * @param url the url
 * @return the string
 */
protected String callBioportal(String url) {
    log.info("Calling Bioportal REST: " + url);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");

    ResponseEntity<String> response;

    try {
        response = this.restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw e;
        } else {
            log.error("Error calling BioPortal REST Service", e);
            throw ExceptionFactory.createUnknownException("Error calling NCBO BioPortal: " + e.getMessage());
        }
    }

    return response.getBody();
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

/**
 * Get the job output directory.//from w ww  . ja  v  a  2 s. com
 *
 * @param id            The id of the job to get output for
 * @param forwardedFrom The host this request was forwarded from if present
 * @param request       the servlet request
 * @param response      the servlet response
 * @throws IOException      on redirect error
 * @throws ServletException when trying to handle the request
 * @throws GenieException   on any Genie internal error
 */
@RequestMapping(value = { "/{id}/output", "/{id}/output/",
        "/{id}/output/**" }, method = RequestMethod.GET, produces = MediaType.ALL_VALUE)
public void getJobOutput(@PathVariable("id") final String id,
        @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) final String forwardedFrom,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException, GenieException {
    log.info("[getJobOutput] Called for job with id: {}", id);

    // if forwarded from isn't null it's already been forwarded to this node. Assume data is on this node.
    if (this.jobsProperties.getForwarding().isEnabled() && forwardedFrom == null) {
        // TODO: It's possible that could use the JobMonitorCoordinator to check this in memory
        //       However that could get into problems where the job finished or died
        //       and it would return false on check if the job with given id is running on that node
        final String jobHostname = this.jobSearchService.getJobHost(id);
        if (!this.hostName.equals(jobHostname)) {
            log.info("Job {} is not or was not run on this node. Forwarding to {}", id, jobHostname);
            final String forwardUrl = buildForwardURL(request, jobHostname);
            try {
                this.restTemplate.execute(forwardUrl, HttpMethod.GET,
                        forwardRequest -> copyRequestHeaders(request, forwardRequest),
                        new ResponseExtractor<Void>() {
                            @Override
                            public Void extractData(final ClientHttpResponse forwardResponse)
                                    throws IOException {
                                response.setStatus(HttpStatus.OK.value());
                                copyResponseHeaders(response, forwardResponse);
                                // Documentation I could find pointed to the HttpEntity reading the bytes off
                                // the stream so this should resolve memory problems if the file returned is large
                                ByteStreams.copy(forwardResponse.getBody(), response.getOutputStream());
                                return null;
                            }
                        });
            } catch (HttpStatusCodeException e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(e.getStatusCode().value(), e.getStatusText());
            } catch (Exception e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }

            //No need to search on this node
            return;
        }
    }

    log.info("Job {} is running or was run on this node. Fetching requested resource...", id);
    final String path = ControllerUtils.getRemainingPath(request);
    if (StringUtils.isNotBlank(path)) {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, false);
    } else {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, true);
    }
    log.debug("PATH = {}", path);
    request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, id + "/" + path);

    this.resourceHttpRequestHandler.handleRequest(request, response);
}

From source file:com.jaspersoft.android.sdk.client.JsRestClient.java

/**
 * Gets server information details// w  ww .  jav a2s .  co  m
 *
 * @param forceUpdate set to <code>true</code> to force update of the server info
 * @return the ServerInfo value
 * @throws RestClientException thrown by RestTemplate whenever it encounters client-side HTTP errors
 * @since 1.4
 */
public ServerInfo getServerInfo(boolean forceUpdate) throws RestClientException {
    if (forceUpdate || serverInfo == null) {
        String uri = getServerProfile().getServerUrl() + REST_SERVICES_V2_URI + REST_SERVER_INFO_URI;
        try {
            serverInfo = restTemplate.getForObject(uri, ServerInfo.class);
        } catch (HttpStatusCodeException ex) {
            HttpStatus statusCode = ex.getStatusCode();
            if (statusCode == HttpStatus.NOT_FOUND) {
                serverInfo = new ServerInfo();
            } else {
                throw ex;
            }
        }
    }

    return serverInfo;
}

From source file:org.syncope.core.rest.ConnInstanceTestITCase.java

@Test
public void create() {
    ConnInstanceTO connectorTO = new ConnInstanceTO();

    // set connector version
    connectorTO.setVersion(connidSoapVersion);

    // set connector name
    connectorTO.setConnectorName(WebServiceConnector.class.getName());

    // set bundle name
    connectorTO.setBundleName("org.connid.bundles.soap");

    connectorTO.setDisplayName("Display name");

    // set the connector configuration using PropertyTO
    Set<ConnConfProperty> conf = new HashSet<ConnConfProperty>();

    ConnConfPropSchema endpointSchema = new ConnConfPropSchema();
    endpointSchema.setName("endpoint");
    endpointSchema.setType(String.class.getName());
    endpointSchema.setRequired(true);//  w ww.  ja v  a2  s. co m
    ConnConfProperty endpoint = new ConnConfProperty();
    endpoint.setSchema(endpointSchema);
    endpoint.setValues(Collections.singletonList("http://localhost:8888/wssample/services"));

    ConnConfPropSchema servicenameSchema = new ConnConfPropSchema();
    servicenameSchema.setName("servicename");
    servicenameSchema.setType(String.class.getName());
    servicenameSchema.setRequired(true);
    ConnConfProperty servicename = new ConnConfProperty();
    servicename.setSchema(servicenameSchema);
    servicename.setValues(Collections.singletonList("Provisioning"));

    conf.add(endpoint);
    conf.add(servicename);

    // set connector configuration
    connectorTO.setConfiguration(conf);

    // set connector capabilities
    connectorTO.addCapability(ConnectorCapability.TWO_PHASES_CREATE);
    connectorTO.addCapability(ConnectorCapability.ONE_PHASE_CREATE);
    connectorTO.addCapability(ConnectorCapability.TWO_PHASES_UPDATE);

    ConnInstanceTO actual = restTemplate.postForObject(BASE_URL + "connector/create.json", connectorTO,
            ConnInstanceTO.class);

    assertNotNull(actual);

    assertEquals(actual.getBundleName(), connectorTO.getBundleName());
    assertEquals(actual.getConnectorName(), connectorTO.getConnectorName());
    assertEquals(actual.getVersion(), connectorTO.getVersion());
    assertEquals("Display name", actual.getDisplayName());
    assertEquals(connectorTO.getCapabilities(), actual.getCapabilities());

    Throwable t = null;

    // check for the updating
    connectorTO.setId(actual.getId());

    connectorTO.removeCapability(ConnectorCapability.TWO_PHASES_UPDATE);
    actual = null;
    try {
        actual = restTemplate.postForObject(BASE_URL + "connector/update.json", connectorTO,
                ConnInstanceTO.class);
    } catch (HttpStatusCodeException e) {
        LOG.error("update failed", e);
        t = e;
    }

    assertNull(t);
    assertNotNull(actual);
    assertEquals(connectorTO.getCapabilities(), actual.getCapabilities());

    // check also for the deletion of the created object
    try {
        restTemplate.delete(BASE_URL + "connector/delete/{connectorId}.json", String.valueOf(actual.getId()));
    } catch (HttpStatusCodeException e) {
        LOG.error("delete failed", e);
        t = e;
    }

    assertNull(t);

    // check the non existence
    try {
        restTemplate.getForObject(BASE_URL + "connector/read/{connectorId}", ConnInstanceTO.class,
                String.valueOf(actual.getId()));
    } catch (HttpStatusCodeException e) {
        assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
    }
}

From source file:org.syncope.core.rest.UserTestITCase.java

@Test
public void delete() {
    try {/*from  w ww.jav a  2  s.  com*/
        restTemplate.getForObject(BASE_URL + "user/delete/{userId}", UserTO.class, 0);
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
    }

    UserTO userTO = getSampleTO("qqgf.z@nn.com");

    // specify a propagation
    userTO.addResource("resource-testdb");

    userTO = restTemplate.postForObject(BASE_URL + "user/create", userTO, UserTO.class);

    long id = userTO.getId();

    userTO = restTemplate.getForObject(BASE_URL + "user/delete/{userId}", UserTO.class, id);

    assertNotNull(userTO);
    assertEquals(id, userTO.getId());
    assertTrue(userTO.getAttributes().isEmpty());

    // check for propagation result
    assertFalse(userTO.getPropagationTOs().isEmpty());
    assertTrue(userTO.getPropagationTOs().get(0).getStatus().isSuccessful());

    try {
        restTemplate.getForObject(BASE_URL + "user/read/{userId}.json", UserTO.class, userTO.getId());
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode());
    }
}

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

public DriveFile getDriveFile(String resourceID)
        throws GoogleDocsServiceException, GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException {
    log.debug("Get Document list entry for resource " + resourceID);
    DriveOperations driveOperations = getDriveOperations(getConnection());

    DriveFile driveFile = null;//w w  w  .  j ava  2  s . c  o m

    try {
        driveFile = driveOperations.getFile(resourceID.substring(resourceID.lastIndexOf(':') + 1));
    } catch (HttpStatusCodeException hsce) {
        throw new GoogleDocsServiceException(hsce.getMessage(), hsce.getStatusCode().value());
    }

    return driveFile;
}