Search in sources :

Example 1 with HttpClientHelperException

use of org.sagebionetworks.utils.HttpClientHelperException in project Synapse-Repository-Services by Sage-Bionetworks.

the class Synapse method dispatchSynapseRequest.

/**
 * Convert exceptions emanating from the service to
 * Synapse[User|Service]Exception but let all other types of exceptions
 * bubble up as usual
 *
 * @param requestUrl
 * @param requestMethod
 * @param requestContent
 * @param requestHeaders
 * @return
 */
protected JSONObject dispatchSynapseRequest(String endpoint, String uri, String requestMethod, String requestContent, Map<String, String> requestHeaders) throws SynapseException {
    if (requestProfile && !requestMethod.equals("DELETE")) {
        requestHeaders.put(REQUEST_PROFILE_DATA, "true");
    } else {
        if (requestHeaders.containsKey(REQUEST_PROFILE_DATA))
            requestHeaders.remove(REQUEST_PROFILE_DATA);
    }
    // remove session token if it is null
    if (requestHeaders.containsKey(SESSION_TOKEN_HEADER) && requestHeaders.get(SESSION_TOKEN_HEADER) == null) {
        requestHeaders.remove(SESSION_TOKEN_HEADER);
    }
    JSONObject results = null;
    URL requestUrl = null;
    try {
        URL parsedEndpoint = new URL(endpoint);
        String endpointPrefix = parsedEndpoint.getPath();
        String endpointLocation = endpoint.substring(0, endpoint.length() - endpointPrefix.length());
        requestUrl = (uri.startsWith(endpointPrefix)) ? new URL(endpointLocation + uri) : new URL(endpoint + uri);
        HttpResponse response = clientProvider.performRequest(requestUrl.toString(), requestMethod, requestContent, requestHeaders);
        if (requestProfile && !requestMethod.equals("DELETE")) {
            Header header = response.getFirstHeader(PROFILE_RESPONSE_OBJECT_HEADER);
            String encoded = header.getValue();
            String decoded = new String(Base64.decodeBase64(encoded.getBytes("UTF-8")), "UTF-8");
            profileData = new JSONObject(decoded);
        } else {
            profileData = null;
        }
        String responseBody = (null != response.getEntity()) ? EntityUtils.toString(response.getEntity()) : null;
        if (null != responseBody && responseBody.length() > 0) {
            try {
                results = new JSONObject(responseBody);
            } catch (JSONException jsone) {
                throw new SynapseServiceException("responseBody: <<" + responseBody + ">>", jsone);
            }
            if (log.isDebugEnabled()) {
                if (authEndpoint.equals(endpoint)) {
                    log.debug(requestMethod + " " + requestUrl + " : (not logging auth request details)");
                } else {
                    log.debug(requestMethod + " " + requestUrl + " : " + results.toString(JSON_INDENT));
                }
            }
        }
    } catch (HttpClientHelperException e) {
        // Well-handled server side exceptions come back as JSON, attempt to
        // deserialize and convert the error
        // assume a service exception
        int statusCode = 500;
        statusCode = e.getHttpStatus();
        String response = "";
        String resultsStr = "";
        try {
            response = e.getResponse();
            if (null != response && response.length() > 0) {
                try {
                    results = new JSONObject(response);
                } catch (JSONException jsone) {
                    throw new SynapseServiceException("Failed to parse: " + response, jsone);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved " + requestUrl + " : " + results.toString(JSON_INDENT));
                }
                if (results != null)
                    resultsStr = results.getString("reason");
            }
            String exceptionContent = "Service Error(" + statusCode + "): " + resultsStr + " " + e.getMessage();
            if (statusCode == 401) {
                throw new SynapseUnauthorizedException(exceptionContent);
            } else if (statusCode == 403) {
                throw new SynapseForbiddenException(exceptionContent);
            } else if (statusCode == 404) {
                throw new SynapseNotFoundException(exceptionContent);
            } else if (statusCode == 400) {
                throw new SynapseBadRequestException(exceptionContent);
            } else if (statusCode >= 400 && statusCode < 500) {
                throw new SynapseUserException(exceptionContent);
            } else {
                throw new SynapseServiceException("request content: " + requestContent + " exception content: " + exceptionContent);
            }
        } catch (JSONException jsonEx) {
            // return the response as-is since it is not JSON
            throw new SynapseServiceException(jsonEx);
        } catch (ParseException parseEx) {
            throw new SynapseServiceException(parseEx);
        }
    }// end catch
     catch (MalformedURLException e) {
        throw new SynapseServiceException(e);
    } catch (ClientProtocolException e) {
        throw new SynapseServiceException(e);
    } catch (IOException e) {
        throw new SynapseServiceException(e);
    } catch (JSONException e) {
        throw new SynapseServiceException(e);
    }
    return results;
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException) URL(java.net.URL) HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException) ClientProtocolException(org.apache.http.client.ClientProtocolException) SynapseBadRequestException(org.sagebionetworks.client.exceptions.SynapseBadRequestException) SynapseUnauthorizedException(org.sagebionetworks.client.exceptions.SynapseUnauthorizedException) SynapseForbiddenException(org.sagebionetworks.client.exceptions.SynapseForbiddenException) JSONObject(org.json.JSONObject) Header(org.apache.http.Header) EntityHeader(org.sagebionetworks.repo.model.EntityHeader) SynapseUserException(org.sagebionetworks.client.exceptions.SynapseUserException) SynapseServiceException(org.sagebionetworks.client.exceptions.SynapseServiceException) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException) ParseException(org.apache.http.ParseException)

