Example usage for org.apache.commons.httpclient HttpMethodBase getPath

List of usage examples for org.apache.commons.httpclient HttpMethodBase getPath

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getPath.

Prototype

@Override
public String getPath() 

Source Link

Document

Gets the path of this HTTP method.

Usage

From source file:com.google.gsa.valve.modules.utils.HTTPAuthZProcessor.java

/**
 * Sets the document name putting it into the Content-Disposition header
 * // w ww. j  a v  a 2  s.  c  o  m
 * @param response HTTP response
 * @param method HTTP method
 */
public static void setDocumentName(HttpServletResponse response, HttpMethodBase method, String contentType) {
    response.setHeader("Content-Type", contentType);
    //Set the file name properly
    String[] tabpath = (method.getPath()).split("/");
    String fileName = tabpath[tabpath.length - 1];
    String decodeFileName = null;
    try {
        decodeFileName = URLDecoder.decode(fileName, "UTF-8");
    } catch (Exception e) {
        logger.error("Exception decoding URL: " + e);
        decodeFileName = fileName;
    }
    response.setHeader("Content-Disposition", "inline; filename=" + decodeFileName);
}

From source file:com.eucalyptus.blockstorage.HttpTransfer.java

/**
 * Calculates and sets the Authorization header value for the request using the EucaRSA-V2 signing algorithm
 * Algorithm Overview:/*from  w w w .j av  a2s  .  co  m*/
 * 
 * 1. Generate the canonical Request
 *  a.) CanonicalRequest =
 *          HTTPRequestMethod + '\n' +
 *          CanonicalURI + '\n' +
 *          CanonicalQueryString + '\n' +
 *          CanonicalHeaders + '\n' +
 *          SignedHeaders
 *    b.) Where CanonicalURI = 
 *    c.) Where CanonicalQueryString = 
 *   d.) Where CanonicalHeaders =  sorted (by lowercased header name) ';' delimited list of <lowercase(headername)>:<value> items
 *   e.) Where SignedHeaders = sorted, ';' delimited list of headers in CanonicalHeaders
 * 
 * 2. Signature = RSA(privkey, SHA256(CanonicalRequest))
 * 
 * 3. Add an Authorization HTTP header to the request that contains the following strings, separated by spaces:
 * EUCA2-RSA-SHA256
 * The lower-case hexadecimal encoding of the component's X.509 certificate's md5 fingerprint
 * The SignedHeaders list calculated in Task 1
 * The Base64 encoding of the Signature calculated in Task 2
 * 
 * @param httpBaseRequest -- the request, the 'Authorization' header will be added to the request
 */
public static void signEucaInternal(HttpMethodBase httpBaseRequest) {
    StringBuilder canonicalRequest = new StringBuilder();
    String canonicalURI = null;
    String verb = httpBaseRequest.getName();
    canonicalURI = httpBaseRequest.getPath();

    String canonicalQuery = calcCanonicalQuery(httpBaseRequest);
    String[] processedHeaders = getCanonicalAndSignedHeaders(httpBaseRequest);
    String canonicalHeaders = processedHeaders[0];
    String signedHeaders = processedHeaders[1];

    canonicalRequest.append(verb).append('\n');
    canonicalRequest.append(canonicalURI).append('\n');
    canonicalRequest.append(canonicalQuery).append('\n');
    canonicalRequest.append(canonicalHeaders).append('\n');
    canonicalRequest.append(signedHeaders);

    StringBuilder authHeader = new StringBuilder(EUCA2_AUTH_ID);
    String signature = null;
    String fingerprint = null;
    try {
        Credentials ccCreds = SystemCredentials.lookup(Storage.class);
        PrivateKey ccPrivateKey = ccCreds.getPrivateKey();
        fingerprint = ccCreds.getCertFingerprint();
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(ccPrivateKey);
        LOG.debug("Signing canonical request: " + canonicalRequest.toString());
        sign.update(canonicalRequest.toString().getBytes());
        byte[] sig = sign.sign();
        signature = new String(Base64.encode(sig));
    } catch (Exception ex) {
        LOG.error("Signing error while signing request", ex);
    }

    authHeader.append(" ").append(fingerprint.toLowerCase()).append(" ").append(signedHeaders.toString())
            .append(" ").append(signature);
    httpBaseRequest.addRequestHeader(EUCA2_AUTH_HEADER_NAME, authHeader.toString());
}

