camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ningji...@apache.org
Subject svn commit: r651239 - in /activemq/camel/trunk/components/camel-http: ./ src/main/java/org/apache/camel/component/http/ src/main/java/org/apache/camel/component/http/helper/ src/test/java/org/apache/camel/component/http/
Date Thu, 24 Apr 2008 12:14:10 GMT
Author: ningjiang
Date: Thu Apr 24 05:14:09 2008
New Revision: 651239

URL: http://svn.apache.org/viewvc?rev=651239&view=rev
Log:
CAMEL-479 appiled patch with thanks to Justin, also fixed some warnning message from the method.getResponse()
by copying the inputstream

Added:
    activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
  (with props)
    activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/
    activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
  (with props)
    activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
  (with props)
Modified:
    activemq/camel/trunk/components/camel-http/pom.xml
    activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpPollingConsumer.java
    activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java

Modified: activemq/camel/trunk/components/camel-http/pom.xml
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/pom.xml?rev=651239&r1=651238&r2=651239&view=diff
==============================================================================
--- activemq/camel/trunk/components/camel-http/pom.xml (original)
+++ activemq/camel/trunk/components/camel-http/pom.xml Thu Apr 24 05:14:09 2008
@@ -7,9 +7,9 @@
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
-  
+
   http://www.apache.org/licenses/LICENSE-2.0
-  
+
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -52,6 +52,13 @@
       <groupId>commons-httpclient</groupId>
       <artifactId>commons-httpclient</artifactId>
       <version>3.1</version>
+      <optional>false</optional>
+    </dependency>
+
+    <dependency>
+      <groupId>commons-io</groupId>
+      <artifactId>commons-io</artifactId>
+      <version>1.3.1</version>
       <optional>false</optional>
     </dependency>
 

