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

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

Introduction

In this page you can find the example usage for org.springframework.web.client HttpClientErrorException 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:org.cloudfoundry.caldecott.client.TunnelHelper.java

private static String testUriSchemes(CloudFoundryClient client, String[] uriSchemes, String uriAuthority) {
    int i = 0;//from w  w w.j  a v  a2  s. c o m
    int retries = 0;
    String scheme = null;
    while (i < uriSchemes.length) {
        scheme = uriSchemes[i];
        String uriToUse = scheme + "//" + uriAuthority;
        try {
            getTunnelProtocolVersion(client, uriToUse);
            break;
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                if (retries < 10) {
                    retries++;
                } else {
                    throw new TunnelException("Not able to locate tunnel server at: " + uriToUse, e);
                }
            } else {
                throw new TunnelException("Error accessing tunnel server at: " + uriToUse, e);
            }
        } catch (ResourceAccessException e) {
            if (e.getMessage().contains("refused") || e.getMessage().contains("unable")) {
                i++;
            } else {
                throw e;
            }
        } catch (RuntimeException e) {
            throw e;
        }
    }
    return scheme;
}

From source file:io.syndesis.rest.v1.handler.exception.HttpClientErrorExceptionMapper.java

@Override
public Response toResponse(HttpClientErrorException exception) {
    RestError error = new RestError(exception.getMessage(), exception.getMessage(),
            ErrorMap.from(new String(exception.getResponseBodyAsByteArray(), StandardCharsets.UTF_8)),
            exception.getStatusCode().value());
    return Response.status(exception.getStatusCode().value()).type(MediaType.APPLICATION_JSON_TYPE)
            .entity(error).build();//w w w.j a v  a2s  . co m
}

From source file:com.github.cjm.service.BaseService.java

public ResourceCollection load(String resource, Class clazz, int page) {

    StringBuilder uri = new StringBuilder(MOVIEDB_URL);
    uri.append(resource);//from   w w w.jav a  2  s.  c  o m
    uri.append("?api_key=").append(apiKey);
    if (page > 1) {
        uri.append("&page=").append(page);
    }

    RestTemplate restTemplate = new RestTemplate();
    ResourceCollection<T> resourceCollection = new ResourceCollection<>();
    String data = null;
    try {
        data = restTemplate.getForObject(uri.toString(), String.class);
    } catch (HttpClientErrorException e) {
        log.warn(e.getMessage());
    }
    if (data != null) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            TypeFactory t = TypeFactory.defaultInstance();
            resourceCollection = mapper.readValue(data, t.constructType(clazz));
        } catch (IOException ex) {
            log.error("ObjectMapper exception: ", ex);
        }
    }
    return resourceCollection;
}

From source file:com.github.ibm.domino.client.DominoRestClient.java

public ResponseEntity<Object> postEvent(CalendarEventsWrapper events) {

    init("events");
    try {//from www  .  j a  v  a 2s  .co  m

        ResponseEntity<Object> result = restTemplate.postForEntity(getUri(), events, Object.class);
        return result;
    } catch (HttpClientErrorException e) {
        System.out.println(e.getMessage());
    }

    return null;

}

From source file:se.malmo.www.kontaktruta.service.ContactServiceImpl.java

