Example usage for org.apache.commons.httpclient.methods OptionsMethod OptionsMethod

List of usage examples for org.apache.commons.httpclient.methods OptionsMethod OptionsMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods OptionsMethod OptionsMethod.

Prototype

public OptionsMethod(String paramString) 

Source Link

Usage

From source file:org.apache.abdera.protocol.client.util.MethodHelper.java

public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) {
    if (method == null)
        return null;
    Method m = Method.fromString(method);
    Method actual = null;//from  ww w  .  j a v a2s .c o m
    HttpMethod httpMethod = null;
    if (options.isUsePostOverride()) {
        if (m.equals(Method.PUT)) {
            actual = m;
        } else if (m.equals(Method.DELETE)) {
            actual = m;
        }
        if (actual != null)
            m = Method.POST;
    }
    switch (m) {
    case GET:
        httpMethod = new GetMethod(uri);
        break;
    case POST:
        httpMethod = getMethod(new PostMethod(uri), entity);
        break;
    case PUT:
        httpMethod = getMethod(new PutMethod(uri), entity);
        break;
    case DELETE:
        httpMethod = new DeleteMethod(uri);
        break;
    case HEAD:
        httpMethod = new HeadMethod(uri);
        break;
    case OPTIONS:
        httpMethod = new OptionsMethod(uri);
        break;
    case TRACE:
        httpMethod = new TraceMethod(uri);
        break;
    default:
        httpMethod = getMethod(new ExtensionMethod(method, uri), entity);
    }
    if (actual != null) {
        httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);

    // by default use expect-continue is enabled on the client
    // only disable if explicitly disabled
    if (!options.isUseExpectContinue())
        httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    // should we follow redirects, default is true
    if (!(httpMethod instanceof EntityEnclosingMethod))
        httpMethod.setFollowRedirects(options.isFollowRedirects());

    return httpMethod;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate./*from   w w w .ja  va2  s . c  o  m*/
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 *
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + urlStr);
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }

    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
    try {
        // May generate IllegalArgumentException
        if (method.equals(HTTPConstants.POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(HTTPConstants.GET)) {
            httpMethod = new GetMethod(urlStr);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.DELETE;
                }
            };
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpMethod = new EntityEnclosingMethod(urlStr) {
                @Override
                public String getName() { // HC3.1 does not have the method
                    return HTTPConstants.PATCH;
                }
            };
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }

        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
            if (cacheManager.inCache(url)) {
                return updateSampleResultForResourceInCache(res);
            }
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);

        // Setup connection
        HttpClient client = setupConnection(url, httpMethod, res);
        savedClient = client;

        // Handle the various methods
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData((PostMethod) httpMethod);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                || method.equals(HTTPConstants.DELETE)) {
            String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
            res.setQueryString(putBody);
        }

        int statusCode = client.executeMethod(httpMethod);

        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
        if (localAddr != null) {
            httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        // Needs to be done after execute to pick up all the headers
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

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

        if (instream != null) {// will be null for HEAD
            instream = new CountingInputStream(instream);
            try {
                Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                    InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                    res.setResponseData(
                            readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));
                } else {
                    res.setResponseData(
                            readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                }
            } finally {
                JOrphanUtils.closeQuietly(instream);
            }
        }

        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;
        Header h = httpMethod.getResponseHeader(HTTPConstants.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);
        }

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

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        if (instream != null) {
            res.setBodySize(((CountingInputStream) instream).getCount());
        }
        res.setHeadersSize(calculateHeadersSize(httpMethod));
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // 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
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

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

        log.debug("End : sample");
        return res;
    } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod can be null if method is unexpected
        if (httpMethod != null) {
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
        }
        errorResult(e, res);
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        // pick up headers if failed to execute the request
        // httpMethod cannot be null here, otherwise 
        // it would have been caught in the previous catch block
        res.setRequestHeaders(getConnectionHeaders(httpMethod));
        errorResult(e, res);
        return res;
    } finally {
        savedClient = null;
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java

/**
 * Samples the URL passed in and stores the result in
 * <code>HTTPSampleResult</code>, following redirects and downloading
 * page resources as appropriate./*from  w ww .  ja va2  s .c o  m*/
 * <p>
 * When getting a redirect target, redirects are not followed and resources
 * are not downloaded. The caller will take care of this.
 * 
 * @param url
 *            URL to sample
 * @param method
 *            HTTP method: GET, POST,...
 * @param areFollowingRedirect
 *            whether we're getting a redirect target
 * @param frameDepth
 *            Depth of this target in the frame structure. Used only to
 *            prevent infinite recursion.
 * @return results of the sampling
 */
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toExternalForm();

    // Check if this is an entity-enclosing method
    boolean isPost = method.equals(POST) || method.equals(PUT);

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

    // Handles OAuth signing
    try {
        message = getOAuthMessage(url, method);

        urlStr = message.URL;

        if (isPost) {
            urlStr = message.URL;
        } else {
            if (useAuthHeader)
                urlStr = OAuth.addParameters(message.URL, nonOAuthParams);
            else
                urlStr = OAuth.addParameters(message.URL, message.getParameters());
        }
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (OAuthException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } catch (URISyntaxException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    }

    log.debug("Start : sample " + urlStr); //$NON-NLS-1$
    log.debug("method " + method); //$NON-NLS-1$

    HttpMethodBase httpMethod = null;
    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.sampleStart(); // Count the retries as well in the time
    HttpClient client = null;
    InputStream instream = null;

    try {
        // May generate IllegalArgumentException
        if (method.equals(POST)) {
            httpMethod = new PostMethod(urlStr);
        } else if (method.equals(PUT)) {
            httpMethod = new PutMethod(urlStr);
        } else if (method.equals(HEAD)) {
            httpMethod = new HeadMethod(urlStr);
        } else if (method.equals(TRACE)) {
            httpMethod = new TraceMethod(urlStr);
        } else if (method.equals(OPTIONS)) {
            httpMethod = new OptionsMethod(urlStr);
        } else if (method.equals(DELETE)) {
            httpMethod = new DeleteMethod(urlStr);
        } else if (method.equals(GET)) {
            httpMethod = new GetMethod(urlStr);
        } else {
            log.error("Unexpected method (converted to GET): " + method); //$NON-NLS-1$
            httpMethod = new GetMethod(urlStr);
        }

        // Set any default request headers
        setDefaultRequestHeaders(httpMethod);
        // Setup connection
        client = setupConnection(new URL(urlStr), httpMethod, res);
        // Handle POST and PUT
        if (isPost) {
            String postBody = sendPostData(httpMethod);
            res.setQueryString(postBody);
        }

        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = client.executeMethod(httpMethod);

        // 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);
        }

        res.setResponseHeaders(getResponseHeaders(httpMethod));
        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"); //$NON-NLS-1$
            }
            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"); //$NON-NLS-1$
        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()); //$NON-NLS-1$
        return err;
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString()); //$NON-NLS-1$
        return err;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.appcelerator.transport.ProxyTransportServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String method = request.getMethod();
    String url = request.getParameter("url");
    if (url == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;//from w w  w .  j  a v a  2s.c o m
    }

    url = URLDecoder.decode(url, "UTF-8");

    if (url.indexOf("://") == -1) {
        url = new String(Base64.decode(url));
    }

    HttpClient client = new HttpClient();
    HttpMethodBase methodBase = null;

    if (method.equalsIgnoreCase("POST")) {
        methodBase = new PostMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PostMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("GET")) {
        methodBase = new GetMethod(url);
        methodBase.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("PUT")) {
        methodBase = new PutMethod(url);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(request.getInputStream(), out);
        ByteArrayRequestEntity req = new ByteArrayRequestEntity(out.toByteArray());
        ((PutMethod) methodBase).setRequestEntity(req);
    } else if (method.equalsIgnoreCase("DELETE")) {
        methodBase = new DeleteMethod(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        methodBase = new OptionsMethod(url);
    }

    methodBase.setRequestHeader("User-Agent", request.getHeader("user-agent") + " (Appcelerator Proxy)");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Proxying url: " + url + ", method: " + method);
    }

    int status = client.executeMethod(methodBase);

    response.setStatus(status);
    response.setContentLength((int) methodBase.getResponseContentLength());

    for (Header header : methodBase.getResponseHeaders()) {
        String name = header.getName();
        if (name.equalsIgnoreCase("Set-Cookie") == false && name.equals("Transfer-Encoding") == false) {
            response.setHeader(name, header.getValue());
        }
    }
    InputStream in = methodBase.getResponseBodyAsStream();
    Util.copy(in, response.getOutputStream());
}

