Example usage for org.apache.commons.httpclient HttpMethod getName

List of usage examples for org.apache.commons.httpclient HttpMethod getName

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getName.

Prototype

public abstract String getName();

Source Link

Usage

From source file:org.infoscoop.request.OAuth2Authenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuth2Config oauthConfig = request.getOauth2Config();
    try {/*from w  w  w .ja  va 2s  .c  o m*/
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig, getCallbackURL(request));
        if (oauthConfig.accessToken == null) {
            returnApprovalUrl(request, consumer);
        }

        if (oauthConfig.validityPeriodUTC != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            if (cal.getTimeInMillis() > oauthConfig.validityPeriodUTC) {
                if (oauthConfig.refreshToken == null) {
                    OAuthService.getHandle().deleteOAuth2Token(request.getPortalUid(), oauthConfig.gadgetUrl,
                            oauthConfig.serviceName);
                    returnApprovalUrl(request, consumer);
                } else {
                    log.error(
                            "AccessToken was expired, try re-get the token. [" + oauthConfig.serviceName + "]");
                    getAccessTokenByRefreshToken(request, consumer);
                    OAuth2Token token2 = OAuth2TokenDAO.newInstance().getAccessToken(request.getPortalUid(),
                            oauthConfig.gadgetUrl, oauthConfig.serviceName);
                    oauthConfig.setAccessToken(token2.getAccessToken());
                    oauthConfig.setRefreshToken(token2.getRefreshToken());
                    oauthConfig.setValidityPeriodUTC(token2.getValidityPeriodUTC());
                }
            }
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }

        if ("Bearer".equalsIgnoreCase(oauthConfig.tokenType)) {
            method.addRequestHeader("Authorization", oauthConfig.tokenType + " " + oauthConfig.accessToken);
        } else {
            method.addRequestHeader("Authorization", "OAuth " + oauthConfig.accessToken);

            String queryString = method.getQueryString();
            queryString = "access_token=" + oauthConfig.accessToken + "&" + queryString;
            method.setQueryString(queryString);
        }
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.infoscoop.request.OAuthAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    ProxyRequest.OAuthConfig oauthConfig = request.getOauthConfig();
    try {//from  w ww .jav  a2 s .  c  om
        OAuthConsumer consumer = newConsumer(oauthConfig.serviceName, oauthConfig);
        OAuthAccessor accessor = newAccessor(consumer, oauthConfig);
        if (accessor.accessToken == null) {
            getRequestToken(request, accessor);
        }

        Map<String, String> parameters = null;
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equals("POST")) {
            // TODO analyze charset
            String charset = RequestUtil.getCharset(contentType);
            parameters = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
        }
        OAuthMessage message = accessor.newRequestMessage(method.getName(), method.getURI().toString(),
                parameters != null ? parameters.entrySet() : null);
        String authHeader = message.getAuthorizationHeader(null);
        request.setRequestHeader("Authorization", authHeader);
        // Find the non-OAuth parameters:
    } catch (URISyntaxException e) {
        throw new ProxyAuthenticationException(e);
    } catch (OAuthException e) {
        throw new ProxyAuthenticationException(e);
    } catch (IOException e) {
        throw new ProxyAuthenticationException(e);
    }

}

