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:org.springframework.data.keyvalue.riak.client.RiakRestClient.java

private <T> ResponseEntity<T> execute(String path, HttpMethod method, Object value, RiakParameter[] parameters,
        Class<T> clazz, String... pathParams) throws RiakException {
    try {/*from   www.  j  av a 2 s.  c  o  m*/
        if (value == null)
            return restTemplate.exchange(getUrl(path, parameters, pathParams), method,
                    new HttpEntity<Object>(getHeadersMap(parameters)), clazz);
        else
            return restTemplate.exchange(getUrl(path, parameters, pathParams), method,
                    new HttpEntity<Object>(value, getHeadersMap(parameters)), clazz);
    } catch (RestClientException e) {
        if (e instanceof HttpClientErrorException) {
            // 400 error
            HttpClientErrorException ex = (HttpClientErrorException) e;
            if (ex.getStatusCode().equals(HttpStatus.NOT_FOUND))
                throw new RiakObjectNotFoundException(HttpStatus.NOT_FOUND.toString());

            throw new RiakUncategorizedClientErrorException(ex.getStatusText());
        } else if (e instanceof HttpServerErrorException) {
            // 500 error
            HttpServerErrorException ex = (HttpServerErrorException) e;
            throw new RiakServerErrorException(ex.getStatusText());
        }

        throw new RiakUncategorizedException("Uncategorized exception thrown", e);
    }
}

From source file:org.springframework.web.client.RestTemplateIntegrationTests.java

@Test
public void notFound() {
    try {//from w  ww  .j a  v a  2 s  .  com
        template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
        fail("HttpClientErrorException expected");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
        assertNotNull(ex.getStatusText());
        assertNotNull(ex.getResponseBodyAsString());
    }
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

private List<String> findStreamQueues(String adminUri, String vhost, String busPrefix, String stream,
        RestTemplate restTemplate) {// www  .j  a v  a 2s  . c  om
    List<String> removedQueues = new ArrayList<>();
    int n = 0;
    while (true) { // exits when no queue found
        String queueName = MessageBusSupport.applyPrefix(busPrefix,
                AbstractMessageBusBinderPlugin.constructPipeName(stream, n++));
        URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api")
                .pathSegment("queues", "{vhost}", "{stream}").buildAndExpand(vhost, queueName).encode().toUri();
        try {
            getQueueDetails(restTemplate, queueName, uri);
            removedQueues.add(queueName);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                break; // No more for this stream
            }
            throw new RabbitAdminException("Failed to lookup queue " + queueName, e);
        }
        queueName = MessageBusSupport.constructDLQName(queueName);
        uri = UriComponentsBuilder.fromUriString(adminUri + "/api").pathSegment("queues", "{vhost}", "{stream}")
                .buildAndExpand(vhost, queueName).encode().toUri();
        try {
            getQueueDetails(restTemplate, queueName, uri);
            removedQueues.add(queueName);
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                continue; // DLQs are not mandatory
            }
            throw new RabbitAdminException("Failed to lookup queue " + queueName, e);
        }
    }
    return removedQueues;
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

private List<String> findJobQueues(String adminUri, String vhost, String busPrefix, String job,
        RestTemplate restTemplate) {//from w w  w .  jav a2 s.c  o  m
    List<String> removedQueues = new ArrayList<>();
    String jobQueueName = MessageBusSupport.applyPrefix(busPrefix, AbstractJobPlugin.getJobChannelName(job));
    URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api").pathSegment("queues", "{vhost}", "{job}")
            .buildAndExpand(vhost, jobQueueName).encode().toUri();
    try {
        getQueueDetails(restTemplate, jobQueueName, uri);
        removedQueues.add(jobQueueName);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw new RabbitAdminException("Failed to lookup queue " + jobQueueName, e);
        }
    }
    String jobRequestsQueueName = MessageBusSupport.applyPrefix(busPrefix, MessageBusSupport.applyRequests(
            AbstractMessageBusBinderPlugin.constructPipeName(AbstractJobPlugin.getJobChannelName(job), 0)));
    uri = UriComponentsBuilder.fromUriString(adminUri + "/api").pathSegment("queues", "{vhost}", "{job}")
            .buildAndExpand(vhost, jobRequestsQueueName).encode().toUri();
    try {
        getQueueDetails(restTemplate, jobRequestsQueueName, uri);
        removedQueues.add(jobRequestsQueueName);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw new RabbitAdminException("Failed to lookup queue " + jobRequestsQueueName, e);
        }
    }
    return removedQueues;
}

From source file:org.thingsboard.demo.loader.data.DemoData.java