From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java

private HttpMethodBase createMethod(HttpClient client, Request request)
        throws IOException, FileNotFoundException {
    String methodName = request.getMethod();
    HttpMethodBase method = null;// w  w w.  j  a v  a  2s  .  c  o m
    if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
        EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl())
                : new PutMethod(request.getUrl());

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        post.getParams().setContentCharset("ISO-8859-1");
        if (request.getByteData() != null) {
            post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData()));
            post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length));
        } else if (request.getStringData() != null) {
            post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset));
            post.setRequestHeader("Content-Length",
                    String.valueOf(request.getStringData().getBytes(bodyCharset).length));
        } else if (request.getStreamData() != null) {
            InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData());
            post.setRequestEntity(r);
            post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));

        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    if (sb.length() > 0) {
                        sb.append("&");
                    }
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                }
            }

            post.setRequestHeader("Content-Length", String.valueOf(sb.length()));
            post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1"));

            if (!request.getHeaders().containsKey("Content-Type")) {
                post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
        } else if (request.getParts() != null) {
            MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(),
                    post.getParams());
            post.setRequestEntity(mre);
            post.setRequestHeader("Content-Type", mre.getContentType());
            post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength()));
        } else if (request.getEntityWriter() != null) {
            post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(),
                    computeAndSetContentLength(request, post)));
        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format(Thread.currentThread() + "File %s is not a file or doesn't exist",
                                file.getAbsolutePath()));
            }
            post.setRequestHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream fis = new FileInputStream(file);
            try {
                InputStreamRequestEntity r = new InputStreamRequestEntity(fis);
                post.setRequestEntity(r);
                post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength()));
            } finally {
                fis.close();
            }
        } else if (request.getBodyGenerator() != null) {
            Body body = request.getBodyGenerator().createBody();
            try {
                int length = (int) body.getContentLength();
                if (length < 0) {
                    length = (int) request.getContentLength();
                }

                // TODO: This is suboptimal
                if (length >= 0) {
                    post.setRequestHeader("Content-Length", String.valueOf(length));

                    // This is totally sub optimal
                    byte[] bytes = new byte[length];
                    ByteBuffer buffer = ByteBuffer.wrap(bytes);
                    for (;;) {
                        buffer.clear();
                        if (body.read(buffer) < 0) {
                            break;
                        }
                    }
                    post.setRequestEntity(new ByteArrayRequestEntity(bytes));
                }
            } finally {
                try {
                    body.close();
                } catch (IOException e) {
                    logger.warn("Failed to close request body: {}", e.getMessage(), e);
                }
            }
        }

        String expect = request.getHeaders().getFirstValue("Expect");
        if (expect != null && expect.equalsIgnoreCase("100-Continue")) {
            post.setUseExpectHeader(true);
        }
        method = post;
    } else if (methodName.equalsIgnoreCase("DELETE")) {
        method = new DeleteMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("HEAD")) {
        method = new HeadMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("GET")) {
        method = new GetMethod(request.getUrl());
    } else if (methodName.equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(request.getUrl());
    } else {
        throw new IllegalStateException(String.format("Invalid Method", methodName));
    }

    ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request);
    if (proxyServer != null) {

        if (proxyServer.getPrincipal() != null) {
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyServer.getPrincipal(),
                    proxyServer.getPassword());
            client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);
        }

        ProxyHost proxyHost = proxyServer == null ? null
                : new ProxyHost(proxyServer.getHost(), proxyServer.getPort());
        client.getHostConfiguration().setProxyHost(proxyHost);
    }
    if (request.getLocalAddress() != null) {
        client.getHostConfiguration().setLocalAddress(request.getLocalAddress());
    }

    method.setFollowRedirects(false);
    Collection<Cookie> cookies = request.getCookies();
    if (isNonEmpty(cookies)) {
        method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
    }

    if (request.getHeaders() != null) {
        for (String name : request.getHeaders().keySet()) {
            if (!"host".equalsIgnoreCase(name)) {
                for (String value : request.getHeaders().get(name)) {
                    method.setRequestHeader(name, value);
                }
            }
        }
    }

    String ua = request.getHeaders().getFirstValue("User-Agent");
    if (ua != null) {
        method.setRequestHeader("User-Agent", ua);
    } else if (config.getUserAgent() != null) {
        method.setRequestHeader("User-Agent", config.getUserAgent());
    } else {
        method.setRequestHeader("User-Agent",
                AsyncHttpProviderUtils.constructUserAgent(ApacheAsyncHttpProvider.class, config));
    }

    if (config.isCompressionEnabled()) {
        Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding");
        if (acceptableEncodingHeader != null) {
            String acceptableEncodings = acceptableEncodingHeader.getValue();
            if (acceptableEncodings.indexOf("gzip") == -1) {
                StringBuilder buf = new StringBuilder(acceptableEncodings);
                if (buf.length() > 1) {
                    buf.append(",");
                }
                buf.append("gzip");
                method.setRequestHeader("Accept-Encoding", buf.toString());
            }
        } else {
            method.setRequestHeader("Accept-Encoding", "gzip");
        }
    }

    if (request.getVirtualHost() != null) {

        String vs = request.getVirtualHost();
        int index = vs.indexOf(":");
        if (index > 0) {
            vs = vs.substring(0, index);
        }
        method.getParams().setVirtualHost(vs);
    }

    return method;
}

