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

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

Introduction

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

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code.

Usage

From source file:eu.freme.broker.eservices.FremeNER.java

private ResponseEntity<String> callBackend(String uri, HttpMethod method, String body) {

    RestTemplate restTemplate = new RestTemplate();
    try {/*from  ww  w.  j  a  va  2s  .  c o m*/
        if (body == null) {
            return restTemplate.exchange(new URI(uri), method, null, String.class);
        } else {
            ResponseEntity<String> response = restTemplate.exchange(new URI(uri), method,
                    new HttpEntity<String>(body), String.class);

            if (response.getStatusCode() == HttpStatus.CONFLICT) {
                throw new eu.freme.broker.exception.BadRequestException(
                        "Dataset with this name already existis and it cannot be created.");
            } else {
                return response;
            }
            //                return restTemplate.exchange(new URI(uri), method, new HttpEntity<String>(body), String.class);
        }
    } catch (HttpClientErrorException rce) {
        if (rce.getStatusCode() == HttpStatus.CONFLICT) {
            throw new eu.freme.broker.exception.BadRequestException(
                    "Dataset with this name already existis and it cannot be created.");
        } else {
            throw new eu.freme.broker.exception.ExternalServiceFailedException(rce.getMessage());
        }
    } catch (RestClientException rce) {
        logger.error("failed", rce);
        throw new eu.freme.broker.exception.ExternalServiceFailedException(rce.getMessage());
    } catch (Exception e) {
        logger.error("failed", e);
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java

@Test
public void dependencyNotInRange() {
    try {//from   w ww. j a v  a2  s .c  o  m
        execute("/starter.tgz?style=org.acme:bur", byte[].class, null, (String[]) null);
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_ACCEPTABLE, ex.getStatusCode());
    }
}

From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java

@Test
public void metadataWithUnknownAcceptHeader() {
    try {//w  w  w  .ja va 2  s .c  o m
        invokeHome(null, "application/vnd.initializr.v5.4+json");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_ACCEPTABLE, ex.getStatusCode());
    }
}

From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java

@Test
public void missingDependencyProperException() {
    try {/*w w  w. ja va 2s.com*/
        downloadArchive("/starter.zip?style=foo:bar");
        fail("Should have failed");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
        assertStandardErrorBody(ex.getResponseBodyAsString(),
                "Unknown dependency 'foo:bar' check project metadata");
    }
}

From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java

