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

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

Introduction

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

Prototype

public String getResponseBodyAsString() 

Source Link

Document

Return the response body as a string.

Usage

From source file:com.brightcove.zencoder.client.ZencoderClient.java

/**
 * The VOD+Live usage for the specified time period.
 *
 * NOTE: It's important to note that our service operates in the UTC time zone
 * (including billing periods). All dates and times reported will be in UTC.
 *
 * @see https://app.zencoder.com/docs/api/reports/all
 * @see https://app.zencoder.com/docs/api/encoding/job/grouping
 * @param from/*from  w w  w  .  j av  a  2  s  .com*/
 *            (optional) Start date (default: 30 days ago).
 * @param to
 *            (optional) End date (default: yesterday).
 * @param grouping
 *            (optional) Minute usage for only one report grouping (default: none).
 * @return The VOD+Live usage for the specified time period.
 * @throws ZencoderClientException
 */
public ZencoderAllUsage getUsageForVodAndLive(Date from, Date to, String grouping)
        throws ZencoderClientException {
    String url = api_url + "/reports/all" + createUsageQueryArgString(from, to, grouping);

    HttpHeaders headers = getHeaders();
    @SuppressWarnings("rawtypes")
    HttpEntity entity = new HttpEntity<String>("", headers);

    ResponseEntity<String> response = null;
    try {
        response = rt.exchange(url, HttpMethod.GET, entity, String.class, new HashMap<String, Object>());

    } catch (HttpClientErrorException hcee) {
        throw new ZencoderClientException(hcee.getResponseBodyAsString(), hcee);
    }

    ZencoderAllUsage usage = null;
    try {
        usage = mapper.readValue(response.getBody(), ZencoderAllUsage.class);

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to deserialize ZencoderLiveUsage as JSON", e);
    }

    return usage;
}

From source file:com.brightcove.zencoder.client.ZencoderClient.java

/**
 * Creates a Zencoder Account.//from ww w  .j a  v  a  2s. c om
 * New accounts will be created under the Test (Free) plan.
 * NOTE: A password will be generated and returned if not specified.
 *
 * @see https://app.zencoder.com/docs/api/accounts/create
 * @see http://zencoder.com/en/terms
 * @param account The account to create.
 * @return The created account with it's API key and password.
 * @throws ZencoderClientException
 */
public ZencoderAccount createAccount(ZencoderAccount account) throws ZencoderClientException {
    String url = api_url + "/account";

    String body = null;
    try {
        body = mapper.writeValueAsString(account);

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to serialize ZencoderAccount as JSON", e);
    }

    HttpHeaders headers = getHeaders();
    @SuppressWarnings("rawtypes")
    HttpEntity entity = new HttpEntity<String>(body, headers);

    ResponseEntity<String> response = null;
    try {
        response = rt.exchange(url, HttpMethod.POST, entity, String.class, new HashMap<String, Object>());

    } catch (HttpClientErrorException hcee) {
        throw new ZencoderClientException(hcee.getResponseBodyAsString(), hcee);
    }

    ZencoderAccount zencoderAccountResponse = null;
    try {
        zencoderAccountResponse = mapper.readValue(response.getBody(), ZencoderAccount.class);

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to deserialize ZencoderAccount as JSON", e);
    }
    return zencoderAccountResponse;
}

From source file:com.brightcove.zencoder.client.ZencoderClient.java

/**
 * Creates a VOD transcode job.//www . j  ava2  s. c o m
 * 
 * @see https://app.zencoder.com/docs/api/jobs/create
 * @param job
 * @return ZencoderJobResponse
 * @throws ZencoderClientException
 */
public ZencoderCreateJobResponse createZencoderJob(ZencoderCreateJobRequest job)
        throws ZencoderClientException {
    String url = api_url + "/jobs";
    String body = null;
    try {
        body = mapper.writeValueAsString(job);

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to serialize ZencoderCreateJobRequest as JSON", e);
    }

    HttpHeaders headers = getHeaders();
    @SuppressWarnings("rawtypes")
    HttpEntity entity = new HttpEntity<String>(body, headers);

    ResponseEntity<String> response = null;
    try {
        response = rt.exchange(url, HttpMethod.POST, entity, String.class, new HashMap<String, Object>());

    } catch (HttpClientErrorException hcee) {
        throw new ZencoderClientException(hcee.getResponseBodyAsString(), hcee);
    }

    ZencoderCreateJobResponse zencoderJobResponse = null;
    try {
        zencoderJobResponse = mapper.readValue(response.getBody(), ZencoderCreateJobResponse.class);

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to deserialize ZencoderCreateJobResponse as JSON", e);
    }

    return zencoderJobResponse;
}

From source file:com.brightcove.zencoder.client.ZencoderClient.java