From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI./*w  ww. j  a v a2 s  .c  o  m*/
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new DeleteMethod(requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
}

From source file:org.collectionspace.services.client.test.ServiceLayerTest.java

@Test
public void servicesExist() {

    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("servicesExist", CLASS_NAME));
    }//  w ww  . j  a  v  a  2s. co  m
    //use ID service that should always be present in a working service layer
    String url = serviceClient.getBaseURL() + "idgenerators";
    OptionsMethod method = new OptionsMethod(url);
    try {
        serviceClient = new TestServiceClient();
        int statusCode = httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("servicesExist url=" + url + " status=" + statusCode);
        }
        Assert.assertEquals(statusCode, HttpStatus.SC_OK, "expected " + HttpStatus.SC_OK);
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: ", e);
    } catch (IOException e) {
        logger.error("Fatal transport error", e);
    } catch (Exception e) {
        logger.error("unknown exception ", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.exist.xquery.modules.httpclient.OPTIONSFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;//ww  w. j  a  v a2 s .c om

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the persist state
    boolean persistState = args[1].effectiveBooleanValue();

    //setup OPTIONS request
    OptionsMethod options = new OptionsMethod(url);

    //setup OPTIONS Request Headers
    if (!args[2].isEmpty()) {
        setHeaders(options, ((NodeValue) args[2].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, options, persistState, null, null);
    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        options.releaseConnection();
    }

    return (response);
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void signOn() throws Exception {
    HttpClient client = getClient();/*from www .  j  ava2s.  c  om*/
    URL serverUrl = new URL(server);
    String host = serverUrl.getHost();
    int port = serverUrl.getPort();
    if (port == -1)
        port = serverUrl.getDefaultPort();
    AuthScope authScope = new AuthScope(host, port);

    if (username.indexOf("\\") < 0) {
        client.getState().setCredentials(authScope, new UsernamePasswordCredentials(username, password));
    } else {
        // Try to connect with NTLM authentication
        String domainUser = username.substring(username.indexOf("\\") + 1, username.length());
        String domain = username.substring(0, username.indexOf("\\"));
        client.getState().setCredentials(authScope, new NTCredentials(domainUser, password, host, domain));
    }

    boolean authenticated = false;
    OptionsMethod authTest = new OptionsMethod(server + "/exchange");
    try {
        authenticated = (client.executeMethod(authTest) < 400);
    } finally {
        try {
            InputStream stream = authTest.getResponseBodyAsStream();
            byte[] buf = new byte[65536];
            try {
                if (session.getDebug()) {
                    PrintStream log = session.getDebugOut();
                    log.println("Response Body:");
                    int count;
                    while ((count = stream.read(buf, 0, 65536)) != -1) {
                        log.write(buf, 0, count);
                    }
                    log.flush();
                    log.println();
                } else {
                    while (stream.read(buf, 0, 65536) != -1)
                        ;
                }
            } catch (Exception ignore) {
            } finally {
                try {
                    stream.close();
                } catch (Exception ignore2) {
                }
            }
        } finally {
            authTest.releaseConnection();
        }
    }
    if (!authenticated) {
        PostMethod op = new PostMethod(server + SIGN_ON_URI);
        op.setRequestHeader("Content-Type", FORM_URLENCODED_CONTENT_TYPE);
        op.addParameter("destination", server + "/exchange");
        op.addParameter("flags", "0");
        op.addParameter("username", username);
        op.addParameter("password", password);
        try {
            int status = client.executeMethod(op);
            if (status >= 400) {
                throw new IllegalStateException("Sign-on failed: " + status);
            }
        } finally {
            try {
                InputStream stream = op.getResponseBodyAsStream();
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
    }
    findInbox();
}

From source file:org.exoplatform.calendar.service.impl.RemoteCalendarServiceImpl.java

@Override
public boolean isValidRemoteUrl(String url, String type, String remoteUser, String remotePassword)
        throws IOException, UnsupportedOperationException {
    try {/*  www .j  a  v a2 s.c om*/
        HttpClient client = new HttpClient();
        HostConfiguration hostConfig = new HostConfiguration();
        String host = new URL(url).getHost();
        if (StringUtils.isEmpty(host))
            host = url;
        hostConfig.setHost(host);
        client.setHostConfiguration(hostConfig);
        Credentials credentials = null;
        client.setHostConfiguration(hostConfig);
        if (!StringUtils.isEmpty(remoteUser)) {
            credentials = new UsernamePasswordCredentials(remoteUser, remotePassword);
            client.getState().setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                    credentials);
        }

        if (CalendarService.ICALENDAR.equals(type)) {
            GetMethod get = new GetMethod(url);
            client.executeMethod(get);
            int statusCode = get.getStatusCode();
            get.releaseConnection();
            return (statusCode == HttpURLConnection.HTTP_OK);
        } else {
            if (CalendarService.CALDAV.equals(type)) {
                OptionsMethod options = new OptionsMethod(url);
                client.executeMethod(options);
                Header header = options.getResponseHeader("DAV");
                options.releaseConnection();
                if (header == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Cannot connect to remoter server or not support WebDav access");
                    }
                    return false;
                }
                Boolean support = header.toString().contains("calendar-access");
                options.releaseConnection();
                if (!support) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Remote server does not support CalDav access");
                    }
                    throw new UnsupportedOperationException("Remote server does not support CalDav access");
                }
                return support;
            }
            return false;
        }
    } catch (MalformedURLException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        throw new IOException("URL is invalid. Maybe no legal protocol or URl could not be parsed");
    } catch (IOException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        throw new IOException("Error occurs when connecting to remote server");
    }
}