From source file:org.infoscoop.request.SignedAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    try {//w ww .j a va  2 s .  c o  m
        OAuthConsumer consumer = newConsumer();
        OAuthAccessor accessor = new OAuthAccessor(consumer);

        Map<String, String> optionParams = new HashMap<String, String>(request.getFilterParameters());

        String targetUrlPath = analyzeUrl(request.getTargetURL(), optionParams);

        String userId = SecurityController.getPrincipalByType("UIDPrincipal").getName();
        optionParams.put("opensocial_viewer_id", userId);
        optionParams.put("opensocial_owner_id", userId);
        optionParams.put("opensocial_app_url", request.getRequestHeader("gadgetUrl"));
        optionParams.put("opensocial_app_id", request.getRequestHeader("moduleId"));
        optionParams.put("opensocial_instance_id", request.getRequestHeader("moduleId"));
        optionParams.put("xoauth_signature_publickey", PUBLIC_KEY_NAME);
        optionParams.put("xoauth_public_key", PUBLIC_KEY_NAME);

        Map<String, String> postParams = new HashMap<String, String>();
        String contentType = request.getRequestHeader("Content-Type");
        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")
                && method.getName().equalsIgnoreCase("POST")) {

            String charset = RequestUtil.getCharset(contentType);
            postParams = RequestUtil.parseRequestBody(request.getRequestBody(), charset);
            optionParams.putAll(postParams);
        }

        OAuthMessage message = new OAuthMessage(method.getName(), targetUrlPath, optionParams.entrySet());
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> authParams = message.getParameters();
        List<NameValuePair> queryParams = buildQueryParams(authParams, postParams);
        method.setQueryString((NameValuePair[]) queryParams.toArray(new NameValuePair[0]));

    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.mule.transport.as2.As2MuleMessageFactory.java

@Override
protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception {
    String method;/*from  w  w w . j a v a  2 s .co  m*/
    HttpVersion httpVersion;
    String uri;
    String statusCode = null;
    Map<String, Object> headers;
    Map<String, Object> httpHeaders = new HashMap<String, Object>();
    Map<String, Object> queryParameters = new HashMap<String, Object>();

    if (transportMessage instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) transportMessage;
        method = httpRequest.getRequestLine().getMethod();
        httpVersion = httpRequest.getRequestLine().getHttpVersion();
        uri = httpRequest.getRequestLine().getUri();
        headers = convertHeadersToMap(httpRequest.getHeaders(), uri);
        convertMultiPartHeaders(headers);
    } else if (transportMessage instanceof HttpMethod) {
        HttpMethod httpMethod = (HttpMethod) transportMessage;
        method = httpMethod.getName();
        httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion());
        uri = httpMethod.getURI().toString();
        statusCode = String.valueOf(httpMethod.getStatusCode());
        headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri);
    } else {
        // This should never happen because of the supported type checking in our superclass
        throw new MessageTypeNotSupportedException(transportMessage, getClass());
    }

    rewriteConnectionAndKeepAliveHeaders(headers);

    headers = processIncomingHeaders(headers);

    httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers));

    String encoding = getEncoding(headers);

    queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding));

    //Make any URI params available ans inbound message headers
    addUriParamsAsHeaders(headers, uri);

    headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method);
    headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri);
    headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString());
    if (enableCookies) {
        headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec);
    }

    if (statusCode != null) {
        headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode);
    }

    message.addInboundProperties(headers);
    message.addInboundProperties(httpHeaders);
    message.addInboundProperties(queryParameters);

    // The encoding is stored as message property. To avoid overriding it from the message
    // properties, it must be initialized last
    initEncoding(message, encoding);
}

From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java

private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers)
        throws Exception {
    HttpMethod httpMethod = mock(HttpMethod.class);
    when(httpMethod.getName()).thenReturn(method);
    when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK"));
    when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK);
    when(httpMethod.getURI()).thenReturn(new URI(uri, false));
    when(httpMethod.getResponseHeaders()).thenReturn(headers);
    when(httpMethod.getResponseBodyAsStream()).thenReturn(body);

    return httpMethod;
}

From source file:org.osaf.caldav4j.exceptions.BadStatusException.java