Added: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java?rev=651239&view=auto
==============================================================================
--- activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
(added)
+++ activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
Thu Apr 24 05:14:09 2008
@@ -0,0 +1,71 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.http;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Expression;
+import org.apache.camel.builder.ExpressionBuilder;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.HeadMethod;
+import org.apache.commons.httpclient.methods.OptionsMethod;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.TraceMethod;
+
+public enum HttpMethods implements Expression<Exchange> {
+
+    GET(GetMethod.class), POST(PostMethod.class), PUT(PutMethod.class), DELETE(DeleteMethod.class),
HEAD(
+        HeadMethod.class), OPTIONS(OptionsMethod.class), TRACE(TraceMethod.class);
+
+    public static final String HTTP_METHOD = "http.requestMethod";
+
+    final Class<? extends HttpMethod> clazz;
+    final boolean entity;
+
+    HttpMethods(Class<? extends HttpMethod> clazz) {
+        this.clazz = clazz;
+        entity = EntityEnclosingMethod.class.isAssignableFrom(clazz);
+    }
+
+    public HttpMethod createMethod(final String url) {
+        try {
+            return clazz.getDeclaredConstructor(String.class).newInstance(url);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public HttpMethod createMethod() {
+        try {
+            return clazz.newInstance();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public final boolean isEntityEnclosing() {
+        return entity;
+    }
+
+    public Object evaluate(Exchange exchange) {
+        return ExpressionBuilder.constantExpression(name()).evaluate(exchange);
+    }
+
+}

Propchange: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpMethods.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Modified: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpPollingConsumer.java
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpPollingConsumer.java?rev=651239&r1=651238&r2=651239&view=diff
==============================================================================
--- activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpPollingConsumer.java
(original)
+++ activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpPollingConsumer.java
Thu Apr 24 05:14:09 2008
@@ -17,14 +17,17 @@
 package org.apache.camel.component.http;
 
 import java.io.IOException;
+import java.io.InputStream;
 
 import org.apache.camel.Message;
 import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.component.http.helper.LoadingByteArrayOutputStream;
 import org.apache.camel.impl.PollingConsumerSupport;
 import org.apache.commons.httpclient.Header;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.io.IOUtils;
 
 /**
  * A polling HTTP consumer which by default performs a GET
@@ -50,15 +53,19 @@
     }
 
     public HttpExchange receiveNoWait() {
+        HttpExchange exchange = endpoint.createExchange();
+        HttpMethod method = createMethod();
+
         try {
-            HttpExchange exchange = endpoint.createExchange();
-            HttpMethod method = createMethod();
             int responseCode = httpClient.executeMethod(method);
-
             // lets store the result in the output message.
-            byte[] responseBody = method.getResponseBody();
+            LoadingByteArrayOutputStream bos = new LoadingByteArrayOutputStream();
+            InputStream is = method.getResponseBodyAsStream();
+            IOUtils.copy(is, bos);
+            bos.flush();
+            is.close();
             Message message = exchange.getIn();
-            message.setBody(responseBody);
+            message.setBody(bos.createInputStream());
 
             // lets set the headers
             Header[] headers = method.getResponseHeaders();
@@ -72,6 +79,8 @@
             return exchange;
         } catch (IOException e) {
             throw new RuntimeCamelException(e);
+        } finally {
+            method.releaseConnection();
         }
     }
 

Modified: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java?rev=651239&r1=651238&r2=651239&view=diff
==============================================================================
--- activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java
(original)
+++ activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java
Thu Apr 24 05:14:09 2008
@@ -16,19 +16,30 @@
  */
 package org.apache.camel.component.http;
 
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
 import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.Message;
 import org.apache.camel.Producer;
+import org.apache.camel.component.http.helper.LoadingByteArrayOutputStream;
 import org.apache.camel.impl.DefaultProducer;
 import org.apache.commons.httpclient.Header;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
 import org.apache.commons.httpclient.methods.RequestEntity;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.commons.io.IOUtils;
+
+
+import static org.apache.camel.component.http.HttpMethods.HTTP_METHOD;
 
 /**
  * @version $Revision$
@@ -37,6 +48,11 @@
     public static final String HTTP_RESPONSE_CODE = "http.responseCode";
     public static final String QUERY = "org.apache.camel.component.http.query";
 
+    // This should be a set of lower-case strings
+    public static final Set<String> HEADERS_TO_SKIP = new HashSet<String>(Arrays.asList("content-length",
+                                                                                        "content-type",
+                                                                                        HTTP_RESPONSE_CODE
+                                                                                        
   .toLowerCase()));
     private HttpClient httpClient;
 
     public HttpProducer(HttpEndpoint endpoint) {
@@ -46,22 +62,31 @@
 
     public void process(Exchange exchange) throws Exception {
         HttpMethod method = createMethod(exchange);
-
+        Message in = exchange.getIn();
         HttpBinding binding = ((HttpEndpoint)getEndpoint()).getBinding();
         // propagate headers as HTTP headers
-        for (String headerName : exchange.getIn().getHeaders().keySet()) {
-            String headerValue = exchange.getIn().getHeader(headerName, String.class);
+        for (String headerName : in.getHeaders().keySet()) {
+            String headerValue = in.getHeader(headerName, String.class);
             if (binding.shouldHeaderBePropagated(headerName, headerValue)) {
                 method.addRequestHeader(headerName, headerValue);
             }
         }
 
-        int responseCode = httpClient.executeMethod(method);
-
         // lets store the result in the output message.
-        InputStream in = method.getResponseBodyAsStream();
         Message out = exchange.getOut(true);
-        out.setBody(in);
+        try {
+            int responseCode = httpClient.executeMethod(method);
+            out.setHeaders(in.getHeaders());
+            out.setHeader(HTTP_RESPONSE_CODE, responseCode);
+            LoadingByteArrayOutputStream bos = new LoadingByteArrayOutputStream();
+            InputStream is = method.getResponseBodyAsStream();
+            IOUtils.copy(is, bos);
+            bos.flush();
+            is.close();
+            out.setBody(bos.createInputStream());
+        } finally {
+            method.releaseConnection();
+        }
 
         // lets set the headers
         Header[] headers = method.getResponseHeaders();
@@ -71,7 +96,6 @@
             out.setHeader(name, value);
         }
 
-        out.setHeader(HTTP_RESPONSE_CODE, responseCode);
     }
 
     public HttpClient getHttpClient() {
@@ -84,36 +108,61 @@
 
     protected HttpMethod createMethod(Exchange exchange) {
         String uri = ((HttpEndpoint)getEndpoint()).getHttpUri().toString();
+
         RequestEntity requestEntity = createRequestEntity(exchange);
-        if (requestEntity == null) {
-            GetMethod method = new GetMethod(uri);
-            if (exchange.getIn().getHeader(QUERY) != null) {
-                method.setQueryString(exchange.getIn().getHeader(QUERY, String.class));
-            }
-            return method;
+        Object m = exchange.getIn().getHeader(HTTP_METHOD);
+        HttpMethods ms = m instanceof HttpMethods
+            ? (HttpMethods)m : HttpMethods.valueOf(m == null
+                                                       ? requestEntity == null
+                                                           ? "GET" : "POST"
+                                                               : m.toString());
+
+        HttpMethod method = ms.createMethod(uri);
+
+        if (exchange.getIn().getHeader(QUERY) != null) {
+            method.setQueryString(exchange.getIn().getHeader(QUERY, String.class));
+        }
+        if (ms.isEntityEnclosing()) {
+            ((EntityEnclosingMethod)method).setRequestEntity(requestEntity);
         }
-        // TODO we might be PUT? - have some better way to explicitly choose
-        // method
-        PostMethod method = new PostMethod(uri);
-        method.setRequestEntity(requestEntity);
         return method;
     }
 
     protected RequestEntity createRequestEntity(Exchange exchange) {
         Message in = exchange.getIn();
+        if (in.getBody() == null) {
+            return null;
+        }
         RequestEntity entity = in.getBody(RequestEntity.class);
         if (entity == null) {
-            byte[] data = in.getBody(byte[].class);
-            if (data == null) {
-                return null;
-            }
+
+            String data = in.getBody(String.class);
             String contentType = in.getHeader("Content-Type", String.class);
-            if (contentType != null) {
-                return new ByteArrayRequestEntity(data, contentType);
-            } else {
-                return new ByteArrayRequestEntity(data);
+            try {
+                if (contentType != null) {
+                    return new StringRequestEntity(data, contentType, null);
+                }
+                return new StringRequestEntity(data, null, null);
+            } catch (UnsupportedEncodingException e) {
+                throw new RuntimeException(e);
             }
         }
         return entity;
+    }
+
+    protected boolean shouldHeaderBePropagated(String headerName, String headerValue) {
+        if (headerValue == null) {
+            return false;
+        }
+        if (HTTP_METHOD.equals(headerName)) {
+            return false;
+        }
+        if (headerName.startsWith("org.apache.camel")) {
+            return false;
+        }
+        if (HEADERS_TO_SKIP.contains(headerName.toLowerCase())) {
+            return false;
+        }
+        return true;
     }
 }

Added: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java?rev=651239&view=auto
==============================================================================
--- activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
(added)
+++ activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
Thu Apr 24 05:14:09 2008
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.http.helper;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+
+/**
+ * Subclass of ByteArrayOutputStream that allows creation of a
+ * ByteArrayInputStream directly without creating a copy of the byte[].
+ *
+ * Also, on "toByteArray()" it truncates it's buffer to the current size
+ * and returns the new buffer directly.  Multiple calls to toByteArray()
+ * will return the exact same byte[] unless a write is called in between.
+ *
+ * Note: once the InputStream is created, the output stream should
+ * no longer be used.  In particular, make sure not to call reset()
+ * and then write as that may overwrite the data that the InputStream
+ * is using.
+ */
+public class LoadingByteArrayOutputStream extends ByteArrayOutputStream {
+    public LoadingByteArrayOutputStream() {
+        super(1024);
+    }
+    public LoadingByteArrayOutputStream(int i) {
+        super(i);
+    }
+
+    public ByteArrayInputStream createInputStream() {
+        return new ByteArrayInputStream(buf, 0, count);
+    }
+
+    public byte[] toByteArray() {
+        if (count != buf.length) {
+            buf = super.toByteArray();
+        }
+        return buf;
+    }
+}
\ No newline at end of file

Propchange: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: activemq/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/LoadingByteArrayOutputStream.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Added: activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
URL: http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java?rev=651239&view=auto
==============================================================================
--- activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
(added)
+++ activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
Thu Apr 24 05:14:09 2008
@@ -0,0 +1,68 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.camel.component.http;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+
+import static org.apache.camel.component.http.HttpMethods.HTTP_METHOD;
+import static org.apache.camel.component.http.HttpMethods.POST;
+
+public class HttpPostWithBodyTest extends ContextTestSupport {
+    protected String expectedText = "<html";
+
+    public void testHttpGet() throws Exception {
+        MockEndpoint mockEndpoint = resolveMandatoryEndpoint("mock:results", MockEndpoint.class);
+        mockEndpoint.expectedMinimumMessageCount(1);
+        sendBody("direct:start", "q=test1234");
+        mockEndpoint.assertIsSatisfied();
+        List<Exchange> list = mockEndpoint.getReceivedExchanges();
+        Exchange exchange = list.get(0);
+        assertNotNull("exchange", exchange);
+
+        Message in = exchange.getIn();
+        assertNotNull("in", in);
+
+        Map<String, Object> headers = in.getHeaders();
+
+        log.debug("Headers: " + headers);
+        assertTrue("Should be more than one header but was: " + headers, headers.size() >
0);
+
+        String body = in.getBody(String.class);
+        System.out.println(body);
+        log.debug("Body: " + body);
+        assertNotNull("Should have a body!", body);
+        assertTrue("body should contain: " + expectedText, body.contains(expectedText));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() {
+                from("direct:start").setHeader(HTTP_METHOD, POST).to("http://www.google.com")
+                    .to("mock:results");
+            }
+        };
+    }
+}

Propchange: activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: activemq/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/HttpPostWithBodyTest.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date



Mime
View raw message