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

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

Introduction

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

Prototype

public InputStreamRequestEntity(InputStream paramInputStream) 

Source Link

Usage

From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java

@Override
public String startAnalysis(String id, String language, List<String> options, InputStream body)
        throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/corefacade/analyze", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);

    NameValuePair[] queryString = new NameValuePair[2 + options.size()];
    queryString[0] = new NameValuePair("id", id);
    queryString[1] = new NameValuePair("language", language);
    int count = 2;
    for (String option : options) {
        queryString[count] = new NameValuePair("option", option);
        count++;//from ww w. j  ava2s . co  m
    }
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity = new InputStreamRequestEntity(body);
    postMethod.setRequestEntity(requestEntity);

    try {
        httpClient.executeMethod(postMethod);
        return postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:de.mpg.escidoc.services.test.search.TestBase.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * //w w w  . jav a2 s  .c  om
 * @param filename The file to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file
 * @throws Exception
 */
protected static URL uploadFile(String filename, String mimetype, String userHandle) throws Exception {
    XmlTransforming xmlTransforming = (XmlTransforming) getService(
            "ejb:search_ear/common_logic/XmlTransformingBean!" + XmlTransforming.class.getName());
    // Prepare the HttpMethod.
    String fwUrl = ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");

    method.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(filename)));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);

    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    ProxyHelper.executeMethod(client, method);
    String response = method.getResponseBodyAsString();
    assertEquals(HttpServletResponse.SC_OK, method.getStatusCode());

    return xmlTransforming.transformUploadResponseToFileURL(response);

}

From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.ImportProcess.java

private String createTaskItemXml() {
    try {/*from   w ww. j  a va 2s.  c om*/

        String fwUrl = PropertyReader.getFrameworkUrl();
        HttpClient client = new HttpClient();
        ProxyHelper.setProxy(client, fwUrl);

        StringBuilder sb = new StringBuilder(ResourceUtil.getResourceAsString(
                "multipleImport/ImportTaskTemplate.xml", ImportProcess.class.getClassLoader()));
        replace("$01", escape(this.escidocContext.getObjectId()), sb);
        replace("$02", escape(PropertyReader.getProperty("escidoc.import.task.content-model")), sb);
        replace("$03", escape("Import Task Item for import " + name + " "), sb);

        // Upload original data
        PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
        method.setRequestHeader("Content-Type", this.format.toString());
        method.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        InputStream is = new FileInputStream(this.formatProcessor.getSourceFile());
        method.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method);
        is.close();
        String response = method.getResponseBodyAsString();
        URL originalDataUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$04", escape(this.name), sb);
        replace("$05", escape(this.fileName), sb);
        replace("$06", escape(originalDataUrl.toExternalForm()), sb);
        replace("$07", escape(log.getStoredId() + ""), sb);
        replace("$08", escape(this.format.toString()), sb);
        replace("$09", escape(String.valueOf(this.formatProcessor.getLength())), sb);

        // Upload and create task item xml
        File tempLogXml = File.createTempFile("multipleImportLogXml", "xml");
        Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempLogXml), "UTF-8"));
        log.toXML(fw);
        fw.flush();
        fw.close();

        PutMethod method2 = new PutMethod(fwUrl + "/st/staging-file");
        method2.setRequestHeader("Content-Type", "text/xml");
        method2.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        is = new FileInputStream(tempLogXml);
        method2.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method2);
        is.close();

        response = method2.getResponseBodyAsString();
        URL logXmlUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$10", escape(this.name), sb);
        replace("$11", "importlog.xml", sb);
        replace("$12", escape(logXmlUrl.toExternalForm()), sb);
        replace("$13", escape(log.getStoredId() + ""), sb);
        replace("$14", escape(String.valueOf(tempLogXml.length())), sb);

        tempLogXml.delete();

        /*
         * String taskItemXml =
         * ResourceUtil.getResourceAsString("multipleImport/ImportTaskTemplate.xml"); taskItemXml =
         * taskItemXml.replace("$1", escape(this.escidocContext.getObjectId())); taskItemXml =
         * taskItemXml.replace("$2",
         * escape(PropertyReader.getProperty("escidoc.import.task.content-model"))); taskItemXml =
         * taskItemXml.replace("$4", escape(this.name)); taskItemXml = taskItemXml.replace("$5",
         * escape(this.fileName)); taskItemXml = taskItemXml.replace("$6",
         * escape(this.formatProcessor.getDataAsBase64())); taskItemXml = taskItemXml.replace("$7",
         * escape(log.getStoredId() + "")); taskItemXml = taskItemXml.replace("$8",
         * escape(this.format.toString())); taskItemXml = taskItemXml.replace("$9",
         * escape(this.formatProcessor.getLength() + ""));
         */
        log.finishItem();

        log.close();

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.pubman.multipleimport.ImportProcess.java

