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

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

Introduction

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

Prototype

@Override
public URI getURI() throws URIException 

Source Link

Document

Returns the URI of the HTTP method

Usage

From source file:org.portletbridge.portlet.DefaultHttpClientTemplate.java

public Object service(HttpMethodBase method, HttpClientState state, HttpClientCallback callback)
        throws ResourceException {
    try {/*  w  w w . j  a  v  a  2 s .  c  om*/
        HostConfiguration hostConfiguration = new HostConfiguration();

        if (state.getProxyHost() != null && state.getProxyHost().trim().length() > 0) {
            hostConfiguration.setProxy(state.getProxyHost(), state.getProxyPort());
        }
        hostConfiguration.setHost(method.getURI());
        int statusCode = httpClient.executeMethod(hostConfiguration, method, state.getHttpState());
        return callback.doInHttpClient(statusCode, method);
    } catch (ResourceException e) {
        throw e;
    } catch (Throwable e) {
        throw new ResourceException("error.httpclient", e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

/**
 * @param response/*from  w ww. j  ava2 s .c  om*/
 * @param bridgeRequest
 * @param perPortletMemento
 * @param url
 * @throws ServletException
 */
protected void fetch(final HttpServletRequest request, final HttpServletResponse response,
        final BridgeRequest bridgeRequest, final PortletBridgeMemento memento,
        final PerPortletMemento perPortletMemento, final URI url) throws ServletException {
    try {
        GetMethod getMethod = new GetMethod(url.toString());
        // TODO: suspect to send the same request headers after a redirect?
        copyRequestHeaders(request, getMethod);
        httpClientTemplate.service(getMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    org.apache.commons.httpclient.URI effectiveUri = method.getURI();
                    BridgeRequest effectiveBridgeRequest = null;
                    if (!effectiveUri.toString().equals(url.toString())) {
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        effectiveBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), new URI(effectiveUri.toString()));
                    } else {
                        effectiveBridgeRequest = bridgeRequest;
                    }
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(effectiveBridgeRequest.getId(),
                                new PortletBridgeContent(url, "get", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end
                        response.sendRedirect(effectiveBridgeRequest.getPageUrl());
                    } else if (responseHeader != null
                            && responseHeader.getValue().startsWith("text/javascript")) {
                        // rewrite external javascript
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/javascript");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.script(null, content));
                        writer.flush();
                    } else if (responseHeader != null && responseHeader.getValue().startsWith("text/css")) {
                        // rewrite external css
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/css");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.style(null, content));
                        writer.flush();
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        Header header = method.getResponseHeader("Content-Type");
                        response.setContentType(((null == header.getName() ? "" : header.getName()) + ": "
                                + (null == header.getValue() ? "" : header.getValue())));

                        log.trace("fetch(): returning URL=" + url + ", as stream, content type=" + header);
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void copyRequestHeaders(HttpServletRequest request, HttpMethodBase method) {

    Enumeration properties = request.getHeaderNames();
    while (properties.hasMoreElements()) {
        String propertyName = (String) properties.nextElement();
        String propertyNameToLower = propertyName.toLowerCase();
        if (!ignoreRequestHeaders.contains(propertyNameToLower) && !(method instanceof GetMethod
                && ignorePostToGetRequestHeaders.contains(propertyNameToLower))) {
            Enumeration values = request.getHeaders(propertyName);
            while (values.hasMoreElements()) {
                String property = (String) values.nextElement();
                // System.out.println(propertyName + ":" + property);
                method.setRequestHeader(propertyName, property);
            }/*from  w  w w .ja  v a  2  s  .  c o m*/
        }
    }

    // TODO consider what happens if the host is different after a redirect...
    // Conditional cookie transfer
    try {
        org.apache.commons.httpclient.URI uri = method.getURI();
        if (uri != null) {
            String host = uri.getHost();
            if (host != null) {
                if (host.equals(request.getHeader("host"))) {
                    String cookie = request.getHeader("cookie");
                    if (cookie != null)
                        method.setRequestHeader("cookie", cookie);
                }
            } else {
                log.warn("host is null for uri " + uri);
            }
        } else {
            log.warn("uri is null for method " + method);
        }
    } catch (URIException e) {
        log.warn(e, e);
    }

}

From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java

private static String constructUri(HttpMethodBase request) {
    try {/*from  w  ww  . j  av a 2 s  .c o  m*/
        return request.getURI().toString();
    } catch (URIException e) {
        return request.getPath();
    }
}

From source file:org.rhq.enterprise.server.plugins.url.HttpProvider.java

/**
 * Given a client and the method to be used by that client, this will prepare those objects
 * so they can be used to get the remote content.
 * //  www. java  2s. c o  m
 * @param client
 * @param method
 * 
 * @throws Exception if the client cannot be prepared successfully
 */
protected void prepareHttpClient(HttpClient client, HttpMethodBase method) throws Exception {

    // prepare the client with proxy info, if appropriate
    configureProxy(client);

    // setup the authentication
    method.setFollowRedirects(true);

    if (this.username != null) {
        method.setDoAuthentication(true);

        org.apache.commons.httpclient.URI fullUri = method.getURI();
        AuthScope authScope = new AuthScope(fullUri.getHost(), fullUri.getPort(), AuthScope.ANY_REALM);
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        client.getState().setCredentials(authScope, credentials);
    }

    return;
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private void setupAuthentication(URI link, String realm, HttpClient client, HttpMethodBase method)
        throws URIException, CredentialsException {
    ICredentials authCredentials = Owl.getConnectionService().getAuthCredentials(link, realm);
    if (authCredentials != null) {
        client.getParams().setAuthenticationPreemptive(true);

        /* Require Host */
        String host = method.getURI().getHost();

        /* Create the UsernamePasswordCredentials */
        NTCredentials userPwCreds = new NTCredentials(authCredentials.getUsername(),
                authCredentials.getPassword(), host,
                (authCredentials.getDomain() != null) ? authCredentials.getDomain() : ""); //$NON-NLS-1$

        /* Authenticate to the Server */
        client.getState().setCredentials(AuthScope.ANY, userPwCreds);
        method.setDoAuthentication(true);
    }//  ww w  .j a  v  a2s  .  c  o  m
}

From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java

String execute(HttpMethodBase method) {
    try {/*from   w w w .  ja va  2  s  .  com*/
        if (client == null) {
            init();
        }
        LOGGER.logMessage(LogLevel.DEBUG, "?:{}", method.getURI().toString());
        if (!("ISO-8859-1").equals(requestCharset)) {
            method.addRequestHeader("Content-Type", "text/html; charset=" + requestCharset);
        }
        method.setDoAuthentication(authEnabled);
        int iGetResultCode = client.executeMethod(method);
        if (iGetResultCode == HttpStatus.SC_OK) {
            LOGGER.logMessage(LogLevel.DEBUG, "?");
            Header responseHeader = method.getResponseHeader("Content-Encoding");
            if (responseHeader != null) {
                String acceptEncoding = responseHeader.getValue();
                if (acceptEncoding != null && ("gzip").equals(acceptEncoding)) {
                    //gzip?
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                            method.getResponseBody());
                    GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
                    return IOUtils.readFromInputStream(gzipInputStream, responseCharset);
                }
            }
            return new String(method.getResponseBody(), responseCharset);
        }
        LOGGER.logMessage(LogLevel.ERROR, "{}",
                method.getStatusLine().toString());
        throw new RuntimeException(method.getStatusLine().toString());
    } catch (Exception e) {
        LOGGER.logMessage(LogLevel.DEBUG, "{}", e.getMessage());
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.wso2.carbon.appmgt.mdm.wso2mdm.MDMOperationsImpl.java

private boolean executeMethod(String tokenApiURL, String clientKey, String clientSecret, String authUser,
        String authPass, HttpClient httpClient, HttpMethodBase httpMethod) {
    String authKey = getAPIToken(tokenApiURL, clientKey, clientSecret, authUser, authPass, false);
    if (log.isDebugEnabled())
        log.debug("Access token received : " + authKey);
    //String authKey = "12345";
    try {/*from w  ww. j  ava2  s .c  o  m*/
        int statusCode = 401;
        int tries = 0;
        while (statusCode != 200) {
            if (log.isDebugEnabled())
                log.debug("Trying to call API : trying for " + (tries + 1) + " time(s)");
            httpMethod.setRequestHeader("Authorization", "Bearer " + authKey);
            if (log.isDebugEnabled())
                log.debug("Sending " + httpMethod.getName() + " request to " + httpMethod.getURI());
            statusCode = httpClient.executeMethod(httpMethod);
            if (log.isDebugEnabled())
                log.debug("Status code received : " + statusCode);

            if (++tries >= 3) {
                log.info("API Call failed for the 3rd time: No or Unauthorized Access Aborting...");
                return false;
            }
            if (statusCode == 401) {
                authKey = getAPIToken(tokenApiURL, clientKey, clientSecret, authUser, authPass, true);
                if (log.isDebugEnabled())
                    log.debug("Access token getting again, Access token received :  " + authKey + " in  try "
                            + tries);
            }

        }
        return true;
    } catch (IOException e) {
        String errorMessage = "No OK response received form the API";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
        return false;
    }
}

From source file:smartrics.jmeter.sampler.RestSampler.java

/**
 * Method invoked by JMeter when a sample needs to happen. It's actually an
 * indirect call from the main sampler interface. it's resolved in the base
 * class.//w ww.  j ava 2 s .co m
 * 
 * This is a copy and paste from the HTTPSampler2 - quick and dirty hack as
 * that class is not very extensible. The reason to extend and slightly
 * modify is that I needed to get the body content from a text field in the
 * GUI rather than a file.
 */
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    log.debug("Start : sample " + urlStr);
    log.debug("method " + method);

    HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.setURL(url);
    res.sampleStart(); // Count the retries as well in the time
    HttpClient client = null;
    InputStream instream = null;
    try {
        httpMethod = createHttpMethod(method, urlStr);
        // Set any default request headers
        res.setRequestHeaders("");
        // Setup connection
        client = setupConnection(url, httpMethod, res);
        // Handle the various methods
        if (httpMethod instanceof EntityEnclosingMethod) {
            String postBody = sendData((EntityEnclosingMethod) httpMethod);
            res.setResponseData(postBody.getBytes());
        }
        overrideHeaders(httpMethod);
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = -1;
        try {
            statusCode = client.executeMethod(httpMethod);
        } catch (RuntimeException e) {
            log.error("Exception when executing '" + httpMethod + "'", e);
            throw e;
        }

        // Request sent. Now get the response:
        instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        String responseHeaders = getResponseHeaders(httpMethod);
        res.setResponseHeaders(responseHeaders);
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but
                // avoids NPE
                throw new IllegalArgumentException("Missing location header");
            }
            res.setRedirectLocation(headerLocation.getValue());
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample");
        httpMethod.releaseConnection();
        return res;
    } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
    {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString());
        return err;
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString());
        return err;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}