Example 2 with HttpClientHelperException

use of org.sagebionetworks.utils.HttpClientHelperException in project Synapse-Repository-Services by Sage-Bionetworks.

the class Synapse method getSynapseTermsOfUse.

public String getSynapseTermsOfUse() throws SynapseException {
    try {
        HttpResponse response = clientProvider.performRequest(authEndpoint + "/termsOfUse.html", "GET", null, null);
        InputStream is = response.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        int i = is.read();
        while (i > 0) {
            sb.append((char) i);
            i = is.read();
        }
        is.close();
        return sb.toString();
    } catch (IOException e) {
        throw new SynapseException(e);
    } catch (HttpClientHelperException e) {
        throw new SynapseException(e);
    }
}
Also used : SynapseException(org.sagebionetworks.client.exceptions.SynapseException) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException)

Example 3 with HttpClientHelperException

use of org.sagebionetworks.utils.HttpClientHelperException in project Synapse-Repository-Services by Sage-Bionetworks.

the class SynapseTest method testTermsOfUseNotAccepted.

@Test(expected = SynapseTermsOfUseException.class)
public void testTermsOfUseNotAccepted() throws Exception {
    HttpClientHelperException simulatedHttpException = new HttpClientHelperException() {

        public int getHttpStatus() {
            return 403;
        }
    };
    when(mockProvider.performRequest(any(String.class), any(String.class), any(String.class), (Map<String, String>) anyObject())).thenThrow(simulatedHttpException);
    synapse.login("username", "password", false);
}
Also used : HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException) Test(org.junit.Test)

Example 4 with HttpClientHelperException

use of org.sagebionetworks.utils.HttpClientHelperException in project Synapse-Repository-Services by Sage-Bionetworks.

the class CrowdAuthUtil method executeRequest.

public static byte[] executeRequest(String requestURL, String requestMethod, String requestContent, HttpStatus expectedRc, String failureReason) throws AuthenticationException {
    try {
        HttpResponse response = null;
        try {
            response = HttpClientHelper.performRequest(DefaultHttpClientSingleton.getInstance(), requestURL, requestMethod, requestContent, getHeaders());
            if (expectedRc.value() != response.getStatusLine().getStatusCode()) {
                throw new AuthenticationException(response.getStatusLine().getStatusCode(), failureReason, null);
            }
            byte[] respBody = (readInputStream(response.getEntity().getContent())).getBytes();
            return respBody;
        } catch (HttpClientHelperException hche) {
            throw new AuthenticationException(hche.getHttpStatus(), failureReason, hche);
        }
    } catch (IOException e) {
        throw new AuthenticationException(500, failureReason, e);
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException)

Example 5 with HttpClientHelperException

use of org.sagebionetworks.utils.HttpClientHelperException in project Synapse-Repository-Services by Sage-Bionetworks.

the class BaseControllerTest method testCSExceptionScrubbing.

/**
 */
@Test
public void testCSExceptionScrubbing() {
    SearchController controller = new SearchController();
    HttpServletRequest request = new MockHttpServletRequest();
    HttpClientHelperException ex = new HttpClientHelperException("Connect to search-prod-20120206-vigj35bjslyimyxftqh4mludxm.us-east-1.cloudsearch.amazonaws.com:80 timed out");
    // org.apache.http.conn.ConnectTimeoutException: Connect to
    // search-prod-20120206-vigj35bjslyimyxftqh4mludxm.us-east-1.cloudsearch.amazonaws.com:80
    // timed out
    ErrorResponse response = controller.handleException(ex, request);
    assertEquals("search failed, try again", response.getReason());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException) ErrorResponse(org.sagebionetworks.repo.model.ErrorResponse) Test(org.junit.Test)

Aggregations

HttpClientHelperException (org.sagebionetworks.utils.HttpClientHelperException)5 IOException (java.io.IOException)3 HttpResponse (org.apache.http.HttpResponse)3 Test (org.junit.Test)2 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 Header (org.apache.http.Header)1 ParseException (org.apache.http.ParseException)1 ClientProtocolException (org.apache.http.client.ClientProtocolException)1 JSONException (org.json.JSONException)1 JSONObject (org.json.JSONObject)1 SynapseBadRequestException (org.sagebionetworks.client.exceptions.SynapseBadRequestException)1 SynapseException (org.sagebionetworks.client.exceptions.SynapseException)1 SynapseForbiddenException (org.sagebionetworks.client.exceptions.SynapseForbiddenException)1 SynapseNotFoundException (org.sagebionetworks.client.exceptions.SynapseNotFoundException)1 SynapseServiceException (org.sagebionetworks.client.exceptions.SynapseServiceException)1 SynapseUnauthorizedException (org.sagebionetworks.client.exceptions.SynapseUnauthorizedException)1 SynapseUserException (org.sagebionetworks.client.exceptions.SynapseUserException)1