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

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

Introduction

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

Prototype

public TraceMethod(String paramString) 

Source Link

Usage

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse trace(final RequestContext rq, Binding cmisBinding, String version, String cmisOperation)
        throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), cmisBinding, version, cmisOperation,
            null);//from ww w.j  a  v a 2 s.c  o m
    String url = endpoint.getUrl();

    TraceMethod req = new TraceMethod(url.toString());
    return submitRequest(req, rq);
}

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   w  ww . j a v a  2 s  .c  om*/
    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.camel.component.jetty.JettyEndpointSetHttpTraceTest.java

@Test
public void testTraceDisabled() throws Exception {
    HttpClient httpclient = new HttpClient();
    TraceMethod trace = new TraceMethod("http://localhost:" + portTraceOff + "/myservice");
    httpclient.executeMethod(trace);/* w w w  . ja va2s  .  c  o  m*/

    // TRACE shouldn't be allowed by default
    assertTrue(trace.getStatusCode() == 405);
    trace.releaseConnection();
}

From source file:org.apache.camel.component.jetty.JettyEndpointSetHttpTraceTest.java

@Test
public void testTraceEnabled() throws Exception {
    HttpClient httpclient = new HttpClient();
    TraceMethod trace = new TraceMethod("http://localhost:" + portTraceOn + "/myservice");
    httpclient.executeMethod(trace);//from ww  w  .j  a va 2  s .c o  m

    // TRACE is now allowed
    assertTrue(trace.getStatusCode() == 200);
    trace.releaseConnection();
}

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./*www. j a  v  a 2s . co 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  w  w .j  av  a  2  s.co 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.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  .  ja v a2s .  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 traceSupported() {
    if (logger.isDebugEnabled()) {
        logger.debug(BaseServiceTest.testBanner("traceSupported", CLASS_NAME));
    }/* w  ww.j a  v a2s .  co m*/
    String url = serviceClient.getBaseURL() + "collectionobjects";
    TraceMethod method = new TraceMethod(url);
    try {
        int statusCode = httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug("traceSupported url=" + url + " status=" + statusCode);
            logger.debug("traceSupported response=" + new String(method.getResponseBody()));
            for (Header h : method.getResponseHeaders()) {
                logger.debug("traceSupported header name=" + h.getName() + " value=" + h.getValue());
            }
        }
        Assert.assertEquals(statusCode, HttpStatus.SC_METHOD_NOT_ALLOWED,
                "expected " + HttpStatus.SC_METHOD_NOT_ALLOWED);
    } 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.easyj.http.RESTHttpClient.java

/**
 * Executes a TRACE HTTP request and returns the body response as {@code String}
 *
 * @param uri URI of the resource to be requested
 * @return The body response of the request as {@code String}
 *//*from   www .  jav  a 2 s .  c o  m*/
public RESTHttpClient trace(String uri) {
    method = new TraceMethod(buildURI(uri));
    return execute(uri);
}

From source file:org.jaggeryjs2.xhr.XMLHttpRequest.java

private void sendRequest(Object obj) throws Exception {
    final HttpMethodBase method;
    if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod(this.url);
    } else if ("HEAD".equalsIgnoreCase(methodName)) {
        method = new HeadMethod(this.url);
    } else if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod post = new PostMethod(this.url);
        if (obj instanceof FormData) {
            FormData fd = ((FormData) obj);
            List<Part> parts = new ArrayList<Part>();
            for (Map.Entry<String, String> entry : fd) {
                parts.add(new StringPart(entry.getKey(), entry.getValue()));
            }// w  ww  . j ava 2  s. com
            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        } else {
            String content = getRequestContent(obj);
            if (content != null) {
                post.setRequestEntity(
                        new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
            }
        }
        method = post;
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod put = new PutMethod(this.url);
        String content = getRequestContent(obj);
        if (content != null) {
            put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
        }
        method = put;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod(this.url);
    } else if ("TRACE".equalsIgnoreCase(methodName)) {
        method = new TraceMethod(this.url);
    } else if ("OPTIONS".equalsIgnoreCase(methodName)) {
        method = new OptionsMethod(this.url);
    } else {
        throw new Exception("Unknown HTTP method : " + methodName);
    }
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    if (username != null) {
        httpClient.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
    }
    this.method = method;
    final XMLHttpRequest xhr = this;
    if (async) {
        updateReadyState(xhr, LOADING);
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {
            public Object call() throws Exception {
                try {
                    executeRequest(xhr);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    es.shutdown();
                }
                return null;
            }
        });
    } else {
        executeRequest(xhr);
    }
}