Search in sources :

Example 1 with InputStreamRequestEntity

use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project camel by apache.

the class HttpProducer method createRequestEntity.

/**
     * Creates a holder object for the data to send to the remote server.
     *
     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }
    RequestEntity answer = in.getBody(RequestEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentType = ExchangeHelper.getContentType(exchange);
                if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
                    if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        answer = new FileRequestEntity(file, contentType);
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    answer = new StringRequestEntity((String) data, contentType, charset);
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    answer = new InputStreamRequestEntity(is, contentType);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Message(org.apache.camel.Message) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 2 with InputStreamRequestEntity

use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project openhab1-addons by openhab.

the class AbstractRequest method executeUrl.

/**
     * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
     * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
     * 
     * @param httpMethod
     *            the HTTP method to use
     * @param url
     *            the url to execute (in milliseconds)
     * @param contentString
     *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
     *            sent.
     * @param contentType
     *            the content type of the given <code>contentString</code>
     * @return the response body or <code>NULL</code> when the request went wrong
     */
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
    HttpClient client = new HttpClient();
    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(httpRequestTimeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }
    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }
        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }
        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    return null;
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 3 with InputStreamRequestEntity

use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.

the class UserServlet method putRemoteResource.

public static Pair<Header[], HttpInputStream> putRemoteResource(ZAuthToken authToken, String url, InputStream req, Header[] headers) throws ServiceException, IOException {
    StringBuilder u = new StringBuilder(url);
    u.append("?").append(QP_AUTH).append('=').append(AUTH_COOKIE);
    PutMethod method = new PutMethod(u.toString());
    String contentType = "application/octet-stream";
    if (headers != null) {
        for (Header hdr : headers) {
            String name = hdr.getName();
            method.addRequestHeader(hdr);
            if (name.equals("Content-Type"))
                contentType = hdr.getValue();
        }
    }
    method.setRequestEntity(new InputStreamRequestEntity(req, contentType));
    Pair<Header[], HttpMethod> pair = doHttpOp(authToken, method);
    return new Pair<Header[], HttpInputStream>(pair.getFirst(), new HttpInputStream(pair.getSecond()));
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Header(org.apache.commons.httpclient.Header) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) Pair(com.zimbra.common.util.Pair)

Example 4 with InputStreamRequestEntity

use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.

the class ZimbraServlet method proxyServletRequest.

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server, String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpState(org.apache.commons.httpclient.HttpState) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 5 with InputStreamRequestEntity

use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.

the class TestZimbraHttpConnectionManager method testSoTimeoutViaHttpPostMethod.

// @Test
public void testSoTimeoutViaHttpPostMethod() throws Exception {
    int serverPort = 7778;
    String resourceToPost = "/opt/zimbra/unittest/rights-unittest.xml";
    // delay 10 seconds in server
    long delayInServer = 100000;
    // 3000;  // 3 seconds, 0 for infinite wait
    int soTimeout = 60000;
    String qp = "?" + SimpleHttpServer.DelayWhen.BEFORE_WRITING_RESPONSE_HEADERS.name() + "=" + delayInServer;
    String uri = "http://localhost:" + serverPort + resourceToPost + qp;
    // start a http server for testing
    SimpleHttpServer.start(serverPort);
    // post the exported content to the target server
    HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod method = new PostMethod(uri);
    // infinite wait because it can take a long time to import a large mailbox
    method.getParams().setSoTimeout(soTimeout);
    File file = new File(resourceToPost);
    FileInputStream fis = null;
    long startTime = System.currentTimeMillis();
    long endTime;
    try {
        fis = new FileInputStream(file);
        InputStreamRequestEntity isre = new InputStreamRequestEntity(fis, file.length(), MimeConstants.CT_APPLICATION_OCTET_STREAM);
        method.setRequestEntity(isre);
        int respCode = httpClient.executeMethod(method);
        dumpResponse(respCode, method, "");
        // nope, it should have timed out
        Assert.fail();
    } catch (java.net.SocketTimeoutException e) {
        e.printStackTrace();
        // good, just what we want
        endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("Client timed out after " + elapsedTime + " msecs");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        method.releaseConnection();
    }
    // shutdown the server
    SimpleHttpServer.shutdown();
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) java.net(java.net) ServiceException(com.zimbra.common.service.ServiceException)

Aggregations

InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)5 HttpClient (org.apache.commons.httpclient.HttpClient)4 HttpMethod (org.apache.commons.httpclient.HttpMethod)4 GetMethod (org.apache.commons.httpclient.methods.GetMethod)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 InputStream (java.io.InputStream)3 Header (org.apache.commons.httpclient.Header)3 PutMethod (org.apache.commons.httpclient.methods.PutMethod)3 ZMailbox (com.zimbra.client.ZMailbox)2 Pair (com.zimbra.common.util.Pair)2 IOException (java.io.IOException)2 URI (java.net.URI)2 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)2 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)2 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)2 Test (org.junit.Test)2 ServiceException (com.zimbra.common.service.ServiceException)1 Document (com.zimbra.cs.mailbox.Document)1