public BadStatusException(HttpMethod method) {
    super(String.format(MESSAGE, method.getStatusCode(), method.getName(), method.getPath()));
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

/**
 * Execute an http method and return the status code.
 * /*from www . ja v  a2 s. co m*/
 * @param method
 * @return
 * @throws IOException
 * @throws DocProxyException
 */
private int executeMethod(HttpMethod method, Node node) throws DocProxyException {
    try {
        addHmac(method, node);
        int returnCode = client.executeMethod(method);
        if (returnCode < 200 || returnCode >= 300) {
            throw new DocProxyException(returnCode,
                    "Error occurred while executing method [" + method.getName() + ":" + returnCode + "]");
        }
        return returnCode;
    } catch (IOException e) {
        throw new DocProxyException(500, e.getMessage());
    } catch (RepositoryException e) {
        throw new DocProxyException(500, e.getMessage());
    } catch (SignatureException e) {
        throw new DocProxyException(500, e.getMessage());
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java

/**
 * Prepare an HTTP request to Sakai OAE and parse the response (if JSON).
 * @param client an {@link HttpClient} to execute the request.
 * @param method an HTTP method to send/*from  ww w.  j  a  v a  2s  .  co  m*/
 * @return a JSONObject of the response if the request returns JSON
 * @throws GroupModificationException if there was an error updating the group information.
 */
public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException {

    method.setRequestHeader("User-Agent", HTTP_USER_AGENT);
    method.setRequestHeader("Referer", HTTP_REFERER);

    String errorMessage = null;
    String responseString = null;
    JSONObject responseJSON = null;

    boolean isJSONRequest = !method.getPath().toString().endsWith(".html");

    if (log.isDebugEnabled() && method instanceof PostMethod) {
        log.debug(method.getName() + " " + method.getPath() + " params:");
        for (NameValuePair nvp : ((PostMethod) method).getParameters()) {
            log.debug(nvp.getName() + " = " + nvp.getValue());
        }
    }

    int responseCode = -1;
    try {
        responseCode = client.executeMethod(method);
        responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream()));

        if (isJSONRequest) {
            responseJSON = parseJSONResponse(responseString);
        }

        if (log.isDebugEnabled()) {
            log.debug(responseCode + " " + method.getName() + " " + method.getPath());
        }
        if (log.isTraceEnabled()) {
            log.trace("reponse: " + responseString);
        }

        switch (responseCode) {

        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
            break;
        case HttpStatus.SC_BAD_REQUEST: // 400
        case HttpStatus.SC_UNAUTHORIZED: // 401
        case HttpStatus.SC_NOT_FOUND: // 404
        case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500
            if (isJSONRequest && responseJSON != null) {
                errorMessage = responseJSON.getString("status.message");
            }
            if (errorMessage == null) {
                errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server.";
            }
            break;
        default:
            errorMessage = "Unknown HTTP response " + responseCode;
            break;
        }
    } catch (Exception e) {
        errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString();
    } finally {
        method.releaseConnection();
    }

    if (errorMessage != null) {
        log.error(errorMessage);
        errorToException(responseCode, errorMessage);
    }
    return responseJSON;
}

From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerTest.java

private CertificateManagerImpl createCertificateManager() {
    return new CertificateManagerImpl() {
        @Override/*  w w  w  .j ava 2  s  . c o  m*/
        protected HttpClient getNewHttpClient() {
            return new HttpClient() {
                @Override
                public int executeMethod(HttpMethod method) {
                    if (StringUtils.equals(method.getName(), DELETE)) {
                        try {
                            URI reqURI = method.getURI();
                            FileUtils.deleteQuietly(new File(reqURI.getPath()));
                        } catch (URIException uex) {
                            //do nothing
                        }
                        return 200;
                    } else {
                        return 501;
                    }
                }
            };
        }
    };
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

protected int executeMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method,
        URL remoteUrl) throws RemoteStorageException {
    final Stopwatch stopwatch = timingLog.isDebugEnabled() ? new Stopwatch().start() : null;
    try {//w  ww .  j a v a2  s .c  om
        return doExecuteMethod(repository, request, method, remoteUrl);
    } finally {
        if (stopwatch != null) {
            stopwatch.stop();
            timingLog.debug("[{}] {} {} took {}",
                    new Object[] { repository.getId(), method.getName(), remoteUrl, stopwatch });
        }
    }
}