Search in sources :

Example 1 with RequestEntity

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

the class HttpProducer method createMethod.

/**
     * Creates the HttpMethod to use to call the remote server, either its GET or POST.
     *
     * @param exchange the exchange
     * @return the created method as either GET or POST
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
@SuppressWarnings("deprecation")
protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();
    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
        uri = new URI(url);
        // use raw query to have uri decimal encoded which http client requires
        queryString = uri.getRawQuery();
    }
    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
        url = url.substring(0, url.indexOf('?'));
    }
    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    String methodName = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null).name();
    HttpMethods methodsToUse = HttpMethods.valueOf(methodName);
    HttpMethod method = methodsToUse.createMethod(url);
    if (queryString != null) {
        // need to encode query string
        queryString = UnsafeUriCharactersEncoder.encode(queryString);
        method.setQueryString(queryString);
    }
    LOG.trace("Using URL: {} with method: {}", url, method);
    if (methodsToUse.isEntityEnclosing()) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        if (requestEntity != null && requestEntity.getContentType() == null) {
            LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
        }
    }
    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
        throw new IllegalArgumentException("Invalid uri: " + url + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint());
    }
    return method;
}
Also used : EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) 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) URI(java.net.URI) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 2 with RequestEntity

use of org.apache.commons.httpclient.methods.RequestEntity 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 3 with RequestEntity

use of org.apache.commons.httpclient.methods.RequestEntity in project pinot by linkedin.

the class FileUploadUtils method sendSegmentJsonImpl.

public static int sendSegmentJsonImpl(final String host, final String port, final JSONObject segmentJson) {
    PostMethod postMethod = null;
    try {
        RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
        postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        postMethod.setRequestEntity(requestEntity);
        postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
        int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
        if (statusCode >= 400) {
            String errorString = "POST Status Code: " + statusCode + "\n";
            if (postMethod.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return statusCode;
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpException(org.apache.commons.httpclient.HttpException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 4 with RequestEntity

use of org.apache.commons.httpclient.methods.RequestEntity in project pinpoint by naver.

the class HttpMethodBaseExecuteMethodInterceptor method recordEntity.

private void recordEntity(HttpMethod httpMethod, Trace trace) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            if (entitySampler.isSampling()) {
                try {
                    String entityValue;
                    String charSet = entityEnclosingMethod.getRequestCharSet();
                    if (charSet == null || charSet.isEmpty()) {
                        charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                    }
                    if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                        entityValue = entityUtilsToString(entity, charSet);
                    } else {
                        entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                    }
                    final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
                    recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
                } catch (Exception e) {
                    logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
                }
            }
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) URIException(org.apache.commons.httpclient.URIException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 5 with RequestEntity

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

the class JaxbFallbackTypeConverterTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            // setup the camel property for the PrettyPrint
            context.getProperties().put(FallbackTypeConverter.PRETTY_PRINT, "false");
            from("direct:start").process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    Message in = exchange.getIn();
                    RequestEntity entity = in.getBody(RequestEntity.class);
                    assertNull("We should not get the entity here", entity);
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    // make sure we can get the InputStream rightly.
                    exchange.getOut().setBody(is);
                }
            });
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) Message(org.apache.camel.Message) InputStream(java.io.InputStream) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity)

Aggregations

RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)11 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)6 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)5 IOException (java.io.IOException)3 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)3 FileRequestEntity (org.apache.commons.httpclient.methods.FileRequestEntity)3 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)3 PostMethod (org.apache.commons.httpclient.methods.PostMethod)3 PutMethod (org.apache.commons.httpclient.methods.PutMethod)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 InputStream (java.io.InputStream)2 Message (org.apache.camel.Message)2 HttpClient (org.apache.commons.httpclient.HttpClient)2 HttpMethod (org.apache.commons.httpclient.HttpMethod)2 GetMethod (org.apache.commons.httpclient.methods.GetMethod)2 SpanEventRecorder (com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder)1 Serializable (java.io.Serializable)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1