Search in sources :

Example 1 with SynapseBadRequestException

use of org.sagebionetworks.client.exceptions.SynapseBadRequestException 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 SynapseBadRequestException

use of org.sagebionetworks.client.exceptions.SynapseBadRequestException in project Synapse-Repository-Services by Sage-Bionetworks.

the class IT990CrowdAuthentication method testCreateNewUser.

@Ignore
@Test
public void testCreateNewUser() throws Exception {
    // delete the user
    String username = StackConfiguration.getIntegrationTestUserThreeName();
    String password = StackConfiguration.getIntegrationTestUserThreePassword();
    synapse.login(username, password);
    // this says 'delete me'.  It only works for the specified integration test user
    synapse.deleteSynapseEntity(authEndpoint, "/user");
    // expect exception
    try {
        synapse.login(username, password);
        fail("exception expected");
    } catch (SynapseBadRequestException e) {
    // as expected
    }
    // now recreate it
    JSONObject userRequest = new JSONObject();
    userRequest.put("email", username);
    userRequest.put("password", password);
    userRequest.put("firstName", "dev");
    userRequest.put("lastName", "usr3");
    userRequest.put("displayName", "dev usr3");
    synapse.createAuthEntity("/user", userRequest);
    // now log in to verify it's there
    synapse.login(username, password);
}
Also used : SynapseBadRequestException(org.sagebionetworks.client.exceptions.SynapseBadRequestException) JSONObject(org.json.JSONObject) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

JSONObject (org.json.JSONObject)2 SynapseBadRequestException (org.sagebionetworks.client.exceptions.SynapseBadRequestException)2 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Header (org.apache.http.Header)1 HttpResponse (org.apache.http.HttpResponse)1 ParseException (org.apache.http.ParseException)1 ClientProtocolException (org.apache.http.client.ClientProtocolException)1 JSONException (org.json.JSONException)1 Ignore (org.junit.Ignore)1 Test (org.junit.Test)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 EntityHeader (org.sagebionetworks.repo.model.EntityHeader)1 HttpClientHelperException (org.sagebionetworks.utils.HttpClientHelperException)1