@Override
public <T> T getContactList(String contactType, String query, Class<T> type) {
    query = "search?q=" + query;
    T contacts = null;/*  w  ww . ja  v a  2s.co m*/
    try {
        contacts = restTemplate.getForObject(String.format(BASEURL, contactType, query), type);
    } catch (HttpClientErrorException ex) {
        Logger.getLogger(ContactServiceImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        return contacts;
    }
    return contacts;
}

From source file:se.malmo.www.kontaktruta.service.ContactServiceImpl.java

@Override
@Cacheable(cacheName = "contacts", cacheNull = false, keyGenerator = @KeyGenerator(name = "StringCacheKeyGenerator", properties = {
        @Property(name = "includeMethod", value = "false"),
        @Property(name = "includeParameterTypes", value = "false")

}))/*from   www .j  av a2s . c o  m*/
public <T extends APISuggestion> T getContact(@PartialCacheKey String contactType, @PartialCacheKey String id,
        Class<T> classType) {
    T contact = null;
    try {
        contact = restTemplate.getForObject(
                String.format(BASEURL, contactType, id).replace("&app_token", "?app_token"), classType);
        Logger.getLogger(ContactServiceImpl.class.getName()).log(Level.INFO, new StringBuilder(" found: ")
                .append(contact.getName()).append(" for id:").append(id).toString());
    } catch (HttpClientErrorException ex) {
        Logger.getLogger(ContactServiceImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        return contact;
    }
    return contact;
}

From source file:com.compomics.colims.core.service.impl.UniProtServiceImpl.java

@Override
public Map<String, String> getUniProtByAccession(String accession) throws RestClientException, IOException {
    Map<String, String> uniProt = new HashMap<>();

    try {//  ww  w .j  a va  2s.  c o m
        // Set XML content type explicitly to force response in XML (If not spring gets response in JSON)
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

        ResponseEntity<String> response = restTemplate.exchange(UNIPROT_BASE_URL + "/" + accession + ".xml",
                HttpMethod.GET, entity, String.class);
        String responseBody = response.getBody();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(responseBody));

        Document document = (Document) builder.parse(is);
        document.getDocumentElement().normalize();
        NodeList recommendedName = document.getElementsByTagName("recommendedName");

        Node node = recommendedName.item(0);
        Element element = (Element) node;
        if (element.getElementsByTagName("fullName").item(0).getTextContent() != null
                && !element.getElementsByTagName("fullName").item(0).getTextContent().equals("")) {
            uniProt.put("description", element.getElementsByTagName("fullName").item(0).getTextContent());
        }

        NodeList organism = document.getElementsByTagName("organism");
        node = organism.item(0);
        element = (Element) node;
        if (element.getElementsByTagName("name").item(0).getTextContent() != null
                && !element.getElementsByTagName("name").item(0).getTextContent().equals("")) {
            uniProt.put("species", element.getElementsByTagName("name").item(0).getTextContent());
        }

        NodeList dbReference = document.getElementsByTagName("dbReference");
        node = dbReference.item(0);
        element = (Element) node;
        if (element.getAttribute("id") != null && !element.getAttribute("id").equals("")) {
            uniProt.put("taxid", element.getAttribute("id"));
        }

    } catch (HttpClientErrorException ex) {
        LOGGER.error(ex.getMessage(), ex);
        //ignore the exception if the namespace doesn't correspond to an ontology
        if (!ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            throw ex;
        }
    } catch (ParserConfigurationException | SAXException ex) {
        java.util.logging.Logger.getLogger(UniProtServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return uniProt;
}

From source file:org.glytoucan.admin.service.AuthService.java

/**
 * @param auth/*w  w w. ja va 2  s. c o  m*/
 * @return
 * @throws UserException
 */
@Transactional
public ResponseMessage authenticate(Authentication auth) {
    System.out.println("user:>" + auth.getId());
    System.out.println("key:>" + auth.getApiKey());
    //    String id = auth.getId();

    ResponseMessage rm = new ResponseMessage();
    rm.setErrorCode(ErrorCode.AUTHENTICATION_SUCCESS.toString());
    try {
        //      if (StringUtils.contains(id, "@")) {
        //        id = userProcedure.getIdByEmail(id);
        //      }
        if (!userProcedure.checkApiKey(auth.getId(), auth.getApiKey())) {
            DefaultOAuth2AccessToken defToken = new DefaultOAuth2AccessToken(auth.getApiKey());
            DefaultOAuth2ClientContext defaultContext = new DefaultOAuth2ClientContext();
            defaultContext.setAccessToken(defToken);
            OAuth2RestOperations rest = new OAuth2RestTemplate(googleOAuth2Details(), defaultContext);
            UserInfo user = null;
            try {
                final ResponseEntity<UserInfo> userInfoResponseEntity = rest
                        .getForEntity("https://www.googleapis.com/oauth2/v2/userinfo", UserInfo.class);
                logger.debug("userInfo:>" + userInfoResponseEntity.toString());
                user = userInfoResponseEntity.getBody();
            } catch (HttpClientErrorException e) {
                logger.debug("oauth failed:>" + e.getMessage());
                rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
                rm.setMessage("oauth failed:>" + e.getMessage());
                return rm;
            }
            //        String idFromEmail = userProcedure.getIdByEmail(user.getEmail());
            if (!StringUtils.equals(user.getEmail(), auth.getId())) {
                rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
                rm.setMessage("id do not equal:>" + user.getEmail() + "<> " + auth.getId());
                return rm;
            }
        } else {
            return rm;
        }
    } catch (UserException e1) {
        rm.setErrorCode(ErrorCode.AUTHENTICATION_FAILURE.toString());
        rm.setMessage("rdf checks failed:>" + e1.getMessage());
        return rm;
    }

    return rm;
}

From source file:org.alfresco.dropbox.webscripts.PostNode.java

private void add(NodeRef nodeRef) {
    Metadata metadata = null;//from w w w .  j  a va  2 s .com

    if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_CONTENT)) {
        metadata = dropboxService.putFile(nodeRef, false);
    } else if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_FOLDER)) {
        try {
            metadata = dropboxService.createFolder(nodeRef);

            logger.debug("Dropbox: Add: createFolder: " + nodeRef.toString());
        } catch (HttpClientErrorException hcee) {
            if (hcee.getMessage().equals(FOLDER_EXISTS)) {
                metadata = dropboxService.getMetadata(nodeRef);
            } else {
                throw new WebScriptException(hcee.getMessage());
            }
        }
    }

    // update/add the Dropbox aspect and set its properties;
    if (metadata != null) {
        dropboxService.persistMetadata(metadata, nodeRef);
    } else {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "Dropbox metadata maybe out of sync for " + nodeRef);
    }
}

From source file:com.goldengekko.meetr.itest.AuthITest.java

@Test
public void testNegativeUserAccess() {
    //        final String API_URL = DomainHelper.getEndpoints(BASE_URL);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", DomainHelper.J_BASIC_ITEST);
    HttpEntity requestEntity = new HttpEntity(headers);

    // negative test first:
    try {/*from   w w  w  .  ja  v a 2  s. co m*/
        ResponseEntity<MeetingPage> noTokenResponse = restTemplate.exchange(API_URL + "/meeting/v10",
                HttpMethod.GET, requestEntity, MeetingPage.class);
        fail("Expected exception");
    } catch (HttpClientErrorException expected) {
        assertEquals("403 Forbidden", expected.getMessage());
    }

    // then with unregistered token:
    try {
        ResponseEntity<MeetingPage> unregisteredResponse = restTemplate.exchange(
                API_URL + "/meeting/v10?access_token=itest", HttpMethod.GET, requestEntity, MeetingPage.class);
        fail("Expected exception");
    } catch (HttpClientErrorException expected) {
        assertEquals("403 Forbidden", expected.getMessage());
    }
}