public void uploadData(RestTemplate restTemplate, String baseUrl) throws Exception {
    plugins.forEach(plugin -> {//  ww  w.  j  a va2s  . c o m
        try {
            String apiToken = plugin.getApiToken();
            PluginMetaData savedPlugin = null;
            try {
                savedPlugin = restTemplate.getForObject(baseUrl + "/api/plugin/token/" + apiToken,
                        PluginMetaData.class);
            } catch (HttpClientErrorException e) {
                if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
                    throw e;
                }
            }
            if (savedPlugin == null) {
                savedPlugin = restTemplate.postForObject(baseUrl + "/api/plugin", plugin, PluginMetaData.class);
            }
            if (savedPlugin.getState() == ComponentLifecycleState.SUSPENDED) {
                restTemplate.postForLocation(
                        baseUrl + "/api/plugin/" + savedPlugin.getId().getId().toString() + "/activate", null);
            }
        } catch (Exception e) {
            log.error("Unable to upload plugin!");
            log.error("Cause:", e);
        }
    });

    rules.forEach(rule -> {
        try {
            RuleMetaData savedRule = null;
            TextPageData<RuleMetaData> rules;
            ResponseEntity<TextPageData<RuleMetaData>> entity = restTemplate.exchange(
                    baseUrl + "/api/rule?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null,
                    new ParameterizedTypeReference<TextPageData<RuleMetaData>>() {
                    }, 1000, rule.getName());
            rules = entity.getBody();
            if (rules.getData().size() > 0) {
                savedRule = rules.getData().get(0);
            }
            if (savedRule == null) {
                savedRule = restTemplate.postForObject(baseUrl + "/api/rule", rule, RuleMetaData.class);
            }
            if (savedRule.getState() == ComponentLifecycleState.SUSPENDED) {
                restTemplate.postForLocation(
                        baseUrl + "/api/rule/" + savedRule.getId().getId().toString() + "/activate", null);
            }
        } catch (Exception e) {
            log.error("Unable to upload rule!");
            log.error("Cause:", e);
        }
    });

    Map<String, CustomerId> customerIdMap = new HashMap<>();
    customers.forEach(customer -> {
        try {
            Customer savedCustomer = null;
            TextPageData<Customer> customers;
            ResponseEntity<TextPageData<Customer>> entity = restTemplate.exchange(
                    baseUrl + "/api/customers?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null,
                    new ParameterizedTypeReference<TextPageData<Customer>>() {
                    }, 1000, customer.getTitle());
            customers = entity.getBody();
            if (customers.getData().size() > 0) {
                savedCustomer = customers.getData().get(0);
            }
            if (savedCustomer == null) {
                savedCustomer = restTemplate.postForObject(baseUrl + "/api/customer", customer, Customer.class);
            }
            customerIdMap.put(savedCustomer.getTitle(), savedCustomer.getId());
        } catch (Exception e) {
            log.error("Unable to upload customer!");
            log.error("Cause:", e);
        }
    });

    List<Device> loadedDevices = new ArrayList<>();

    Map<String, DeviceId> deviceIdMap = new HashMap<>();
    devices.forEach(device -> {
        try {
            CustomerId customerId = null;
            String customerTitle = customerDevices.get(device.getName());
            if (customerTitle != null) {
                customerId = customerIdMap.get(customerTitle);
            }
            Device savedDevice = null;
            TextPageData<Device> devices;
            if (customerId != null) {
                ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange(
                        baseUrl + "/api/customer/{customerId}/devices?limit={limit}&textSearch={textSearch}",
                        HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() {
                        }, customerId.getId().toString(), 1000, device.getName());
                devices = entity.getBody();
                if (devices.getData().size() > 0) {
                    savedDevice = devices.getData().get(0);
                }
            }
            if (savedDevice == null) {
                ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange(
                        baseUrl + "/api/tenant/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET,
                        null, new ParameterizedTypeReference<TextPageData<Device>>() {
                        }, 1000, device.getName());
                devices = entity.getBody();
                if (devices.getData().size() > 0) {
                    savedDevice = devices.getData().get(0);
                }
            }
            if (savedDevice == null) {
                savedDevice = restTemplate.postForObject(baseUrl + "/api/device", device, Device.class);
            }
            if (customerId != null && savedDevice.getCustomerId().isNullUid()) {
                restTemplate.postForLocation(baseUrl + "/api/customer/{customerId}/device/{deviceId}", null,
                        customerId.getId().toString(), savedDevice.getId().toString());
            }
            String deviceName = savedDevice.getName();
            DeviceId deviceId = savedDevice.getId();
            deviceIdMap.put(deviceName, deviceId);
            loadedDevices.add(savedDevice);
            DeviceCredentials credentials = restTemplate.getForObject(
                    baseUrl + "/api/device/{deviceId}/credentials", DeviceCredentials.class,
                    deviceId.getId().toString());
            loadedDevicesCredentialsMap.put(deviceId, credentials);

            Map<String, JsonNode> attributesMap = devicesAttributes.get(deviceName);
            if (attributesMap != null) {
                attributesMap.forEach((k, v) -> {
                    restTemplate.postForObject(baseUrl + "/api/plugins/telemetry/{deviceId}/{attributeScope}",
                            v, Void.class, deviceId.getId().toString(), k);
                });
            }
        } catch (Exception e) {
            log.error("Unable to upload device!");
            log.error("Cause:", e);
        }
    });

    devices = loadedDevices;

    Map<String, Dashboard> pendingDashboards = dashboards.stream()
            .collect(Collectors.toMap(Dashboard::getTitle, Function.identity()));
    Map<String, Dashboard> savedDashboards = new HashMap<>();
    while (pendingDashboards.size() != 0) {
        Dashboard savedDashboard = null;
        for (Dashboard dashboard : pendingDashboards.values()) {
            savedDashboard = getDashboardByName(restTemplate, baseUrl, dashboard);
            if (savedDashboard == null) {
                try {
                    Optional<String> dashboardConfigurationBody = resolveLinks(savedDashboards,
                            dashboard.getConfiguration());
                    if (dashboardConfigurationBody.isPresent()) {
                        dashboard.setConfiguration(objectMapper.readTree(dashboardConfigurationBody.get()));
                        JsonNode dashboardConfiguration = dashboard.getConfiguration();
                        JsonNode deviceAliases = dashboardConfiguration.get("deviceAliases");
                        deviceAliases.forEach(jsonNode -> {
                            String aliasName = jsonNode.get("alias").asText();
                            DeviceId deviceId = deviceIdMap.get(aliasName);
                            if (deviceId != null) {
                                ((ObjectNode) jsonNode).put("deviceId", deviceId.getId().toString());
                            }
                        });
                        savedDashboard = restTemplate.postForObject(baseUrl + "/api/dashboard", dashboard,
                                Dashboard.class);
                    }
                } catch (Exception e) {
                    log.error("Unable to upload dashboard!");
                    log.error("Cause:", e);
                }
            }
            if (savedDashboard != null) {
                break;
            }
        }
        if (savedDashboard != null) {
            savedDashboards.put(savedDashboard.getTitle(), savedDashboard);
            pendingDashboards.remove(savedDashboard.getTitle());
        } else {
            log.error("Unable to upload dashboards due to unresolved references!");
            break;
        }
    }

    dashboards = new ArrayList<>(savedDashboards.values());
}

