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:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java

/**
 * Sets the headers and does some checking for if this request
 * is meant for the server or for the proxy. This check is done
 * by looking at the Max-Forwards header.
 * //from   w w  w .j  a v a 2s  . c o m
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {
    HttpMethodBase method = null;

    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        method = new OptionsMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("TRACE")) {
        method = new TraceMethod(url);
    } else {
        return null;
    }

    try {
        int max = request.getIntHeader("Max-Forwards");
        if (max == 0 || request.getRequestURI().equals("*")) {
            setAllHeaders(method, request);
            method.abort();
        } else if (max != -1) {
            setHeaders(method, request);
            method.setRequestHeader("Max-Forwards", "" + max--);
        } else {
            setHeaders(method, request);
        }
    } catch (NumberFormatException e) {
    }

    return method;
}

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase createMethod(URL url, int type) {
    HttpMethodBase request = null;//  w  ww.j  ava2s .c om
    switch (type) {
    case GET:
        request = new GetMethod(url.toString());
        break;
    case POST:
        request = new PostMethod(url.toString());
        break;
    case HEAD:
        request = new HeadMethod(url.toString());
        break;
    case OPTIONS:
        request = new OptionsMethod(url.toString());
        break;
    case PUT:
        request = new PutMethod(url.toString());
        break;
    case DELETE:
        request = new DeleteMethod(url.toString());
        break;
    case TRACE:
        request = new TraceMethod(url.toString());
        break;
    }
    return request;
}

From source file:jails.http.client.CommonsClientHttpRequestFactory.java

/**
 * Create a Commons HttpMethodBase object for the given HTTP method
 * and URI specification./* w  ww . j  a v a2  s  . c o  m*/
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
    case GET:
        return new GetMethod(uri);
    case DELETE:
        return new DeleteMethod(uri);
    case HEAD:
        return new HeadMethod(uri);
    case OPTIONS:
        return new OptionsMethod(uri);
    case POST:
        return new PostMethod(uri);
    case PUT:
        return new PutMethod(uri);
    case TRACE:
        return new TraceMethod(uri);
    default:
        throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}

From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java

/**
 * Constructor./*from ww  w .  j  av  a  2  s  .  c o m*/
 * 
 * @param helper
 *            The parent HTTP client helper.
 * @param method
 *            The method name.
 * @param requestUri
 *            The request URI.
 * @param hasEntity
 *            Indicates if the call will have an entity to send to the
 *            server.
 * @throws IOException
 */
public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new GetMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new PostMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new PutMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HeadMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new DeleteMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            final HostConfiguration host = new HostConfiguration();
            host.setHost(new URI(requestUri, false));
            this.httpMethod = new ConnectMethod(host);
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new OptionsMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new TraceMethod(requestUri);
        } else {
            this.httpMethod = new EntityEnclosingMethod(requestUri) {
                @Override
                public String getName() {
                    return method;
                }
            };
        }

        this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects());
        this.httpMethod.setDoAuthentication(false);

        if (this.clientHelper.getRetryHandler() != null) {
            try {
                this.httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance());
            } catch (Exception e) {
                this.clientHelper.getLogger().log(Level.WARNING,
                        "An error occurred during the instantiation of the retry handler.", e);
            }
        }

        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Setup the request./*from  w ww  .j a va2s.c  o  m*/
 *
 * @param context the context
 */