/**
 * Lists jobs with pagination./*from w  ww  . j  av a  2 s  .c  o  m*/
 *
 * @param page Which page to return
 * @param per_page How many jobs per page to return
 * @return A list of jobs.
 * @throws ZencoderClientException
 */
public List<ZencoderJobDetail> listJobs(Integer page, Integer per_page) throws ZencoderClientException {
    String url = api_url + "/jobs";
    if (page != null || per_page != null) {
        if (page == null) {
            page = 1;
        }
        if (per_page == null) {
            per_page = 50;
        }
        url = url + "?page=" + page + "&per_page=" + per_page;
    }

    HttpHeaders headers = getHeaders();
    @SuppressWarnings("rawtypes")
    HttpEntity entity = new HttpEntity<String>("", headers);

    ResponseEntity<String> response = null;
    try {
        response = rt.exchange(url, HttpMethod.GET, entity, String.class, new HashMap<String, Object>());

    } catch (HttpClientErrorException hcee) {
        throw new ZencoderClientException(hcee.getResponseBodyAsString(), hcee);
    }

    List<ZencoderJobDetailResponse> jobs = null;
    try {
        TypeFactory typeFactory = TypeFactory.defaultInstance();
        jobs = mapper.readValue(response.getBody(),
                typeFactory.constructCollectionType(List.class, ZencoderJobDetailResponse.class));

    } catch (Exception e) {
        throw new ZencoderClientException("Unable to deserialize ZencoderCreateJobResponse as JSON", e);
    }

    List<ZencoderJobDetail> job_details = new ArrayList<ZencoderJobDetail>();
    for (ZencoderJobDetailResponse job : jobs) {
        job_details.add(job.getJob());
    }

    return job_details;
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;//  w  w w  .ja v a  2s .c o m
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
    headers.add("X-Requested-By", "zeppelin");
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
        headers.add(entry.getKey(), entry.getValue());
    }
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    } catch (RestClientException e) {
        // Exception happens when kerberos is enabled.
        if (e.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
            if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
                throw new SessionNotFoundException(cause.getResponseBodyAsString());
            }
            throw new LivyException(cause.getResponseBodyAsString() + "\n"
                    + ExceptionUtils.getFullStackTrace(ExceptionUtils.getRootCause(e)));
        }
        if (e instanceof HttpServerErrorException) {
            HttpServerErrorException errorException = (HttpServerErrorException) e;
            String errorResponse = errorException.getResponseBodyAsString();
            if (errorResponse.contains("Session is in state dead")) {
                throw new SessionDeadException();
            }
            throw new LivyException(errorResponse, e);
        }
        throw new LivyException(e);
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
            response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException(
                    "No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}

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

/**
 * Get a connection to the Google APIs. Will attempt to refresh tokens if they are invalid. If unable to refresh return a
 * GoogleDocsRefreshTokenException.//from   w w  w.  j av a 2  s  . c  o m
 * 
 * @return
 * @throws GoogleDocsAuthenticationException
 * @throws GoogleDocsRefreshTokenException
 * @throws GoogleDocsServiceException
 */
private Connection<Google> getConnection()
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    Connection<Google> connection = null;

    // OAuth credentials for the current user, if the exist
    OAuth2CredentialsInfo credentialInfo = oauth2CredentialsStoreService
            .getPersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM);

    if (credentialInfo != null) {
        log.debug("OAuth Access Token Exists: " + credentialInfo.getOAuthAccessToken());
        AccessGrant accessGrant = new AccessGrant(credentialInfo.getOAuthAccessToken());

        try {
            log.debug("Attempt to create OAuth Connection");
            connection = connectionFactory.createConnection(accessGrant);
        } catch (HttpClientErrorException hcee) {
            log.debug(hcee.getResponseBodyAsString());
            if (hcee.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) {
                try {
                    accessGrant = refreshAccessToken();
                    connection = connectionFactory.createConnection(accessGrant);
                } catch (GoogleDocsRefreshTokenException gdrte) {
                    throw gdrte;
                } catch (GoogleDocsServiceException gdse) {
                    throw gdse;
                }
            } else {
                throw new GoogleDocsServiceException(hcee.getMessage(), hcee, hcee.getStatusCode().value());
            }
        } catch (HttpServerErrorException hsee) {
            throw new GoogleDocsServiceException(hsee.getMessage(), hsee, hsee.getStatusCode().value());
        }
    }

    log.debug("Connection Created");
    return connection;
}

From source file:org.apache.zeppelin.livy.BaseLivyInterprereter.java

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;//from w w w .  j a  va 2  s . c  o m
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                e.getResponseBodyAsString()));
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
            response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches("\"Session '\\d+' not found.\"")) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException(
                    "No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(),
                responseString));
    }
}