Search in sources :

Example 1 with Status

use of com.sun.jersey.api.client.ClientResponse.Status in project coprhd-controller by CoprHD.

the class IsilonApi method createDir.

/**
 * Create a directory with the path specified
 *
 * @param fspath
 *            Dir path to be created
 * @param recursive
 *            if true, will create parent recursively if it doesn't
 *            exist
 * @throws IsilonException
 */
public void createDir(String fspath, boolean recursive) throws IsilonException {
    fspath = scrubPath(fspath);
    ClientResponse resp = null;
    try {
        // check if already exists
        if (existsDir(fspath)) {
            return;
        }
        fspath = URLEncoder.encode(fspath, "UTF-8");
        MultivaluedMap<String, String> queryParams = null;
        if (recursive) {
            queryParams = new MultivaluedMapImpl();
            queryParams.add("recursive", "1");
        }
        sLogger.debug("IsilonApi createDir {} - start", fspath);
        resp = _client.put(_baseUrl.resolve(URI_IFS.resolve(fspath)), queryParams, "");
        sLogger.debug("IsilonApi createDir {} - complete", fspath);
        if (resp.getStatus() != 200) {
            processErrorResponse("create directory", fspath, resp.getStatus(), resp.getEntity(JSONObject.class));
        }
    } catch (IsilonException ie) {
        throw ie;
    } catch (Exception e) {
        if (e.getCause() instanceof ConnectException) {
            throw IsilonException.exceptions.unableToConnect(_baseUrl, e);
        }
        final Status status = resp != null ? resp.getClientResponseStatus() : Status.NOT_FOUND;
        throw IsilonException.exceptions.createDirFailed(fspath, status, e);
    } finally {
        if (resp != null) {
            resp.close();
        }
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) Status(com.sun.jersey.api.client.ClientResponse.Status) JSONObject(org.codehaus.jettison.json.JSONObject) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) ConnectException(java.net.ConnectException) JSONException(org.codehaus.jettison.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConnectException(java.net.ConnectException)

Example 2 with Status

use of com.sun.jersey.api.client.ClientResponse.Status in project coprhd-controller by CoprHD.

the class KHRequests method deleteRequest.

/*
     * Send DELETE request to KittyHawk server, and handle redirect/cookies
     * 
     * @param resource webResource
     * 
     * @param param parameters for delete
     * 
     * @throws VNXeException
     */
public ClientResponse deleteRequest(Object param) throws VNXeException {
    _logger.debug("delete data: " + _url);
    ClientResponse response = sendDeleteRequest(param);
    Status statusCode = response.getClientResponseStatus();
    if (statusCode == ClientResponse.Status.OK || statusCode == ClientResponse.Status.ACCEPTED || statusCode == ClientResponse.Status.NO_CONTENT) {
        return response;
    } else if (response.getClientResponseStatus() == ClientResponse.Status.UNAUTHORIZED) {
        authenticate();
        response = sendDeleteRequest(param);
        statusCode = response.getClientResponseStatus();
        if (statusCode == ClientResponse.Status.OK || statusCode == ClientResponse.Status.ACCEPTED || statusCode == ClientResponse.Status.NO_CONTENT) {
            return response;
        }
    }
    int redirectTimes = 1;
    // handle redirect
    while (response.getClientResponseStatus() == ClientResponse.Status.FOUND && redirectTimes < VNXeConstants.REDIRECT_MAX) {
        String code = response.getClientResponseStatus().toString();
        String data = response.getEntity(String.class);
        _logger.debug("Returned code: {} returned data: ", code, data);
        WebResource resource = handelRedirect(response);
        if (resource != null) {
            response = buildRequest(resource.getRequestBuilder()).entity(param).delete(ClientResponse.class);
            redirectTimes++;
        } else {
            // could not find the redirect url, return
            _logger.error(String.format("The post request to: %s failed with: %s %s", _url, response.getClientResponseStatus().toString(), response.getEntity(String.class)));
            throw VNXeException.exceptions.unexpectedDataError("Got redirect status code, but could not get redirected URL");
        }
    }
    if (redirectTimes >= VNXeConstants.REDIRECT_MAX) {
        _logger.error("redirected too many times for the request {} ", _url);
        throw VNXeException.exceptions.unexpectedDataError("Redirected too many times while sending the request for " + _url);
    }
    checkResponse(response, DELETE_REQUEST);
    return response;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) Status(com.sun.jersey.api.client.ClientResponse.Status) WebResource(com.sun.jersey.api.client.WebResource)

Example 3 with Status

use of com.sun.jersey.api.client.ClientResponse.Status in project coprhd-controller by CoprHD.

the class KHRequests method checkResponse.

private void checkResponse(ClientResponse response, String requestType) {
    Status status = response.getClientResponseStatus();
    if (status != ClientResponse.Status.OK && status != ClientResponse.Status.ACCEPTED && status != ClientResponse.Status.NO_CONTENT) {
        // error
        if (status == ClientResponse.Status.UNAUTHORIZED) {
            throw VNXeException.exceptions.authenticationFailure(_url.toString());
        }
        String code = null;
        code = Integer.toString(response.getStatus());
        StringBuilder errorBuilder = new StringBuilder();
        errorBuilder.append(requestType).append(" request to:");
        errorBuilder.append(_url);
        errorBuilder.append(" failed with status code: ");
        errorBuilder.append(code);
        errorBuilder.append(" ");
        errorBuilder.append("message: ");
        String msg = response.getEntity(String.class);
        errorBuilder.append(msg);
        _logger.error(errorBuilder.toString());
        throw VNXeException.exceptions.vnxeCommandFailed(_url, code, msg);
    }
}
Also used : Status(com.sun.jersey.api.client.ClientResponse.Status)

Example 4 with Status

use of com.sun.jersey.api.client.ClientResponse.Status in project ORCID-Source by ORCID.

the class OrcidClientCredentialEndPointDelegatorImpl method obtainOauth2Token.

@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
    String code = formParams.getFirst("code");
    String clientId = formParams.getFirst(OrcidOauth2Constants.CLIENT_ID_PARAM);
    String state = formParams.getFirst(OrcidOauth2Constants.STATE_PARAM);
    String redirectUri = formParams.getFirst(OrcidOauth2Constants.REDIRECT_URI_PARAM);
    String refreshToken = formParams.getFirst(OrcidOauth2Constants.REFRESH_TOKEN);
    String scopeList = formParams.getFirst(OrcidOauth2Constants.SCOPE_PARAM);
    String grantType = formParams.getFirst(OrcidOauth2Constants.GRANT_TYPE);
    Boolean revokeOld = formParams.containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(formParams.getFirst(OrcidOauth2Constants.REVOKE_OLD)) : true;
    Long expiresIn = calculateExpiresIn(formParams);
    String bearerToken = null;
    Set<String> scopes = new HashSet<String>();
    if (StringUtils.isNotEmpty(scopeList)) {
        scopes = OAuth2Utils.parseParameterList(scopeList);
    }
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        if (!PojoUtil.isEmpty(authorization)) {
            if ((authorization.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = authorization.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                bearerToken = authHeaderValue;
                if (PojoUtil.isEmpty(bearerToken)) {
                    throw new IllegalArgumentException("Refresh token request doesnt include the authorization");
                }
            }
        }
    }
    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.error("Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }
    /**
     * Patch, update any orcid-grants scope to funding scope
     */
    for (String scope : scopes) {
        if (scope.contains("orcid-grants")) {
            String newScope = scope.replace("orcid-grants", "funding");
            LOGGER.info("Client {} provided a grants scope {} which will be updated to {}", new Object[] { clientId, scope, newScope });
            scopes.remove(scope);
            scopes.add(newScope);
        }
    }
    try {
        if (scopes != null) {
            List<String> toRemove = new ArrayList<String>();
            for (String scope : scopes) {
                ScopePathType scopeType = ScopePathType.fromValue(scope);
                if (scopeType.isInternalScope()) {
                    // You should not allow any internal scope here! go away!
                    String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
                    throw new OrcidInvalidScopeException(message);
                } else if (OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
                    if (!scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                } else {
                    if (scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                }
            }
            for (String remove : toRemove) {
                scopes.remove(remove);
            }
        }
    } catch (IllegalArgumentException iae) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }
    try {
        OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state, bearerToken, revokeOld, expiresIn);
        return getResponse(token);
    } catch (InvalidGrantException e) {
        // this needs to be caught here so the transaction doesn't roll back
        OAuthError error = OAuthErrorUtils.getOAuthError(e);
        Status status = Status.fromStatusCode(error.getResponseStatus().getStatusCode());
        return Response.status(status).entity(error).build();
    }
}
Also used : Status(com.sun.jersey.api.client.ClientResponse.Status) OrcidInvalidScopeException(org.orcid.core.exception.OrcidInvalidScopeException) ArrayList(java.util.ArrayList) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) AbstractEndpoint(org.springframework.security.oauth2.provider.endpoint.AbstractEndpoint) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) OAuthError(org.orcid.core.oauth.OAuthError) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with Status