protected void setupRequest(ProxyContext context) {
    // set the proxy to send requests through
    ExternalProxySettings externalProxy = context.getExternalProxySettings();
    if (externalProxy != null) {
        String proxyServer = externalProxy.getProxyServer();

        if (proxyServer != null) {
            context.getTarget().getHostConfig().setProxy(proxyServer, externalProxy.getProxyPort());
            if (context.getProxyCredentials() != null) {
                context.getHttpClient().getState().setProxyCredentials(ProxyUtil.getDefaultAuthScope(),
                        context.getProxyCredentials());
            }
        }
    }

    String method = context.getMethod();
    String encodedPath = context.getTarget().getEncodedPath();
    if (MessageIOConstants.METHOD_POST.equals(method)) {
        FlexPostMethod postMethod = new FlexPostMethod(encodedPath);
        context.setHttpMethod(postMethod);
        if (context.hasAuthorization()) {
            postMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_GET.equals(method)) {
        FlexGetMethod getMethod = new FlexGetMethod(context.getTarget().getEncodedPath());
        context.setHttpMethod(getMethod);
        if (context.hasAuthorization()) {
            getMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_HEAD.equals(method)) {
        HeadMethod headMethod = new HeadMethod(encodedPath);
        context.setHttpMethod(headMethod);
    } else if (ProxyConstants.METHOD_PUT.equals(method)) {
        PutMethod putMethod = new PutMethod(encodedPath);
        context.setHttpMethod(putMethod);
    } else if (ProxyConstants.METHOD_OPTIONS.equals(method)) {
        OptionsMethod optionsMethod = new OptionsMethod(encodedPath);
        context.setHttpMethod(optionsMethod);
    } else if (ProxyConstants.METHOD_DELETE.equals(method)) {
        DeleteMethod deleteMethod = new DeleteMethod(encodedPath);
        context.setHttpMethod(deleteMethod);
    } else if (ProxyConstants.METHOD_TRACE.equals(method)) {
        TraceMethod traceMethod = new TraceMethod(encodedPath);
        context.setHttpMethod(traceMethod);
    } else {
        ProxyException pe = new ProxyException(INVALID_METHOD);
        pe.setDetails(INVALID_METHOD, "1", new Object[] { method });
        throw pe;
    }

    HttpMethodBase httpMethod = context.getHttpMethod();
    if (httpMethod instanceof EntityEnclosingMethod) {
        ((EntityEnclosingMethod) httpMethod).setContentChunked(context.getContentChunked());
    }
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI./*  w w w. 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 CustomHttpMethod(HTTPMethod.DELETE.name(), 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 {
        return new CustomHttpMethod(method.name(), requestURI.toString());
    }
}

From source file:com.atlantbh.jmeter.plugins.oauth.OAuthSampler.java

private HttpMethodBase createHttpMethod(String method, String urlStr) {
    HttpMethodBase httpMethod;/*from www.ja va2  s .co  m*/
    // 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);
        httpMethod = new GetMethod(urlStr);
    }
    return httpMethod;
}

From source file:com.cloudbees.api.BeesClient.java

/**
 * Sends a request in JSON and expects a JSON response back.
 *
 * @param urlTail The end point to hit. Appended to {@link #base}. Shouldn't start with '/'
 * @param method  HTTP method name like GET or POST.
 * @param headers/* ww w .ja  v  a2  s.  c  o  m*/
 *@param jsonContent  The json request payload, or null if none.  @throws IOException If the communication fails.
 */
public HttpReply jsonRequest(String urlTail, String method, Map<String, String> headers, String jsonContent)
        throws IOException {
    HttpMethodBase httpMethod;

    String urlString = absolutize(urlTail);

    trace("API call: " + urlString);
    if (method.equalsIgnoreCase("GET")) {
        httpMethod = new GetMethod(urlString);
    } else if ((method.equalsIgnoreCase("POST"))) {
        httpMethod = new PostMethod(urlString);
    } else if ((method.equalsIgnoreCase("PUT"))) {
        httpMethod = new PutMethod(urlString);
    } else if ((method.equalsIgnoreCase("DELETE"))) {
        httpMethod = new DeleteMethod(urlString);
    } else if ((method.equalsIgnoreCase("PATCH"))) {
        httpMethod = new PatchMethod(urlString);
    } else if ((method.equalsIgnoreCase("HEAD"))) {
        httpMethod = new HeadMethod(urlString);
    } else if ((method.equalsIgnoreCase("TRACE"))) {
        httpMethod = new TraceMethod(urlString);
    } else if ((method.equalsIgnoreCase("OPTIONS"))) {
        httpMethod = new OptionsMethod(urlString);
    } else
        throw new IOException("Method not supported: " + method);

    httpMethod.setRequestHeader("Accept", "application/json");
    if (jsonContent != null && httpMethod instanceof EntityEnclosingMethod) {
        StringRequestEntity requestEntity = new StringRequestEntity(jsonContent, "application/json", "UTF-8");
        ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        trace("Payload: " + jsonContent);
    }

    return executeRequest(httpMethod, headers);
}

From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java

private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException {
    shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT);
    try {/*  w w  w .  ja v  a2  s.  c o  m*/
        shuttle.sharedScope = context.getSharedScope();

        String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port);
        Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain);
        if (!shouldRewrite(domain)) {
            Engine.logSiteClipper.info(
                    "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector");
            shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "The domain " + domain + " is not allowed with this connector");
            return;
        }

        String uri = shuttle.getRequest(QueryPart.uri);

        Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl());

        HttpMethod httpMethod = null;
        XulRecorder xulRecorder = context.getXulRecorder();
        if (xulRecorder != null) {
            httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery());
        }
        if (httpMethod == null) {
            try {
                switch (shuttle.getRequestHttpMethodType()) {
                case GET:
                    httpMethod = new GetMethod(uri);
                    break;
                case POST:
                    httpMethod = new PostMethod(uri);
                    ((PostMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case PUT:
                    httpMethod = new PutMethod(uri);
                    ((PutMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    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:
                    throw new ServletException(
                            "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod());
                }
                httpMethod.setFollowRedirects(false);
            } catch (Exception e) {
                throw new ServletException(
                        "(SiteClipperConnector) unexpected exception will building the http method : "
                                + e.getMessage());
            }
            shuttle.httpMethod = httpMethod;

            SiteClipperScreenClass screenClass = getCurrentScreenClass();
            Engine.logSiteClipper.info("Request screen class: " + screenClass.getName());

            for (String name : Collections
                    .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) {
                if (requestHeadersToIgnore.contains(HeaderName.parse(name))) {
                    Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name);
                } else {
                    String value = shuttle.request.getHeader(name);
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) Copying request header " + name + "=" + value);
                    shuttle.setRequestCustomHeader(name, value);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass "
                    + screenClass.getName());
            for (IRequestRule rule : screenClass.getRequestRules()) {
                if (rule.isEnabled()) {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) applying request rule " + rule.getName());
                    rule.fireEvents();
                    boolean done = rule.applyOnRequest(shuttle);
                    Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName()
                            + " is " + (done ? "well" : "not") + " applied");
                } else {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName());
                }
            }

            for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey()
                        + "=" + header.getValue());
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }

            String queryString = shuttle.request.getQueryString();

            if (queryString != null) {
                try {
                    // Fake test in order to check query string validity
                    new URI("http://localhost/index?" + queryString, true,
                            httpMethod.getParams().getUriCharset());
                } catch (URIException e) {
                    // Bugfix #2103
                    StringBuffer newQuery = new StringBuffer();
                    for (String part : RegexpUtils.pattern_and.split(queryString)) {
                        String[] pair = RegexpUtils.pattern_equals.split(part, 2);
                        try {
                            newQuery.append('&')
                                    .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8"));
                            if (pair.length > 1) {
                                newQuery.append('=').append(
                                        URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException ee) {
                            Engine.logSiteClipper
                                    .trace("(SiteClipperConnector) failed to encode query part : " + part);
                        }
                    }

                    queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString();
                    Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString);
            httpMethod.setQueryString(queryString);

            //            if (context.httpState == null) {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID);
            //               context.httpState = new HttpState();
            //            } else {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID);
            //            }

            getHttpState(shuttle);

            HostConfiguration hostConfiguration = getHostConfiguration(shuttle);

            HttpMethodParams httpMethodParams = httpMethod.getParams();
            httpMethodParams.setBooleanParameter("http.connection.stalecheck", true);
            httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, true));

            Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " "
                    + hostConfiguration.getHostURL() + httpMethod.getURI().toString());

            HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool());
            HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool());
            httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState);
        } else {
            Engine.logSiteClipper.info("Retrieve recorded response from Context");
        }

        int status = httpMethod.getStatusCode();

        shuttle.processState = ProcessState.response;

        Engine.logSiteClipper.info("Request terminated with status " + status);
        shuttle.response.setStatus(status);

        if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK
                && shuttle.getResponseMimeType().startsWith("text/")) {
            fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString()));
        }

        SiteClipperScreenClass screenClass = getCurrentScreenClass();
        Engine.logSiteClipper.info("Response screen class: " + screenClass.getName());

        if (Engine.isStudioMode()) {
            Engine.theApp.fireObjectDetected(new EngineEvent(screenClass));
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            String name = header.getName();
            if (responseHeadersToIgnore.contains(HeaderName.parse(name))) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name);
            } else {
                String value = header.getValue();
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Copying response header " + name + "=" + value);
                shuttle.responseCustomHeaders.put(name, value);
            }
        }

        Engine.logSiteClipper.debug(
                "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName());
        for (IResponseRule rule : screenClass.getResponseRules()) {
            if (rule.isEnabled()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName());
                rule.fireEvents();
                boolean done = rule.applyOnResponse(shuttle);
                Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName()
                        + " is " + (done ? "well" : "not") + " applied");
            } else {
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName());
            }
        }

        for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) {
            Engine.logSiteClipper.trace(
                    "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue());
            shuttle.response.addHeader(header.getKey(), header.getValue());
        }

        if (shuttle.postInstructions != null) {
            JSONArray instructions = new JSONArray();
            for (IClientInstruction instruction : shuttle.postInstructions) {
                try {
                    instructions.put(instruction.getInstruction());
                } catch (JSONException e) {
                    Engine.logSiteClipper.error(
                            "(SiteClipperConnector) Failed to add a post instruction due to a JSONException",
                            e);
                }
            }
            String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n"
                    + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/jquery.min.js\"></script>\n" + "<script src=\""
                    + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/siteclipper.js\"></script>\n";

            String content = shuttle.getResponseAsString();
            Matcher matcher = HtmlLocation.head_top.matcher(content);
            String newContent = RegexpUtils.inject(matcher, codeToInject);
            if (newContent == null) {
                matcher = HtmlLocation.body_top.matcher(content);
                newContent = RegexpUtils.inject(matcher, codeToInject);
            }
            if (newContent != null) {
                shuttle.setResponseAsString(newContent);
            } else {
                Engine.logSiteClipper.info(
                        "(SiteClipperConnector) Failed to find a head or body tag in the response content");
                Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\"");
            }
        }

        long nbBytes = 0L;
        if (shuttle.responseAsString != null
                && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) {
            OutputStream os = shuttle.response.getOutputStream();
            switch (shuttle.getResponseContentEncoding()) {
            case gzip:
                os = new GZIPOutputStream(os);
                break;
            case deflate:
                os = new DeflaterOutputStream(os,
                        new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
                break;
            default:
                break;
            }
            nbBytes = shuttle.responseAsByte.length;
            IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset());
            os.close();
        } else {
            InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream()
                    : new ByteArrayInputStream(shuttle.responseAsByte);
            if (is != null) {
                nbBytes = 0;
                OutputStream os = shuttle.response.getOutputStream();
                int read = is.read();
                while (read >= 0) {
                    os.write(read);
                    os.flush();
                    read = is.read();
                    nbBytes++;
                }
                is.close();
                //               nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream());
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)");
            }
        }
        shuttle.response.getOutputStream().close();

        shuttle.score = getScore(nbBytes);
        Engine.logSiteClipper
                .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score);
    } finally {
        long duration = context.statistics.stop(shuttle.statisticsTaskID);
        if (context.requestedObject != null) {
            try {
                Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration),
                        Long.valueOf(shuttle.score));
            } catch (Exception e) {
                Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
    }
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