From source file:ch.gadp.alfresco.OAuthSSOAuthenticationFilter.java

/**
 * Add the ticket parameter to the request
 * @param method The method to expand/*  w  w w.j  a  va2 s .c o  m*/
 * @param ticket The ticket to use
 */
protected void addTicketParameter(HttpMethodBase method, String ticket) {
    method.setPath(method.getPath() + "?" + DEFAULT_TICKET_NAME + "=" + ticket);
}

From source file:jeeves.utils.XmlRequest.java

private String getSentData(HttpMethodBase httpMethod) {
    StringBuilder sentData = new StringBuilder(httpMethod.getName()).append(" ").append(httpMethod.getPath());

    if (httpMethod.getQueryString() != null) {
        sentData.append("?" + httpMethod.getQueryString());
    }/*from   w w w.ja v  a 2s . co m*/

    sentData.append("\r\n");

    for (Header h : httpMethod.getRequestHeaders()) {
        sentData.append(h);
    }

    sentData.append("\r\n");

    if (httpMethod instanceof PostMethod) {
        sentData.append(postData);
    }

    return sentData.toString();
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpStreamResponse executeMethodStream(HttpMethodBase method, int timeoutMillis)
        throws HttpClientException {
    try {//from  ww w  . j  a v a2  s.  co  m
        return executeStreamWithTimeout(method, timeoutMillis);
    } catch (Exception e) {
        throw new HttpClientException("Error executing " + method.getName() + " request to: "
                + client.getHostConfiguration().getHostURL() + " path: " + method.getPath(), e);
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse executeMethod(HttpMethodBase method, Map<String, String> headers, int timeoutMillis)
        throws HttpClientException {
    setRequestHeaders(headers, method);/*www . j av  a2s  .  c  om*/

    if (timeoutMillis > 0) {
        return executeWithTimeout(method, timeoutMillis);
    }
    try {
        return execute(method);
    } catch (Exception e) {
        throw new HttpClientException("Error executing " + method.getName() + " request to: "
                + client.getHostConfiguration().getHostURL() + " path: " + method.getPath(), e);
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* invoke creates a socket connection, sends the request SOAP message and
* then reads the response SOAP message back from the SOAP server
* 
* @param msgContext//  w  w w  . ja va 2  s .co  m
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    log.debug(Messages.getMessage("enter00", "CommonsHttpSender::invoke"));
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);

        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();

            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:org.elasticsearch.hadoop.rest.RestClient.java

byte[] execute(HttpMethodBase method, boolean checkStatus) {
    try {/*from www.  java  2s. c om*/
        int status = client.executeMethod(method);
        if (checkStatus && status >= HttpStatus.SC_MULTI_STATUS) {
            String body;
            try {
                body = method.getResponseBodyAsString();
            } catch (IOException ex) {
                body = "";
            }
            throw new IllegalStateException(String.format("[%s] on [%s] failed; server[%s] returned [%s]",
                    method.getName(), method.getURI(), client.getHostConfiguration().getHostURL(), body));
        }
        return method.getResponseBody();
    } catch (IOException io) {
        String target;
        try {
            target = method.getURI().toString();
        } catch (IOException ex) {
            target = method.getPath();
        }
        throw new IllegalStateException(
                String.format("Cannot get response body for [%s][%s]", method.getName(), target));
    } finally {
        method.releaseConnection();
    }
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

private void setupSentData(HttpMethodBase httpMethod) {
    sentData = httpMethod.getName() + " " + httpMethod.getPath();

    if (httpMethod.getQueryString() != null)
        sentData += "?" + httpMethod.getQueryString();

    sentData += "\r\n";

    for (Header h : httpMethod.getRequestHeaders())
        sentData += h;/*  w  w  w .j av  a 2  s.com*/

    sentData += "\r\n";

    if (httpMethod instanceof PostMethod)
        sentData += postData;
}

From source file:org.fao.oaipmh.requests.Transport.java

private void setupSentData(HttpMethodBase httpMethod) {
    sentData = httpMethod.getName() + " " + httpMethod.getPath();

    if (httpMethod.getQueryString() != null)
        sentData += "?" + httpMethod.getQueryString();

    sentData += "\r\n";

    for (Header h : httpMethod.getRequestHeaders())
        sentData += h;//from   w w  w .j a v  a2 s .c o m

    sentData += "\r\n";
}