use of com.sun.jersey.api.client.ClientResponse.Status in project coprhd-controller by CoprHD.

the class IsilonApi method existsDir.

/**
 * Checks to see if the dir with the given path exists on the isilon device
 *
 * @param fspath
 *            directory path to chek
 * @return boolean true if exists, false otherwise
 */
public boolean existsDir(String fspath) throws IsilonException {
    fspath = scrubPath(fspath);
    ClientResponse resp = null;
    try {
        fspath = URLEncoder.encode(fspath, "UTF-8");
        sLogger.debug("IsilonApi existsDir {} - start", fspath);
        resp = _client.head(_baseUrl.resolve(URI_IFS.resolve(fspath)));
        sLogger.debug("IsilonApi existsDir {} - complete", fspath);
        if (resp.getStatus() != 200) {
            return false;
        }
        return true;
    } catch (Exception e) {
        if (e.getCause() instanceof ConnectException) {
            throw IsilonException.exceptions.unableToConnect(_baseUrl, e);
        }
        final Status status = resp != null ? resp.getClientResponseStatus() : Status.NOT_FOUND;
        throw IsilonException.exceptions.existsDirFailed(fspath, status, e);
    } finally {
        if (resp != null) {
            resp.close();
        }
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) Status(com.sun.jersey.api.client.ClientResponse.Status) ConnectException(java.net.ConnectException) JSONException(org.codehaus.jettison.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConnectException(java.net.ConnectException)

Aggregations

Status (com.sun.jersey.api.client.ClientResponse.Status)7 ClientResponse (com.sun.jersey.api.client.ClientResponse)5 WebResource (com.sun.jersey.api.client.WebResource)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ConnectException (java.net.ConnectException)2 JSONException (org.codehaus.jettison.json.JSONException)2 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 NewCookie (javax.ws.rs.core.NewCookie)1 JsonGenerationException (org.codehaus.jackson.JsonGenerationException)1 JsonMappingException (org.codehaus.jackson.map.JsonMappingException)1 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)1 JSONObject (org.codehaus.jettison.json.JSONObject)1 OrcidInvalidScopeException (org.orcid.core.exception.OrcidInvalidScopeException)1 OAuthError (org.orcid.core.oauth.OAuthError)1 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)1 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)1 Authentication (org.springframework.security.core.Authentication)1