private String createTaskItemXml() {
    try {//  w w w  . j  ava2 s  .com

        String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
        HttpClient client = new HttpClient();
        ProxyHelper.setProxy(client, fwUrl);

        StringBuilder sb = new StringBuilder(ResourceUtil.getResourceAsString(
                "multipleImport/ImportTaskTemplate.xml", ImportProcess.class.getClassLoader()));
        replace("$01", escape(this.escidocContext.getObjectId()), sb);
        replace("$02", escape(PropertyReader.getProperty("escidoc.import.task.content-model")), sb);
        replace("$03", escape("Import Task Item for import " + name + " "), sb);

        //Upload original data
        PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
        method.setRequestHeader("Content-Type", this.format.toString());
        method.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        InputStream is = new FileInputStream(this.formatProcessor.getSourceFile());
        method.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method);
        is.close();
        String response = method.getResponseBodyAsString();
        URL originalDataUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$04", escape(this.name), sb);
        replace("$05", escape(this.fileName), sb);
        replace("$06", escape(originalDataUrl.toExternalForm()), sb);
        replace("$07", escape(log.getStoredId() + ""), sb);
        replace("$08", escape(this.format.toString()), sb);
        replace("$09", escape(String.valueOf(this.formatProcessor.getLength())), sb);

        //Upload and create task item xml
        File tempLogXml = File.createTempFile("multipleImportLogXml", "xml");
        Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempLogXml), "UTF-8"));
        log.toXML(fw);
        fw.flush();
        fw.close();

        PutMethod method2 = new PutMethod(fwUrl + "/st/staging-file");
        method2.setRequestHeader("Content-Type", "text/xml");
        method2.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        is = new FileInputStream(tempLogXml);
        method2.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method2);
        is.close();

        response = method2.getResponseBodyAsString();
        URL logXmlUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$10", escape(this.name), sb);
        replace("$11", "importlog.xml", sb);
        replace("$12", escape(logXmlUrl.toExternalForm()), sb);
        replace("$13", escape(log.getStoredId() + ""), sb);
        replace("$14", escape(String.valueOf(tempLogXml.length())), sb);

        tempLogXml.delete();

        /*
         String taskItemXml = ResourceUtil.getResourceAsString("multipleImport/ImportTaskTemplate.xml");
         taskItemXml = taskItemXml.replace("$1", escape(this.escidocContext.getObjectId()));
         taskItemXml = taskItemXml.replace("$2",
            escape(PropertyReader.getProperty("escidoc.import.task.content-model")));
         taskItemXml = taskItemXml.replace("$4", escape(this.name));
         taskItemXml = taskItemXml.replace("$5", escape(this.fileName));
         taskItemXml = taskItemXml.replace("$6", escape(this.formatProcessor.getDataAsBase64()));
         taskItemXml = taskItemXml.replace("$7", escape(log.getStoredId() + ""));
         taskItemXml = taskItemXml.replace("$8", escape(this.format.toString()));
         taskItemXml = taskItemXml.replace("$9", escape(this.formatProcessor.getLength() + ""));
        */
        log.finishItem();

        log.close();

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public int postDocument(InputStream stream) throws IOException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;/*from  w  w  w  .ja v a  2  s.  c o m*/
    String urlStr = solrHost + "/update?commit=true";
    Log.debug("Ingesting a new document to: " + urlStr);
    method = new PostMethod(urlStr);
    RequestEntity entity = new InputStreamRequestEntity(stream);
    ((PostMethod) method).setRequestEntity(entity);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setRequestHeader("Content-Type", "text/xml");
    method.setRequestHeader("charset", "utf-8");

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsStream());

    Log.debug(solrResponse.getXMLDocumentString());
    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        Log.error(solrResponse.getXMLDocumentString());
    } else
        Log.debug(solrResponse.getXMLDocumentString());
    return statusCode;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Sets up the given {@link PostMethod} to send the same standard POST data as was sent in the given {@link HttpServletRequest}
 * /*from  ww  w.j  a  va  2s .com*/
 * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 * @throws IOException
 */