public byte[] getData(Context context) throws IOException, EngineException {
    HttpMethod method = null;/*ww w  .  jav  a  2s  .co m*/

    try {
        // Fire event for plugins
        long t0 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);

        // Retrieving httpState
        getHttpState(context);

        Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
        Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);

        // Setting the referer
        referer = sUrl;

        URL url = null;
        url = new URL(sUrl);

        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        Engine.logBeans.debug("(HttpConnector) Https: " + https);

        String host = "";
        int port = -1;
        if (sUrl.toLowerCase().startsWith("https:")) {
            if (!https) {
                Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
                certificateManager.collectStoreInformation(context);
            }

            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);

            Engine.logBeans
                    .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, this.trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            sUrl = url.getFile();
            Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
        } else {
            url = new URL(sUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }
        AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;

        // Retrieve HTTP method
        HttpMethodType httpVerb = httpTransaction.getHttpVerb();
        String sHttpVerb = httpVerb.name();
        final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();

        if (sCustomHttpVerb.length() > 0) {
            Engine.logBeans.debug(
                    "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case POST:
                method = new PostMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case PUT:
                method = new PutMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case DELETE:
                method = new DeleteMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case HEAD:
                method = new HeadMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            case TRACE:
                method = new TraceMethod(sUrl) {
                    @Override
                    public String getName() {
                        return sCustomHttpVerb;
                    }
                };
                break;
            }
        } else {
            Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);

            switch (httpVerb) {
            case GET:
                method = new GetMethod(sUrl);
                break;
            case POST:
                method = new PostMethod(sUrl);
                break;
            case PUT:
                method = new PutMethod(sUrl);
                break;
            case DELETE:
                method = new DeleteMethod(sUrl);
                break;
            case HEAD:
                method = new HeadMethod(sUrl);
                break;
            case OPTIONS:
                method = new OptionsMethod(sUrl);
                break;
            case TRACE:
                method = new TraceMethod(sUrl);
                break;
            }
        }

        // Setting HTTP parameters
        boolean hasUserAgent = false;

        for (List<String> httpParameter : httpParameters) {
            String key = httpParameter.get(0);
            String value = httpParameter.get(1);
            if (key.equalsIgnoreCase("host") && !value.equals(host)) {
                value = host;
            }

            if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
                method.setRequestHeader(key, value);
            }
            if (HeaderName.UserAgent.is(key)) {
                hasUserAgent = true;
            }
        }

        // set user-agent header if not found
        if (!hasUserAgent) {
            HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
        }

        // Setting POST or PUT parameters if any
        Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
            AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

            if (doMultipartFormData) {
                RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction
                        .getVariable(Parameter.HttpBody.getName());
                if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
                    String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
                    String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue,
                            getProject().getName());
                    File file = new File(filepath);
                    if (file.exists()) {
                        HeaderName.ContentType.setRequestHeader(method, contentType);
                        entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
                    } else {
                        throw new FileNotFoundException(file.getAbsolutePath());
                    }
                } else {
                    List<Part> parts = new LinkedList<Part>();

                    for (RequestableVariable variable : transaction.getVariablesList()) {
                        if (variable instanceof RequestableHttpVariable) {
                            RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                            if ("POST".equals(httpVariable.getHttpMethod())) {
                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addFormDataPart(parts, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addFormDataPart(parts, httpVariable, httpObjectVariableValue);
                                }
                            }
                        }
                    }
                    MultipartRequestEntity mre = new MultipartRequestEntity(
                            parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
                    HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
                    entityEnclosingMethod.setRequestEntity(mre);
                }
            } else if (MimeType.TextXml.is(contentType)) {
                final MimeMultipart[] mp = { null };

                for (RequestableVariable variable : transaction.getVariablesList()) {
                    if (variable instanceof RequestableHttpVariable) {
                        RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;

                        if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
                            Engine.logBeans.trace(
                                    "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");

                            MimeMultipart mimeMultipart = mp[0];
                            try {
                                if (mimeMultipart == null) {
                                    Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");

                                    mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
                                    MimeBodyPart bp = new MimeBodyPart();
                                    bp.setText(postQuery, "UTF-8");
                                    bp.setHeader(HeaderName.ContentType.value(), contentType);
                                    mimeMultipart.addBodyPart(bp);
                                }

                                Object httpObjectVariableValue = transaction
                                        .getVariableValue(httpVariable.getName());

                                if (httpVariable.isMultiValued()) {
                                    if (httpObjectVariableValue instanceof Collection<?>) {
                                        for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
                                            addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
                                        }
                                    }
                                } else {
                                    addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
                                }
                                mp[0] = mimeMultipart;
                            } catch (Exception e) {
                                Engine.logBeans.warn(
                                        "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(),
                                        e);
                            }
                        }
                    }
                }

                if (mp[0] == null) {
                    entityEnclosingMethod.setRequestEntity(
                            new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
                } else {
                    Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: "
                            + mp[0].getContentType());

                    HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
                    entityEnclosingMethod.setRequestEntity(new RequestEntity() {

                        @Override
                        public void writeRequest(OutputStream outputStream) throws IOException {
                            try {
                                mp[0].writeTo(outputStream);
                            } catch (MessagingException e) {
                                new IOException(e);
                            }
                        }

                        @Override
                        public boolean isRepeatable() {
                            return true;
                        }

                        @Override
                        public String getContentType() {
                            return mp[0].getContentType();
                        }

                        @Override
                        public long getContentLength() {
                            return -1;
                        }
                    });
                }
            } else {
                String charset = httpTransaction.getComputedUrlEncodingCharset();
                HeaderName.ContentType.setRequestHeader(method, contentType);
                entityEnclosingMethod
                        .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
            }
        }

        // Getting the result
        Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
        byte[] result = executeMethod(method, context);
        Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0));

        // Fire event for plugins
        long t1 = System.currentTimeMillis();
        Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);

        fireDataChanged(new ConnectorEvent(this, result));

        return result;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}