@Test
public void invalidDependencyProperException() {
    try {//  w w  w.java2s. com
        downloadArchive("/starter.zip?style=foo");
        fail("Should have failed");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
        assertStandardErrorBody(ex.getResponseBodyAsString(),
                "Unknown dependency 'foo' check project metadata");
    }
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.renderer.MarketplaceIntegrationOrderIncrementalRenderer.java

private boolean incrementalOrderDownload(final MarketplaceStoreModel model, final String status) {
    boolean flag = false;
    final String logUUID = logUtil.getUUID();
    final MarketplaceSellerModel seller = model.getMarketplaceSeller();
    final MarketplaceModel marketPlace = seller.getMarketplace();
    modelService.refresh(seller);/* w ww. ja  v a  2 s.c  om*/

    final String requestUrl = marketPlace.getAdapterUrl()
            + Config.getParameter(MARKETPLACE_ORDER_REALTIME_SYNC_PATH)
            + Config.getParameter(MARKETPLACE_ORDER_SYCHRONIZE_MIDDLE_PATH) + model.getIntegrationId()
            + Config.getParameter(MARKETPLACE_ORDER_SYCHRONIZE_LOGUUID) + logUUID;
    final JSONObject jsonObj = new JSONObject();
    jsonObj.put("currency", model.getCurrency().getIsocode());
    jsonObj.put("productCatalogVersion",
            model.getCatalogVersion().getCatalog().getId() + ":" + model.getCatalogVersion().getVersion());
    jsonObj.put("status", status);

    try {
        this.saveMarketplaceLog(status, model, logUUID);

        final JSONObject results = marketplaceHttpUtil.post(requestUrl, jsonObj.toJSONString());
        final String msg = results.toJSONString();
        final String responseCode = results.get("code").toString();

        if ("401".equals(responseCode)) {
            LOG.error("=========================================================================");
            LOG.error("Order incremental download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + responseCode);
            LOG.error("Request path: " + requestUrl);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Authentication was failed, please re-authenticate again!");
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.authorization.fail"),
                    NotificationEvent.Type.FAILURE, "");
            LOG.warn("Authentication was failed, please re-authenticate again!");
        } else if (!("0".equals(responseCode))) {
            LOG.error("=========================================================================");
            LOG.error("Order incremental download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + responseCode);
            LOG.error("Request path: " + requestUrl);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("A known issue occurs in tmall, error details :" + msg);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("=========================================================================");
            /*
             * NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.tmallapp.known.issues", new Object[] { msg
             * }), NotificationEvent.Type.FAILURE, "");
             */
            LOG.warn("A known issue occurs in tmall, error details :" + msg);
        } else if ("0".equals(responseCode)) {
            LOG.debug("Open listen sucessfully");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.incremental.order.success"),
                    NotificationEvent.Type.SUCCESS, "");
            flag = true;
            LOG.info("=========================================================================");
            LOG.info("Order incremental download request post to Tmall suceessfully!");
            LOG.info("-------------------------------------------------------------------------");
            LOG.info("Marketplacestore Code: " + model.getName());
            LOG.info("Request path: " + requestUrl);
            LOG.info("=========================================================================");

        }
    } catch (final HttpClientErrorException httpError) {
        if (httpError.getStatusCode().is4xxClientError()) {
            LOG.error("=========================================================================");
            LOG.error("Order incremental download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + requestUrl);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Tmall service URL is not correct!");
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.request.post.error"),
                    NotificationEvent.Type.FAILURE, "");

        }
        if (httpError.getStatusCode().is5xxServerError()) {
            LOG.error("=========================================================================");
            LOG.error("Order incremental download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + requestUrl);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Json Ojbect is not correct!");
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                    NotificationEvent.Type.FAILURE, "");
        }
        LOG.error(httpError.toString());
        return flag;
    } catch (final ResourceAccessException raError) {
        LOG.error("=========================================================================");
        LOG.error("Order incremental download request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + requestUrl);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Marketplace order download request server access failed!");
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + raError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.access.error"),
                NotificationEvent.Type.FAILURE, "");
        return flag;
    } catch (final HttpServerErrorException serverError) {
        LOG.error("=========================================================================");
        LOG.error("Order incremental download request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + requestUrl);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Marketplace order download request server process failed!");
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + serverError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                NotificationEvent.Type.FAILURE, "");
        return flag;
    } catch (final Exception e) {
        final String errorMsg = e.getClass().toString() + ":" + e.getMessage();
        NotificationUtils.notifyUserVia(
                Labels.getLabel("marketplace.runtime.issues", new Object[] { errorMsg }),
                NotificationEvent.Type.FAILURE, "");
        LOG.error("=========================================================================");
        LOG.error("Order incremental download request failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + requestUrl);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + e.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                NotificationEvent.Type.FAILURE, "");
        LOG.warn(e.getMessage() + e.getStackTrace());
        return flag;
    }
    return flag;
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyClientWithRegisteredRedirect.class, initialize = false)
public void testRegisteredRedirectWithWrongRequestedRedirect() throws Exception {
    try {/*from w  w w  .j a v  a 2  s  . co  m*/
        approveAccessTokenGrant("http://nowhere", true);
        fail("Expected RedirectMismatchException");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
    }
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception {

    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setCurrentUri("http://anywhere");
    request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");

    try {/*from   ww  w.  ja va  2  s .com*/
        String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
        assertNotNull(code);
        fail("Expected UserRedirectRequiredException");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }

}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.renderer.MarketplaceIntegrationOrderRequestRenderer.java

private void orderRequestDownload(final MarketplaceStoreModel model) {
    if (null == model.getRequestStartTime()) {
        NotificationUtils//from  w  w w.  j av  a 2  s.c o  m
                .notifyUserVia(
                        Localization.getLocalizedString(
                                "type.Marketplacestore." + MarketplaceStoreModel.REQUESTSTARTTIME + ".name")
                                + " " + Labels.getLabel("backoffice.field.notfilled"),
                        NotificationEvent.Type.WARNING, "");
        LOG.warn("Order request start time is not filled!");
        return;
    } else if (null == model.getRequestEndTime()) {
        NotificationUtils.notifyUserVia(Localization
                .getLocalizedString("type.Marketplacestore." + MarketplaceStoreModel.REQUESTENDTIME + ".name")
                + " " + Labels.getLabel("backoffice.field.notfilled"), NotificationEvent.Type.WARNING, "");
        LOG.warn("Order request end time is not filled!");
        return;
    } else if (model.getRequestStartTime().after(model.getRequestEndTime())) {
        NotificationUtils.notifyUserVia(Labels.getLabel("backoffice.field.timerange.error"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("start time is greater than end time!");
        return;
    }

    if (!StringUtils.isBlank(model.getIntegrationId()) && !model.getAuthorized().booleanValue()) {
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.authorization.fail"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("authorization is expired!");
        return;
    }
    //in order to avoid this value out of date, we only get it from database
    final Boolean isAuth = ((MarketplaceStoreModel) modelService.get(model.getPk())).getAuthorized();
    final String integrationId = ((MarketplaceStoreModel) modelService.get(model.getPk())).getIntegrationId();
    model.setIntegrationId(integrationId);
    model.setAuthorized(isAuth);
    if (null == isAuth || !isAuth.booleanValue()) {
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.refund.requestorder.unauthed"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("marketplace store do not authorized, download refund/return order failed!");
        return;
    }

    String urlStr = "";
    final String logUUID = logUtil.getUUID();
    final MarketplaceSellerModel seller = model.getMarketplaceSeller();
    final MarketplaceModel marketPlace = seller.getMarketplace();

    try {
        // Configure and open a connection to the site you will send the
        urlStr = marketPlace.getAdapterUrl() + Config.getParameter(MARKETPLACE_REFUND_SYCHRONIZE_PATH)
                + Config.getParameter(MARKETPLACE_REFUND_REQUEST_PATH) + integrationId
                + Config.getParameter(MARKETPLACE_REFUND_REQUEST_LOGUUID) + logUUID;
        final JSONObject jsonObj = new JSONObject();
        jsonObj.put("batchSize", BATCH_SIZE);

        //set the correct timezone
        final String configTimezone = model.getMarketplace().getTimezone();
        boolean isValidTimezone = false;
        for (final String vaildTimezone : TimeZone.getAvailableIDs()) {
            if (vaildTimezone.equals(configTimezone)) {
                isValidTimezone = true;
                break;
            }
        }

        if (!isValidTimezone) {
            final String[] para = { configTimezone == null ? "" : configTimezone,
                    model.getMarketplace().getName() };
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.initorder.wrongtimezone", para),
                    NotificationEvent.Type.WARNING, "");
            LOG.warn("wrong timezone or missing timezone configed in market:"
                    + model.getMarketplace().getName());
            return;
        }

        final SimpleDateFormat format = new SimpleDateFormat(Config.getParameter(BACKOFFICE_FORMAT_DATEFORMAT));
        format.setTimeZone(TimeZone.getTimeZone(configTimezone));

        final String startTimeWithCorrectZone = format.format(model.getRequestStartTime()).toString();
        final String endTimeWithCorrectZone = format.format(model.getRequestEndTime()).toString();

        logUtil.addMarketplaceLog("PENDING", integrationId,
                Labels.getLabel("marketplace.order.requestorder.action"), model.getItemtype(), marketPlace,
                model, logUUID);

        jsonObj.put("startCreated", startTimeWithCorrectZone);
        jsonObj.put("endCreated", endTimeWithCorrectZone);
        jsonObj.put("productCatalogVersion",
                model.getCatalogVersion().getCatalog().getId() + ":" + model.getCatalogVersion().getVersion());
        jsonObj.put("currency", model.getCurrency().getIsocode());
        marketplaceHttpUtil.post(urlStr, jsonObj.toJSONString());
    } catch (final HttpClientErrorException httpError) {
        if (httpError.getStatusCode().is4xxClientError()) {
            LOG.error("=========================================================================");
            LOG.error("Order Request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Tmall service URL is not correct!");
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.request.post.error"),
                    NotificationEvent.Type.FAILURE, "");
        }
        if (httpError.getStatusCode().is5xxServerError()) {
            LOG.error("=========================================================================");
            LOG.error("Order Request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Json Ojbect is not correct!");
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                    NotificationEvent.Type.FAILURE, "");
        }
        LOG.error(httpError.toString());
        return;
    } catch (final ResourceAccessException raError) {
        LOG.error("=========================================================================");
        LOG.error("Order Request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + urlStr);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Order Request server access failed!");
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + raError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.access.error"),
                NotificationEvent.Type.FAILURE, "");
        return;
    } catch (final HttpServerErrorException serverError) {
        LOG.error("=========================================================================");
        LOG.error("Order Request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + urlStr);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Order Request server process failed!");
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + serverError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                NotificationEvent.Type.FAILURE, "");
        return;
    } catch (final Exception e) {
        LOG.error("=========================================================================");
        LOG.error("Order Request failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + urlStr);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Order Request server process failed!");
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Detail error info: " + e.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.refund.requestorder.fail"),
                NotificationEvent.Type.FAILURE, "");
        return;
    }
    NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.refund.requestorder.success"),
            NotificationEvent.Type.SUCCESS, "");
}

From source file:com.ge.predix.integration.test.AccessControlServiceIT.java

@Test(dataProvider = "endpointProvider")
public void testPolicyUpdateWithReadOnlyAccess(final String endpoint) throws Exception {
    try {//from  w w w .  ja  v  a 2  s  . co  m
        String policyFile = "src/test/resources/policy-set-with-multiple-policies-na-with-condition.json";
        this.policyHelper.setTestPolicy(this.acsReadOnlyRestTemplate, this.zone1Headers, endpoint, policyFile);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.FORBIDDEN);
    }
}