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

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

Introduction

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

Prototype

@Override
@Nullable
public String getMessage() 

Source Link

Document

Return the detail message, including the message from the nested exception if there is one.

Usage

From source file:com.redblackit.web.test.RestTemplateTestHelper.java

/**
 * Test HEAD which should fail.//w  ww .ja  v  a 2 s. c  o m
 * Note that the old HttpClient wrongly causes an IOException instead of a HttpStatusCodeException.
 * 
 * @param url
 * @param urlArgs
 * @param assertMsg
 * @param expectedStatusCode
 */
public void doHeadForHttpStatusCodeException(String url, Object[] urlArgs, String assertMsg,
        HttpStatus expectedStatusCode) {

    StringBuilder builder = buildDebugMsg(url, urlArgs, assertMsg);
    builder.append(":getting headers:expecting HttpStatusCodeException");
    try {
        restTemplate.headForHeaders(url, (urlArgs == null ? new Object[0] : urlArgs));
        Assert.fail(builder.append(":no exception").toString());
    } catch (HttpStatusCodeException hsce) {
        Assert.assertEquals(builder.append(":statusCode:hsce=").append(hsce.getMessage()).toString(),
                expectedStatusCode, hsce.getStatusCode());
        logger.debug(builder.append(":OK"), hsce);
    }
}

From source file:com.redblackit.web.test.RestTemplateTestHelper.java

/**
 * Test OPTIONS which should fail//from   w ww  .j  a  v  a2  s.c  o  m
 * 
 * @param url
 * @param urlArgs
 * @param assertMsg
 * @param expectedStatusCode
 */
public void doOptionsForHttpStatusCodeException(String url, Object[] urlArgs, String assertMsg,
        HttpStatus expectedStatusCode) {

    StringBuilder builder = buildDebugMsg(url, urlArgs, assertMsg);
    builder.append(":getting options:expecting HttpStatusCodeException");
    try {
        restTemplate.optionsForAllow(url, (urlArgs == null ? new Object[0] : urlArgs));
        Assert.fail(builder.append(":no exception").toString());
    } catch (HttpStatusCodeException hsce) {
        Assert.assertEquals(builder.append(":statusCode:hsce=").append(hsce.getMessage()).toString(),
                expectedStatusCode, hsce.getStatusCode());
        logger.debug(builder.append(":OK"), hsce);
    }
}

From source file:org.trustedanalytics.servicecatalog.service.RestErrorHandler.java

@ExceptionHandler(HttpStatusCodeException.class)
public void handleHttpStatusCodeException(HttpStatusCodeException e, HttpServletResponse response)
        throws IOException {
    String message = extractErrorFromJSON(e.getResponseBodyAsString());
    message = StringUtils.isNotBlank(message) ? message : e.getMessage();
    ErrorLogger.logAndSendErrorResponse(LOGGER, response, e.getStatusCode(), message, e);
}

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

void handleHttpStatusCodeException(HttpStatusCodeException e, RedirectAttributes attributes)
        throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("authentication failed (message={},X-Track={})", e.getMessage(),
                e.getResponseHeaders().get("X-Track"));
    }/*  w ww.ja v  a  2  s .c  o m*/
    try {
        OAuth2Exception oAuth2Exception = objectMapper.readValue(e.getResponseBodyAsByteArray(),
                OAuth2Exception.class);
        attributes.addAttribute("error", oAuth2Exception.getMessage());
    } catch (JsonMappingException | JsonParseException ex) {
        attributes.addAttribute("error", e.getMessage());
    }
}

From source file:com.vmware.appfactory.workpool.WorkpoolClientService.java

/**
 * Returns the workpool identified by the id passed.
 *
 * @param id/*from   ww w . java  2  s  .  co  m*/
 * @return
 * @throws WpException
 */
public Workpool getWorkpoolById(Long id) throws WpException, AfNotFoundException {
    if (id == null) {
        throw new WpException("Invalid input");
    }
    try {
        return _rest.getForObject(baseUrl() + "/workpools/{id}", Workpool.class, id);
    } catch (HttpStatusCodeException ex) {
        if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new AfNotFoundException("NOT_FOUND: " + ex.getMessage());
        }
        throw new WpException(ex);
    } catch (RestClientException e) {
        throw new WpException(e);
    }
}

From source file:com.vmware.appfactory.workpool.WorkpoolClientService.java

/**
 * Used to update a VM Image. Name field can be updated.
 *
 * @param workpool/*from   w  w w  .j ava 2s  .c om*/
 * @throws WpException
 */
public void updateWorkpool(Workpool workpool) throws WpException, AfNotFoundException, AfConflictException {
    Long id = workpool.getId();
    try {
        _rest.put(baseUrl() + "/workpools/{id}", workpool, id);
    } catch (HttpStatusCodeException ex) {
        if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new AfNotFoundException("NOT_FOUND: " + ex.getMessage());
        } else if (ex.getStatusCode() == HttpStatus.CONFLICT) {
            throw new AfConflictException("CONFLICT_NAME: " + ex.getMessage());
        }
        throw new WpException("Workpool cannot be updated: " + ex.getMessage());
    } catch (RestClientException e) {
        throw new WpException("Workpool cannot be updated: " + e.getMessage());
    }
}

From source file:com.vmware.appfactory.workpool.WorkpoolClientService.java

/**
 * Returns the VmImage identified by the id passed.
 *
 * @param id// w ww.j  av  a2 s.c o m
 * @return
 * @throws WpException
 */
public VmImage getVmImageById(Long id) throws WpException, AfNotFoundException {
    if (id == null) {
        throw new WpException("Empty input");
    }
    try {
        return _rest.getForObject(baseUrl() + "/vmimages/{id}", VmImage.class, id);
    } catch (HttpStatusCodeException ex) {
        if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new AfNotFoundException("NOT_FOUND: " + ex.getMessage());
        }
        throw new WpException(ex);
    } catch (RestClientException e) {
        throw new WpException(e);
    }
}

From source file:com.vmware.appfactory.workpool.WorkpoolClientService.java

/**
 * Used to create a workpool. This call can create workpools of Full,
 * linked, Custom types./*from w  w w .jav a2  s . c o m*/
 *
 * NOTE: The created workpool or the Id is not returned as its not needed
 * at this point in time. If needed @see VmImage.createVmImage()
 *
 * @param workpool
 * @return
 * @throws WpException, AfConflictException
 */
public Long createWorkpool(Workpool workpool) throws WpException, AfConflictException {
    try {
        // This method does not return the
        URI uri = _rest.postForLocation(baseUrl() + "/workpools", workpool);

        return Long.valueOf(AfUtil.extractLastURIToken(uri));
    } catch (HttpStatusCodeException ex) {
        if (ex.getStatusCode() == HttpStatus.CONFLICT) {
            throw new AfConflictException("CONFLICT_NAME: " + ex.getMessage());
        }
        throw new WpException("Workpool cannot be created: " + ex.getMessage());
    } catch (RestClientException e) {
        throw new WpException("Workpool cannot be created: " + e.getMessage());
    }
}

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

/**
 * Kill job based on given job ID.// w w w  .  j a  v  a 2s  .  com
 *
 * @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:com.netflix.genie.web.controllers.JobRestController.java

/**
 * Get the job output directory.//from w  w w  .ja  v  a2  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);
}