From source file:pl.edu.pw.eiti.groupbuying.partner.android.ClaimCouponsActivity.java

@Override
public void onTaskFinished(AbstractGroupBuyingTask<?> task, TaskResult result) {
    FragmentManager manager = getSupportFragmentManager();
    manager.popBackStackImmediate();//from www  .j  av a  2s  .co m
    if (result.equals(TaskResult.SUCCESSFUL)) {
        couponInfo = null;
        showFragment(OPTIONS, false);
        ClaimResponse claimResponse = ((ClaimCouponTask) task).getClaimResponse();
        switch (claimResponse) {
        case CLAIMED:
            Toast.makeText(getApplicationContext(), "Coupon claimed successfully!", Toast.LENGTH_LONG).show();
            break;
        case ALREADY_USED:
            Toast.makeText(getApplicationContext(), "Coupon already used!", Toast.LENGTH_LONG).show();
            break;
        case EXPIRED:
            Toast.makeText(getApplicationContext(), "Coupon expired!", Toast.LENGTH_LONG).show();
            break;
        }
    } else if (result.equals(TaskResult.FAILED)) {
        Exception e = task.getException();
        if (e instanceof HttpClientErrorException) {
            HttpClientErrorException httpError = (HttpClientErrorException) e;
            if (httpError.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                getApplicationContext().getConnectionRepository()
                        .removeConnections(getApplicationContext().getConnectionFactory().getProviderId());
                showFragment(SIGN_IN, true);
            }
        } else if (e instanceof ExpiredAuthorizationException) {
            getApplicationContext().getConnectionRepository()
                    .removeConnections(getApplicationContext().getConnectionFactory().getProviderId());
            showFragment(SIGN_IN, true);
        } else if (e instanceof ResourceAccessException) {
            Throwable t = ((ResourceAccessException) e).getRootCause();
            if (t != null && t instanceof ApiErrorException) {
                ApiErrorException apiErrorException = (ApiErrorException) t;
                switch (apiErrorException.getApiError().getErrorCode()) {
                case INVALID_SECURITY_KEY:
                    Toast.makeText(getApplicationContext(), "Invalid security key.", Toast.LENGTH_LONG).show();
                    break;
                case COUPON_NOT_FOUND:
                    Toast.makeText(getApplicationContext(), "Invalid coupon ID.", Toast.LENGTH_LONG).show();
                    break;
                case INVALID_PARTNER:
                    Toast.makeText(getApplicationContext(), "Another partner's coupon.", Toast.LENGTH_LONG)
                            .show();
                    break;
                default:
                    Toast.makeText(getApplicationContext(), apiErrorException.getApiError().getErrorMessage(),
                            Toast.LENGTH_LONG).show();
                    break;
                }
                couponInfo = null;
                showFragment(OPTIONS, false);
            } else {
                showFragment(NO_INTERNET, true);
            }
        } else {
            Log.e(TAG, "Unknown error: " + e.getLocalizedMessage());
            Toast.makeText(getApplicationContext(), "Unknown error occurred. Please try again later.",
                    Toast.LENGTH_LONG).show();
            couponInfo = null;
            showFragment(OPTIONS, false);
        }
    }
}