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:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;//from w  w w .  j a v  a2 s . co m
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.ozsoft.xmldb.exist.ExistConnector.java

@Override
public void storeResource(String uri, InputStream is) throws XmldbException {
    // Use the REST interface for storing resources.
    String actualUri = String.format("%s/rest%s", existUri, uri);
    PutMethod putMethod = new PutMethod(actualUri);
    putMethod.setRequestEntity(new InputStreamRequestEntity(is));
    try {//from  w  ww . j  ava 2s.  c om
        int statusCode = httpClient.executeMethod(putMethod);
        if (statusCode >= STATUS_ERROR) {
            if (statusCode == NOT_FOUND) {
                throw new NotFoundException(uri);
            } else if (statusCode == AUTHORIZATION_REQUIRED || statusCode == NOT_AUTHORIZED) {
                throw new NotAuthorizedException(String.format("Not authorized to store resource '%s'", uri));
            } else {
                throw new XmldbException(
                        String.format("Could not store resource '%s' (HTTP status code: %d)", uri, statusCode));
            }
        }
    } catch (IOException e) {
        String msg = String.format("Could not store resource '%s': %s", uri, e.getMessage());
        LOG.error(msg, e);
        throw new XmldbException(msg, e);
    }
}

From source file:org.pentaho.di.cluster.SlaveServer.java

PostMethod buildSendExportMethod(String type, String load, InputStream is) throws UnsupportedEncodingException {
    String serviceUrl = AddExportServlet.CONTEXT_PATH;
    if (type != null && load != null) {
        serviceUrl += "/?" + AddExportServlet.PARAMETER_TYPE + "=" + type + "&"
                + AddExportServlet.PARAMETER_LOAD + "=" + URLEncoder.encode(load, "UTF-8");
    }//from  w  w w.j  a va  2s  .  com

    String urlString = constructUrl(serviceUrl);
    if (log.isDebug()) {
        log.logDebug(BaseMessages.getString(PKG, "SlaveServer.DEBUG_ConnectingTo", urlString));
    }

    PostMethod method = new PostMethod(urlString);
    method.setRequestEntity(new InputStreamRequestEntity(is));
    method.setDoAuthentication(true);
    method.addRequestHeader(new Header("Content-Type", "binary/zip"));

    return method;
}

From source file:org.pentaho.di.sdk.samples.carte.AddExportSample.java

public static void addExportToServlet(String urlString, InputStream is, String authentication)
        throws Exception {
    PostMethod method = new PostMethod(urlString);
    method.setRequestEntity(new InputStreamRequestEntity(is));
    method.setDoAuthentication(true);//  ww w.ja  v a 2s.c  om
    method.addRequestHeader(new Header("Content-Type", "binary/zip"));
    //adding authorization token
    if (authentication != null) {
        method.addRequestHeader(new Header("Authorization", authentication));
    }

    //executing method
    HttpClient client = new HttpClient();
    int code = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    method.releaseConnection();
    if (code >= 400) {
        System.out.println("Error occurred during export submission.");
    }
    System.out.println("Server response:");
    System.out.println(response);
}

From source file:org.pentaho.di.sdk.samples.carte.RegisterPackageSample.java

public static void addPackageToServlet(String urlString, InputStream is, String authentication)
        throws Exception {
    PostMethod method = new PostMethod(urlString);
    method.setRequestEntity(new InputStreamRequestEntity(is));
    method.setDoAuthentication(true);//from w  ww .ja v  a  2s.  c o m
    method.addRequestHeader(new Header("Content-Type", "binary/zip"));
    //adding authorization token
    if (authentication != null) {
        method.addRequestHeader(new Header("Authorization", authentication));
    }

    //executing method
    HttpClient client = new HttpClient();
    int code = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    method.releaseConnection();
    if (code >= 400) {
        System.out.println("Error occurred during export submission.");
    }
    System.out.println("Server response:");
    System.out.println(response);
}

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

protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());/*from   w  w w  . j  a  v a  2  s . co  m*/
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(resourceBundle.getString("error.nosession"));
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(resourceBundle.getString("error.nomemento"));
    }
    final BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(resourceBundle.getString("error.nobridgerequest"));
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(resourceBundle.getString("error.noperportletmemento"));
    }

    // go and fetch the data from the backend as appropriate
    final URI url = bridgeRequest.getUrl();

    log.debug("doPost(): URL=" + url);

    try {
        PostMethod postMethod = new PostMethod(url.toString());
        copyRequestHeaders(request, postMethod);
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        httpClientTemplate.service(postMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(bridgeRequest.getId(),
                                new PortletBridgeContent(url, "post", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end

                        log.debug("doPost(): doing response.sendRedirect to URL=" + bridgeRequest.getPageUrl());

                        response.sendRedirect(bridgeRequest.getPageUrl());
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        response.setContentType(method.getResponseHeader("Content-Type").toExternalForm());
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header locationHeader = method.getResponseHeader("Location");
                    if (locationHeader != null) {
                        URI redirectUrl = new URI(locationHeader.getValue().trim());
                        log.debug("redirecting to [" + redirectUrl + "]");
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        BridgeRequest updatedBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), redirectUrl);
                        fetch(request, response, updatedBridgeRequest, memento, perPortletMemento, redirectUrl);

                    } else {
                        throw new PortletBridgeException("error.missingLocation");
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

public Map<String, Object> updateDocument(Node node, String path, Map<String, Object> properties,
        InputStream documentStream, long streamLength) throws DocProxyException {
    PostMethod method = new PostMethod(updateUrl + path);
    for (Entry<String, Object> entry : properties.entrySet()) {
        method.addParameter(entry.getKey(), entry.getValue().toString());
    }/*from w  w  w  . j  a v  a 2 s.  c o m*/
    method.setRequestEntity(new InputStreamRequestEntity(documentStream));
    executeMethod(method, node);
    return null;
}

From source file:org.sonatype.nexus.integrationtests.nxcm970.ContinuousDeployer.java

public void run() {
    PutMethod method = new PutMethod(targetUrl);

    method.setRequestEntity(new InputStreamRequestEntity(new EndlessBlockingInputStream(this)));

    try {/*from ww  w .  ja  v  a2s.c o m*/
        result = httpClient.executeMethod(method);
    } catch (Exception e) {
        result = -2;

        e.printStackTrace();
    }
}

From source file:org.springbyexample.httpclient.HttpClientTemplate.java

/**
 * Execute post method.//  w w  w  .  java2 s  .  co m
 * 
 * @param   input           <code>InputStream</code> to post 
 *                          for the request's data.
 * @param   callback        Callback with HTTP method's response.
 */
public void executePostMethod(InputStream input, ResponseCallback<?> callback) {
    executePostMethod(defaultUri, new InputStreamRequestEntity(input), null, callback);
}

From source file:org.springframework.ws.transport.http.WebServiceHttpHandlerIntegrationTest.java

@Test
public void testNoResponse() throws IOException {
    PostMethod postMethod = new PostMethod(url);
    postMethod.addRequestHeader(HttpTransportConstants.HEADER_CONTENT_TYPE, "text/xml");
    postMethod.addRequestHeader(TransportConstants.HEADER_SOAP_ACTION,
            "http://springframework.org/spring-ws/NoResponse");
    Resource soapRequest = new ClassPathResource("soapRequest.xml", WebServiceHttpHandlerIntegrationTest.class);
    postMethod.setRequestEntity(new InputStreamRequestEntity(soapRequest.getInputStream()));
    client.executeMethod(postMethod);/*from w w  w.  ja va 2 s. co m*/
    assertEquals("Invalid Response Code", HttpTransportConstants.STATUS_ACCEPTED, postMethod.getStatusCode());
    assertEquals("Response retrieved", 0, postMethod.getResponseContentLength());
}