private void handleStandard(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {
    try {

        InputStream is = httpServletRequest.getInputStream();

        methodProxyRequest.setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        //LOGGER.info("original request content length:" + httpServletRequest.getContentLength());
        //LOGGER.info("proxied request content length:" +methodProxyRequest.getRequestEntity().getContentLength()+"");

    } catch (IOException e) {
        throw new IOException(e);
    }
}

From source file:de.mpg.mpdl.inge.pubman.web.editItem.EditItem.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * //from ww w . ja  v a  2 s  .  com
 * @param uploadedFile The file to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = PropertyReader.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    // if(uploadedFile.isTempFile())
    // {
    InputStream fis = uploadedFile.getInputstream();
    method.setRequestEntity(new InputStreamRequestEntity(fis));
    /*
     * } else { method.setRequestEntity(new InputStreamRequestEntity(new
     * ByteArrayInputStream(uploadedFile.getData()))); }
     */

    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    ProxyHelper.setProxy(client, fwUrl);
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    fis.close();

    return xmlTransforming.transformUploadResponseToFileURL(response);
}

From source file:de.mpg.escidoc.pubman.editItem.EditItem.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*from www.  ja  va  2  s. com*/
 * @param uploadedFile The file to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    //if(uploadedFile.isTempFile())
    //{
    InputStream fis = uploadedFile.getInputstream();
    method.setRequestEntity(new InputStreamRequestEntity(fis));
    /*    
    }
     else
     {
        method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(uploadedFile.getData())));
     }
     */

    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    ProxyHelper.setProxy(client, fwUrl);
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    fis.close();

    return xmlTransforming.transformUploadResponseToFileURL(response);
}

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 {//from  w  ww.  ja v  a2  s . c  om
        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.adobe.share.api.ShareAPI.java

/**
 * Prepares a new HTTP request.//from  w  w  w . j a  v a 2s. c o  m
 *
 * @param user the user
 * @param method the method
 * @param url the url
 * @param anon the anon
 * @param requestBody the request body
 *
 * @return the http method
 */
protected final HttpMethod createRequest(final ShareAPIUser user, final String method, final String url,
        final boolean anon, final String requestBody) {
    HttpMethod httpMethod = null;
    if ("GET".equals(method)) {
        httpMethod = new GetMethod(url);
    } else if ("POST".equals(method)) {
        httpMethod = new PostMethod(url);
        httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(requestBody, null, null));
        } catch (UnsupportedEncodingException uee) {
            // Catch the unsupported encoding exception
            LOGGER.error("Unsupported encoding exception: " + uee.getMessage());
        }
    } else if ("PUT".equals(method)) {
        httpMethod = new PutMethod(url);
        httpMethod.setRequestHeader("Content-Type", "text/plain");
        if (requestBody != null) {
            ((PutMethod) httpMethod).setRequestEntity(
                    new InputStreamRequestEntity(new ByteArrayInputStream(requestBody.getBytes())));
        }
    } else if ("DELETE".equals(method)) {
        httpMethod = new DeleteMethod(url);
    } else if ("HEAD".equals(method)) {
        httpMethod = new HeadMethod(url);
    }
    /**
     * MoveMethod not supported by HttpClient else if("MOVE".equals(method))
     * { httpMethod = new MoveMethod(url); }
     **/
    httpMethod.setRequestHeader("Authorization", generateAuthorization(user, anon, method, url));

    return httpMethod;
}