You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2011/07/14 18:37:53 UTC
svn commit: r1146782 - in /camel/trunk/components:
camel-ahc/src/test/java/org/apache/camel/component/ahc/
camel-ahc/src/test/resources/
camel-http/src/main/java/org/apache/camel/component/http/
camel-http/src/main/java/org/apache/camel/component/http/...
Author: davsclaus
Date: Thu Jul 14 16:37:50 2011
New Revision: 1146782
URL: http://svn.apache.org/viewvc?rev=1146782&view=rev
Log:
CAMEL-4212: Add support for multi value headers for the http related components.
Added:
camel/trunk/components/camel-ahc/src/test/java/org/apache/camel/component/ahc/AhcProducerTwoParametersWithSameKeyTest.java
camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoHeadersWithSameKeyTest.java
camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoParametersWithSameKeyTest.java
camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProducerTwoParametersWithSameKeyTest.java
Modified:
camel/trunk/components/camel-ahc/src/test/resources/log4j.properties
camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/DefaultHttpBinding.java
camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java
camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpHelper.java
camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/helper/HttpHelperTest.java
camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/DefaultHttpBinding.java
camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java
camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/helper/HttpHelperTest.java
camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/DefaultJettyHttpBinding.java
camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/JettyHttpProducer.java
camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/HttpJettyProducerTwoParametersWithSameKeyTest.java
camel/trunk/components/camel-jetty/src/test/resources/log4j.properties
Added: camel/trunk/components/camel-ahc/src/test/java/org/apache/camel/component/ahc/AhcProducerTwoParametersWithSameKeyTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-ahc/src/test/java/org/apache/camel/component/ahc/AhcProducerTwoParametersWithSameKeyTest.java?rev=1146782&view=auto
==============================================================================
--- camel/trunk/components/camel-ahc/src/test/java/org/apache/camel/component/ahc/AhcProducerTwoParametersWithSameKeyTest.java (added)
+++ camel/trunk/components/camel-ahc/src/test/java/org/apache/camel/component/ahc/AhcProducerTwoParametersWithSameKeyTest.java Thu Jul 14 16:37:50 2011
@@ -0,0 +1,103 @@
+/**
+ * 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.ahc;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class AhcProducerTwoParametersWithSameKeyTest extends BaseAhcTest {
+
+ @Test
+ public void testTwoParametersWithSameKey() throws Exception {
+ Exchange out = template.request("ahc:http://localhost:{{port}}/myapp?from=me&to=foo&to=bar", null);
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Test
+ public void testTwoHeadersWithSameKeyHeader() throws Exception {
+ Exchange out = template.request("ahc:http://localhost:{{port}}/myapp", new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ exchange.getIn().setBody(null);
+ exchange.getIn().setHeader("from", "me");
+ List<String> list = new ArrayList<String>();
+ list.add("foo");
+ list.add("bar");
+ exchange.getIn().setHeader("to", list);
+ }
+ });
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("jetty://http://localhost:{{port}}/myapp").process(new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ String from = exchange.getIn().getHeader("from", String.class);
+ assertEquals("me", from);
+
+ List to = exchange.getIn().getHeader("to", List.class);
+ assertNotNull(to);
+ assertEquals(2, to.size());
+ assertEquals("foo", to.get(0));
+ assertEquals("bar", to.get(1));
+
+ // response
+ exchange.getOut().setBody("OK");
+ // use multiple values for the foo header in the reply
+ List list = new ArrayList();
+ list.add(123);
+ list.add(456);
+ exchange.getOut().setHeader("foo", list);
+ exchange.getOut().setHeader("bar", "yes");
+ }
+ });
+ }
+ };
+ }
+
+}
Modified: camel/trunk/components/camel-ahc/src/test/resources/log4j.properties
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-ahc/src/test/resources/log4j.properties?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-ahc/src/test/resources/log4j.properties (original)
+++ camel/trunk/components/camel-ahc/src/test/resources/log4j.properties Thu Jul 14 16:37:50 2011
@@ -22,6 +22,7 @@ log4j.rootLogger=INFO, file
# uncomment the following to enable camel debugging
#log4j.logger.org.apache.camel.component.ahc=TRACE
+#log4j.logger.com.ning=TRACE
# CONSOLE appender not used by default
log4j.appender.out=org.apache.log4j.ConsoleAppender
Modified: camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/DefaultHttpBinding.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/DefaultHttpBinding.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/DefaultHttpBinding.java (original)
+++ camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/DefaultHttpBinding.java Thu Jul 14 16:37:50 2011
@@ -23,6 +23,7 @@ import java.io.PrintWriter;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.Enumeration;
+import java.util.Iterator;
import java.util.Map;
import javax.activation.DataHandler;
import javax.servlet.ServletOutputStream;
@@ -83,14 +84,16 @@ public class DefaultHttpBinding implemen
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
- Object value = request.getHeader(name);
- // mapping the content-type
+ String value = request.getHeader(name);
+ // use http helper to extract parameter value as it may contain multiple values
+ Object extracted = HttpHelper.extractHttpParameterValue(value);
+ // mapping the content-type
if (name.toLowerCase().equals("content-type")) {
name = Exchange.CONTENT_TYPE;
}
if (headerFilterStrategy != null
- && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
- headers.put(name, value);
+ && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, message.getExchange())) {
+ HttpHelper.appendHeader(headers, name, extracted);
}
}
@@ -143,18 +146,24 @@ public class DefaultHttpBinding implemen
populateAttachments(request, message);
}
-
+
protected void populateRequestParameters(HttpServletRequest request, HttpMessage message) throws Exception {
//we populate the http request parameters without checking the request method
Map<String, Object> headers = message.getHeaders();
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
- Object value = request.getParameter(name);
- LOG.trace("HTTP header {} = {}", name, value);
- if (headerFilterStrategy != null
- && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
- headers.put(name, value);
+ // there may be multiple values for the same name
+ String[] values = request.getParameterValues(name);
+ LOG.trace("HTTP parameter {} = {}", name, values);
+
+ if (values != null) {
+ for (String value : values) {
+ if (headerFilterStrategy != null
+ && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
+ HttpHelper.appendHeader(headers, name, value);
+ }
+ }
}
}
@@ -175,7 +184,7 @@ public class DefaultHttpBinding implemen
String value = URLDecoder.decode(pair[1], charset);
if (headerFilterStrategy != null
&& !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
- headers.put(name, value);
+ HttpHelper.appendHeader(headers, name, value);
}
} else {
throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param);
@@ -263,9 +272,14 @@ public class DefaultHttpBinding implemen
for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
- if (value != null && headerFilterStrategy != null
- && !headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
- response.setHeader(key, value.toString());
+ // use an iterator as there can be multiple values. (must not use a delimiter)
+ final Iterator it = ObjectHelper.createIterator(value, null);
+ while (it.hasNext()) {
+ String headerValue = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
+ if (headerValue != null && headerFilterStrategy != null
+ && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
+ response.addHeader(key, headerValue);
+ }
}
}
Modified: camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java (original)
+++ camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/HttpProducer.java Thu Jul 14 16:37:50 2011
@@ -22,7 +22,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import org.apache.camel.CamelExchangeException;
@@ -37,6 +40,9 @@ import org.apache.camel.spi.HeaderFilter
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.GZIPHelper;
import org.apache.camel.util.IOHelper;
+import org.apache.camel.util.MessageHelper;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.URISupport;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
@@ -68,8 +74,16 @@ public class HttpProducer extends Defaul
}
public void process(Exchange exchange) throws Exception {
+ // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
+ // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
+ Map<String, Object> skipRequestHeaders = null;
+
if (getEndpoint().isBridgeEndpoint()) {
exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
+ String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
+ if (queryString != null) {
+ skipRequestHeaders = URISupport.parseQuery(queryString);
+ }
}
HttpMethod method = createMethod(exchange);
Message in = exchange.getIn();
@@ -84,9 +98,41 @@ public class HttpProducer extends Defaul
// propagate headers as HTTP headers
for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
- String headerValue = in.getHeader(entry.getKey(), String.class);
- if (strategy != null && !strategy.applyFilterToCamelHeaders(entry.getKey(), headerValue, exchange)) {
- method.addRequestHeader(entry.getKey(), headerValue);
+ String key = entry.getKey();
+ Object headerValue = in.getHeader(key);
+
+ if (headerValue != null) {
+ // use an iterator as there can be multiple values. (must not use a delimiter)
+ final Iterator it = ObjectHelper.createIterator(headerValue, null);
+
+ // the value to add as request header
+ final List<String> values = new ArrayList<String>();
+
+ // if its a multi value then check each value if we can add it and for multi values they
+ // should be combined into a single value
+ while (it.hasNext()) {
+ String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
+
+ // we should not add headers for the parameters in the uri if we bridge the endpoint
+ // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
+ if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
+ Object skipValue = skipRequestHeaders.get(key);
+ if (ObjectHelper.equal(skipValue, value)) {
+ continue;
+ }
+ }
+ if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
+ values.add(value);
+ }
+ }
+
+ // add the value(s) as a http request header
+ if (values.size() > 0) {
+ // use the default toString of a ArrayList to create in the form [xxx, yyy]
+ // if multi valued, for a single value, then just output the value as is
+ String s = values.size() > 1 ? values.toString() : values.get(0);
+ method.addRequestHeader(key, s);
+ }
}
}
@@ -125,7 +171,6 @@ public class HttpProducer extends Defaul
Object response = extractResponseBody(method, exchange);
Message answer = exchange.getOut();
- answer.setHeaders(in.getHeaders());
answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
answer.setBody(response);
@@ -137,10 +182,16 @@ public class HttpProducer extends Defaul
if (name.toLowerCase().equals("content-type")) {
name = Exchange.CONTENT_TYPE;
}
- if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
- answer.setHeader(name, value);
+ // use http helper to extract parameter value as it may contain multiple values
+ Object extracted = HttpHelper.extractHttpParameterValue(value);
+ if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
+ HttpHelper.appendHeader(answer.getHeaders(), name, extracted);
}
}
+
+ // preserve headers from in by copying any non existing headers
+ // to avoid overriding existing headers with old values
+ MessageHelper.copyHeaders(exchange.getIn(), answer, false);
}
protected Exception populateHttpOperationFailedException(Exchange exchange, HttpMethod method, int responseCode) throws IOException, ClassNotFoundException {
Modified: camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpHelper.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpHelper.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpHelper.java (original)
+++ camel/trunk/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpHelper.java Thu Jul 14 16:37:50 2011
@@ -22,6 +22,9 @@ import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@@ -34,6 +37,7 @@ import org.apache.camel.component.http.H
import org.apache.camel.converter.IOConverter;
import org.apache.camel.converter.stream.CachedOutputStream;
import org.apache.camel.util.IOHelper;
+import org.apache.camel.util.ObjectHelper;
public final class HttpHelper {
@@ -234,4 +238,68 @@ public final class HttpHelper {
return answer;
}
+
+ /**
+ * Appends the key/value to the headers.
+ * <p/>
+ * This implementation supports keys with multiple values. In such situations the value
+ * will be a {@link java.util.List} that contains the multiple values.
+ *
+ * @param headers headers
+ * @param key the key
+ * @param value the value
+ */
+ @SuppressWarnings("unchecked")
+ public static void appendHeader(Map headers, String key, Object value) {
+ if (headers.containsKey(key)) {
+ Object existing = headers.get(key);
+ List list;
+ if (existing instanceof List) {
+ list = (List) existing;
+ } else {
+ list = new ArrayList();
+ list.add(existing);
+ }
+ list.add(value);
+ value = list;
+ }
+
+ headers.put(key, value);
+ }
+
+ /**
+ * Extracts the parameter value.
+ * <p/>
+ * This implementation supports HTTP multi value parameters which
+ * is based on the syntax of <tt>[value1, value2, value3]</tt> by returning
+ * a {@link List} containing the values.
+ * <p/>
+ * If the value is not a HTTP mulit value the value is returned as is.
+ *
+ * @param value the parameter value
+ * @return the extracted parameter value, see more details in javadoc.
+ */
+ @SuppressWarnings("unchecked")
+ public static Object extractHttpParameterValue(String value) {
+ if (value == null || ObjectHelper.isEmpty(value)) {
+ return value;
+ }
+
+ // trim value before checking for multiple parameters
+ String trimmed = value.trim();
+
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
+ // remove the [ ] markers
+ trimmed = trimmed.substring(1, trimmed.length() - 1);
+ List list = new ArrayList<String>();
+ String[] values = trimmed.split(",");
+ for (String s : values) {
+ list.add(s.trim());
+ }
+ return list;
+ }
+
+ return value;
+ }
+
}
Modified: camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/helper/HttpHelperTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/helper/HttpHelperTest.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/helper/HttpHelperTest.java (original)
+++ camel/trunk/components/camel-http/src/test/java/org/apache/camel/component/http/helper/HttpHelperTest.java Thu Jul 14 16:37:50 2011
@@ -18,6 +18,9 @@ package org.apache.camel.component.http.
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
@@ -29,10 +32,41 @@ import org.apache.camel.impl.DefaultExch
import org.junit.Test;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
public class HttpHelperTest {
@Test
+ public void testAppendHeader() throws Exception {
+ Map headers = new HashMap();
+ HttpHelper.appendHeader(headers, "foo", "a");
+ HttpHelper.appendHeader(headers, "bar", "b");
+ HttpHelper.appendHeader(headers, "baz", "c");
+
+ assertEquals(3, headers.size());
+ assertEquals("a", headers.get("foo"));
+ assertEquals("b", headers.get("bar"));
+ assertEquals("c", headers.get("baz"));
+ }
+
+ @Test
+ public void testAppendHeaderMultipleValues() throws Exception {
+ Map headers = new HashMap();
+ HttpHelper.appendHeader(headers, "foo", "a");
+ HttpHelper.appendHeader(headers, "bar", "b");
+ HttpHelper.appendHeader(headers, "bar", "c");
+
+ assertEquals(2, headers.size());
+ assertEquals("a", headers.get("foo"));
+
+ List list = (List) headers.get("bar");
+ assertNotNull(list);
+ assertEquals(2, list.size());
+ assertEquals("b", list.get(0));
+ assertEquals("c", list.get(1));
+ }
+
+ @Test
public void createURLShouldReturnTheHeaderURIIfNotBridgeEndpoint() throws URISyntaxException {
String url = HttpHelper.createURL(
createExchangeWithOptionalCamelHttpUriHeader("http://apache.org", null),
Modified: camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/DefaultHttpBinding.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/DefaultHttpBinding.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/DefaultHttpBinding.java (original)
+++ camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/DefaultHttpBinding.java Thu Jul 14 16:37:50 2011
@@ -23,6 +23,7 @@ import java.io.PrintWriter;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.Enumeration;
+import java.util.Iterator;
import java.util.Map;
import javax.activation.DataHandler;
@@ -43,6 +44,8 @@ import org.apache.camel.util.GZIPHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.MessageHelper;
import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Binding between {@link HttpMessage} and {@link HttpServletResponse}.
@@ -51,6 +54,7 @@ import org.apache.camel.util.ObjectHelpe
*/
public class DefaultHttpBinding implements HttpBinding {
+ private static final transient Logger LOG = LoggerFactory.getLogger(DefaultHttpBinding.class);
private boolean useReaderForPayload;
private HeaderFilterStrategy headerFilterStrategy = new HttpHeaderFilterStrategy();
private HttpEndpoint endpoint;
@@ -86,7 +90,7 @@ public class DefaultHttpBinding implemen
}
if (headerFilterStrategy != null
&& !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
- headers.put(name, value);
+ HttpHelper.appendHeader(headers, name, value);
}
}
@@ -137,10 +141,17 @@ public class DefaultHttpBinding implemen
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
- Object value = request.getParameter(name);
- if (headerFilterStrategy != null
- && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
- headers.put(name, value);
+ // there may be multiple values for the same name
+ String[] values = request.getParameterValues(name);
+ LOG.trace("HTTP parameter {} = {}", name, values);
+
+ if (values != null) {
+ for (String value : values) {
+ if (headerFilterStrategy != null
+ && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
+ HttpHelper.appendHeader(headers, name, value);
+ }
+ }
}
}
if (request.getMethod().equals("POST") && request.getContentType() != null
@@ -240,11 +251,18 @@ public class DefaultHttpBinding implemen
}
// append headers
- for (String key : message.getHeaders().keySet()) {
- String value = message.getHeader(key, String.class);
- if (headerFilterStrategy != null
- && !headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
- response.setHeader(key, value);
+ // must use entrySet to ensure case of keys is preserved
+ for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ // use an iterator as there can be multiple values. (must not use a delimiter)
+ final Iterator it = ObjectHelper.createIterator(value, null);
+ while (it.hasNext()) {
+ String headerValue = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
+ if (headerValue != null && headerFilterStrategy != null
+ && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
+ response.addHeader(key, headerValue);
+ }
}
}
Modified: camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java (original)
+++ camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpProducer.java Thu Jul 14 16:37:50 2011
@@ -24,7 +24,10 @@ import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import org.apache.camel.CamelExchangeException;
@@ -39,6 +42,9 @@ import org.apache.camel.spi.HeaderFilter
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.GZIPHelper;
import org.apache.camel.util.IOHelper;
+import org.apache.camel.util.MessageHelper;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.URISupport;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
@@ -72,8 +78,16 @@ public class HttpProducer extends Defaul
}
public void process(Exchange exchange) throws Exception {
+ // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
+ // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
+ Map<String, Object> skipRequestHeaders = null;
+
if (getEndpoint().isBridgeEndpoint()) {
exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
+ String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
+ if (queryString != null) {
+ skipRequestHeaders = URISupport.parseQuery(queryString);
+ }
}
HttpRequestBase httpRequest = createMethod(exchange);
Message in = exchange.getIn();
@@ -86,9 +100,41 @@ public class HttpProducer extends Defaul
// propagate headers as HTTP headers
for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
- String headerValue = in.getHeader(entry.getKey(), String.class);
- if (strategy != null && !strategy.applyFilterToCamelHeaders(entry.getKey(), headerValue, exchange)) {
- httpRequest.addHeader(entry.getKey(), headerValue);
+ String key = entry.getKey();
+ Object headerValue = in.getHeader(key);
+
+ if (headerValue != null) {
+ // use an iterator as there can be multiple values. (must not use a delimiter)
+ final Iterator it = ObjectHelper.createIterator(headerValue, null);
+
+ // the value to add as request header
+ final List<String> values = new ArrayList<String>();
+
+ // if its a multi value then check each value if we can add it and for multi values they
+ // should be combined into a single value
+ while (it.hasNext()) {
+ String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
+
+ // we should not add headers for the parameters in the uri if we bridge the endpoint
+ // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
+ if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
+ Object skipValue = skipRequestHeaders.get(key);
+ if (ObjectHelper.equal(skipValue, value)) {
+ continue;
+ }
+ }
+ if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
+ values.add(value);
+ }
+ }
+
+ // add the value(s) as a http request header
+ if (values.size() > 0) {
+ // use the default toString of a ArrayList to create in the form [xxx, yyy]
+ // if multi valued, for a single value, then just output the value as is
+ String s = values.size() > 1 ? values.toString() : values.get(0);
+ httpRequest.addHeader(key, s);
+ }
}
}
@@ -129,7 +175,6 @@ public class HttpProducer extends Defaul
Object response = extractResponseBody(httpRequest, httpResponse, exchange);
Message answer = exchange.getOut();
- answer.setHeaders(in.getHeaders());
answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
answer.setBody(response);
@@ -141,10 +186,16 @@ public class HttpProducer extends Defaul
if (name.toLowerCase().equals("content-type")) {
name = Exchange.CONTENT_TYPE;
}
- if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
- answer.setHeader(name, value);
+ // use http helper to extract parameter value as it may contain multiple values
+ Object extracted = HttpHelper.extractHttpParameterValue(value);
+ if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
+ HttpHelper.appendHeader(answer.getHeaders(), name, extracted);
}
}
+
+ // preserve headers from in by copying any non existing headers
+ // to avoid overriding existing headers with old values
+ MessageHelper.copyHeaders(exchange.getIn(), answer, false);
}
protected Exception populateHttpOperationFailedException(Exchange exchange, HttpRequestBase httpRequest, HttpResponse httpResponse, int responseCode) throws IOException, ClassNotFoundException {
Modified: camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java (original)
+++ camel/trunk/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java Thu Jul 14 16:37:50 2011
@@ -22,6 +22,9 @@ import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
@@ -34,6 +37,7 @@ import org.apache.camel.component.http4.
import org.apache.camel.converter.IOConverter;
import org.apache.camel.converter.stream.CachedOutputStream;
import org.apache.camel.util.IOHelper;
+import org.apache.camel.util.ObjectHelper;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolException;
@@ -271,4 +275,67 @@ public final class HttpHelper {
return uri.startsWith("https");
}
+ /**
+ * Appends the key/value to the headers.
+ * <p/>
+ * This implementation supports keys with multiple values. In such situations the value
+ * will be a {@link java.util.List} that contains the multiple values.
+ *
+ * @param headers headers
+ * @param key the key
+ * @param value the value
+ */
+ @SuppressWarnings("unchecked")
+ public static void appendHeader(Map headers, String key, Object value) {
+ if (headers.containsKey(key)) {
+ Object existing = headers.get(key);
+ List list;
+ if (existing instanceof List) {
+ list = (List) existing;
+ } else {
+ list = new ArrayList();
+ list.add(existing);
+ }
+ list.add(value);
+ value = list;
+ }
+
+ headers.put(key, value);
+ }
+
+ /**
+ * Extracts the parameter value.
+ * <p/>
+ * This implementation supports HTTP multi value parameters which
+ * is based on the syntax of <tt>[value1, value2, value3]</tt> by returning
+ * a {@link List} containing the values.
+ * <p/>
+ * If the value is not a HTTP mulit value the value is returned as is.
+ *
+ * @param value the parameter value
+ * @return the extracted parameter value, see more details in javadoc.
+ */
+ @SuppressWarnings("unchecked")
+ public static Object extractHttpParameterValue(String value) {
+ if (value == null || ObjectHelper.isEmpty(value)) {
+ return value;
+ }
+
+ // trim value before checking for multiple parameters
+ String trimmed = value.trim();
+
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
+ // remove the [ ] markers
+ trimmed = trimmed.substring(1, trimmed.length() - 1);
+ List list = new ArrayList<String>();
+ String[] values = trimmed.split(",");
+ for (String s : values) {
+ list.add(s.trim());
+ }
+ return list;
+ }
+
+ return value;
+ }
+
}
Added: camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoHeadersWithSameKeyTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoHeadersWithSameKeyTest.java?rev=1146782&view=auto
==============================================================================
--- camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoHeadersWithSameKeyTest.java (added)
+++ camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoHeadersWithSameKeyTest.java Thu Jul 14 16:37:50 2011
@@ -0,0 +1,86 @@
+/**
+ * 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.http4;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.http.Header;
+import org.apache.http.HttpException;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.localserver.LocalTestServer;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpRequestHandler;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class HttpProducerTwoHeadersWithSameKeyTest extends BaseHttpTest {
+
+ @Test
+ public void testTwoHeadersWithSameKeyHeader() throws Exception {
+ Exchange out = template.request("http4://" + getHostName() + ":" + getPort() + "/myapp", new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ exchange.getIn().setBody(null);
+ exchange.getIn().setHeader("from", "me");
+ List<String> list = new ArrayList<String>();
+ list.add("foo");
+ list.add("bar");
+ exchange.getIn().setHeader("to", list);
+ }
+ });
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Override
+ protected void registerHandler(LocalTestServer server) {
+ server.register("/myapp", new HttpRequestHandler() {
+ @Override
+ public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
+ Header[] from = request.getHeaders("from");
+ assertEquals("me", from[0].getValue());
+ Header[] to = request.getHeaders("to");
+ assertEquals("[foo, bar]", to[0].getValue());
+
+ response.setHeader("bar", "yes");
+ response.addHeader("foo", "123");
+ response.addHeader("foo", "456");
+ response.setEntity(new StringEntity("OK", HTTP.ASCII));
+ response.setStatusCode(HttpStatus.SC_OK);
+ }
+ });
+ }
+
+}
Added: camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoParametersWithSameKeyTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoParametersWithSameKeyTest.java?rev=1146782&view=auto
==============================================================================
--- camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoParametersWithSameKeyTest.java (added)
+++ camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpProducerTwoParametersWithSameKeyTest.java Thu Jul 14 16:37:50 2011
@@ -0,0 +1,75 @@
+/**
+ * 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.http4;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.http.Header;
+import org.apache.http.HttpException;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.localserver.LocalTestServer;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpRequestHandler;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class HttpProducerTwoParametersWithSameKeyTest extends BaseHttpTest {
+
+ @Test
+ public void testTwoParametersWithSameKey() throws Exception {
+ Exchange out = template.request("http4://" + getHostName() + ":" + getPort() + "/myapp?from=me&to=foo&to=bar", null);
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Override
+ protected void registerHandler(LocalTestServer server) {
+ server.register("/myapp", new HttpRequestHandler() {
+ @Override
+ public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
+ String uri = request.getRequestLine().getUri();
+ assertEquals("/myapp?from=me&to=foo&to=bar", uri);
+
+ response.setHeader("bar", "yes");
+ response.addHeader("foo", "123");
+ response.addHeader("foo", "456");
+ response.setEntity(new StringEntity("OK", HTTP.ASCII));
+ response.setStatusCode(HttpStatus.SC_OK);
+ }
+ });
+ }
+
+}
Modified: camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/helper/HttpHelperTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/helper/HttpHelperTest.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/helper/HttpHelperTest.java (original)
+++ camel/trunk/components/camel-http4/src/test/java/org/apache/camel/component/http4/helper/HttpHelperTest.java Thu Jul 14 16:37:50 2011
@@ -18,6 +18,9 @@ package org.apache.camel.component.http4
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
@@ -29,10 +32,41 @@ import org.apache.camel.impl.DefaultExch
import org.junit.Test;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
public class HttpHelperTest {
@Test
+ public void testAppendHeader() throws Exception {
+ Map headers = new HashMap();
+ HttpHelper.appendHeader(headers, "foo", "a");
+ HttpHelper.appendHeader(headers, "bar", "b");
+ HttpHelper.appendHeader(headers, "baz", "c");
+
+ assertEquals(3, headers.size());
+ assertEquals("a", headers.get("foo"));
+ assertEquals("b", headers.get("bar"));
+ assertEquals("c", headers.get("baz"));
+ }
+
+ @Test
+ public void testAppendHeaderMultipleValues() throws Exception {
+ Map headers = new HashMap();
+ HttpHelper.appendHeader(headers, "foo", "a");
+ HttpHelper.appendHeader(headers, "bar", "b");
+ HttpHelper.appendHeader(headers, "bar", "c");
+
+ assertEquals(2, headers.size());
+ assertEquals("a", headers.get("foo"));
+
+ List list = (List) headers.get("bar");
+ assertNotNull(list);
+ assertEquals(2, list.size());
+ assertEquals("b", list.get(0));
+ assertEquals("c", list.get(1));
+ }
+
+ @Test
public void createURLShouldReturnTheHeaderURIIfNotBridgeEndpoint() throws URISyntaxException {
String url = HttpHelper.createURL(
createExchangeWithOptionalCamelHttpUriHeader("http://apache.org", null),
Modified: camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/DefaultJettyHttpBinding.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/DefaultJettyHttpBinding.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/DefaultJettyHttpBinding.java (original)
+++ camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/DefaultJettyHttpBinding.java Thu Jul 14 16:37:50 2011
@@ -18,6 +18,7 @@ package org.apache.camel.component.jetty
import java.io.IOException;
import java.io.InputStream;
+import java.util.Enumeration;
import java.util.Map;
import org.apache.camel.Exchange;
@@ -28,6 +29,7 @@ import org.apache.camel.component.http.H
import org.apache.camel.component.http.HttpOperationFailedException;
import org.apache.camel.component.http.helper.HttpHelper;
import org.apache.camel.spi.HeaderFilterStrategy;
+import org.apache.camel.util.MessageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -89,22 +91,30 @@ public class DefaultJettyHttpBinding imp
Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException {
Message answer = exchange.getOut();
- answer.setHeaders(in.getHeaders());
answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
- // propagate HTTP response headers
- // must use entrySet to ensure case of keys is preserved
- for (Map.Entry<String, String> entry : httpExchange.getHeaders().entrySet()) {
- String name = entry.getKey();
- String value = entry.getValue();
- if (name.toLowerCase().equals("content-type")) {
- name = Exchange.CONTENT_TYPE;
- }
- if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
- answer.setHeader(name, value);
+ // must use response fields to get the http headers as
+ // httpExchange.getHeaders() does not work well with multi valued headers
+ Enumeration<String> names = httpExchange.getResponseFields().getFieldNames();
+ while (names.hasMoreElements()) {
+ String name = names.nextElement();
+ Enumeration<String> values = httpExchange.getResponseFields().getValues(name);
+ while (values.hasMoreElements()) {
+ String value = values.nextElement();
+
+ if (name.toLowerCase().equals("content-type")) {
+ name = Exchange.CONTENT_TYPE;
+ }
+ if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
+ HttpHelper.appendHeader(answer.getHeaders(), name, value);
+ }
}
}
+ // preserve headers from in by copying any non existing headers
+ // to avoid overriding existing headers with old values
+ MessageHelper.copyHeaders(exchange.getIn(), answer, false);
+
// extract body after headers has been set as we want to ensure content-type from Jetty HttpExchange
// has been populated first
answer.setBody(extractResponseBody(exchange, httpExchange));
Modified: camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/JettyHttpProducer.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/JettyHttpProducer.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/JettyHttpProducer.java (original)
+++ camel/trunk/components/camel-jetty/src/main/java/org/apache/camel/component/jetty/JettyHttpProducer.java Thu Jul 14 16:37:50 2011
@@ -22,6 +22,9 @@ import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import org.apache.camel.AsyncCallback;
@@ -55,6 +58,7 @@ public class JettyHttpProducer extends D
public JettyHttpProducer(Endpoint endpoint, HttpClient client) {
super(endpoint);
this.client = client;
+ ObjectHelper.notNull(client, "HttpClient", this);
}
@Override
@@ -68,9 +72,6 @@ public class JettyHttpProducer extends D
public boolean process(Exchange exchange, final AsyncCallback callback) {
try {
- // TODO - Why does this use the endpoint client and not the one we were handed during construction?
- HttpClient client = getEndpoint().getClient();
-
JettyContentExchange httpExchange = createHttpExchange(exchange, callback);
doSendExchange(client, httpExchange);
} catch (Exception e) {
@@ -131,15 +132,56 @@ public class JettyHttpProducer extends D
}
}
- // and copy headers from IN message
+ // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
+ // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
+ Map<String, Object> skipRequestHeaders = null;
+ if (getEndpoint().isBridgeEndpoint()) {
+ exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
+ String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
+ if (queryString != null) {
+ skipRequestHeaders = URISupport.parseQuery(queryString);
+ }
+ }
+
+ // propagate headers as HTTP headers
Message in = exchange.getIn();
HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
+ for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
+ String key = entry.getKey();
+ Object headerValue = in.getHeader(key);
+
+ if (headerValue != null) {
+ // use an iterator as there can be multiple values. (must not use a delimiter)
+ final Iterator it = ObjectHelper.createIterator(headerValue, null);
+
+ // the values to add as a request header
+ final List<String> values = new ArrayList<String>();
+
+ // if its a multi value then check each value if we can add it and for multi values they
+ // should be combined into a single value
+ while (it.hasNext()) {
+ String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
+
+ // we should not add headers for the parameters in the uri if we bridge the endpoint
+ // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
+ if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
+ Object skipValue = skipRequestHeaders.get(key);
+ if (ObjectHelper.equal(skipValue, value)) {
+ continue;
+ }
+ }
+ if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
+ values.add(value);
+ }
+ }
- // propagate headers as HTTP headers
- for (String headerName : in.getHeaders().keySet()) {
- String headerValue = in.getHeader(headerName, String.class);
- if (strategy != null && !strategy.applyFilterToCamelHeaders(headerName, headerValue, exchange)) {
- httpExchange.addRequestHeader(headerName, headerValue);
+ // add the value(s) as a http request header
+ if (values.size() > 0) {
+ // use the default toString of a ArrayList to create in the form [xxx, yyy]
+ // if multi valued, for a single value, then just output the value as is
+ String s = values.size() > 1 ? values.toString() : values.get(0);
+ httpExchange.addRequestHeader(key, s);
+ }
}
}
Added: camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProducerTwoParametersWithSameKeyTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProducerTwoParametersWithSameKeyTest.java?rev=1146782&view=auto
==============================================================================
--- camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProducerTwoParametersWithSameKeyTest.java (added)
+++ camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpProducerTwoParametersWithSameKeyTest.java Thu Jul 14 16:37:50 2011
@@ -0,0 +1,103 @@
+/**
+ * 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.jetty;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class HttpProducerTwoParametersWithSameKeyTest extends BaseJettyTest {
+
+ @Test
+ public void testTwoParametersWithSameKey() throws Exception {
+ Exchange out = template.request("http://localhost:{{port}}/myapp?from=me&to=foo&to=bar", null);
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Test
+ public void testTwoHeadersWithSameKeyHeader() throws Exception {
+ Exchange out = template.request("http://localhost:{{port}}/myapp", new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ exchange.getIn().setBody(null);
+ exchange.getIn().setHeader("from", "me");
+ List<String> list = new ArrayList<String>();
+ list.add("foo");
+ list.add("bar");
+ exchange.getIn().setHeader("to", list);
+ }
+ });
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("jetty://http://localhost:{{port}}/myapp").process(new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ String from = exchange.getIn().getHeader("from", String.class);
+ assertEquals("me", from);
+
+ List to = exchange.getIn().getHeader("to", List.class);
+ assertNotNull(to);
+ assertEquals(2, to.size());
+ assertEquals("foo", to.get(0));
+ assertEquals("bar", to.get(1));
+
+ // response
+ exchange.getOut().setBody("OK");
+ // use multiple values for the foo header in the reply
+ List list = new ArrayList();
+ list.add(123);
+ list.add(456);
+ exchange.getOut().setHeader("foo", list);
+ exchange.getOut().setHeader("bar", "yes");
+ }
+ });
+ }
+ };
+ }
+
+}
Modified: camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/HttpJettyProducerTwoParametersWithSameKeyTest.java
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/HttpJettyProducerTwoParametersWithSameKeyTest.java?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/HttpJettyProducerTwoParametersWithSameKeyTest.java (original)
+++ camel/trunk/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/HttpJettyProducerTwoParametersWithSameKeyTest.java Thu Jul 14 16:37:50 2011
@@ -16,12 +16,12 @@
*/
package org.apache.camel.component.jetty.jettyproducer;
-import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.http.HttpMessage;
import org.apache.camel.component.jetty.BaseJettyTest;
import org.junit.Test;
@@ -40,8 +40,50 @@ public class HttpJettyProducerTwoParamet
// give Jetty time to startup properly
Thread.sleep(1000);
- Exchange a = template.request("jetty:http://localhost:{{port}}/myapp?from=me&to=foo&to=bar", null);
- assertNotNull(a);
+ Exchange out = template.request("jetty:http://localhost:{{port}}/myapp?from=me&to=foo&to=bar", null);
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
+ }
+
+ @Test
+ public void testTwoHeadersWithSameKeyHeader() throws Exception {
+ // these tests does not run well on Windows
+ if (isPlatform("windows")) {
+ return;
+ }
+
+ // give Jetty time to startup properly
+ Thread.sleep(1000);
+
+ Exchange out = template.request("jetty:http://localhost:{{port}}/myapp", new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ exchange.getIn().setBody(null);
+ exchange.getIn().setHeader("from", "me");
+ List<String> list = new ArrayList<String>();
+ list.add("foo");
+ list.add("bar");
+ exchange.getIn().setHeader("to", list);
+ }
+ });
+
+ assertNotNull(out);
+ assertFalse("Should not fail", out.isFailed());
+ assertEquals("OK", out.getOut().getBody(String.class));
+ assertEquals("yes", out.getOut().getHeader("bar"));
+
+ List foo = out.getOut().getHeader("foo", List.class);
+ assertNotNull(foo);
+ assertEquals(2, foo.size());
+ assertEquals("123", foo.get(0));
+ assertEquals("456", foo.get(1));
}
@Override
@@ -54,16 +96,20 @@ public class HttpJettyProducerTwoParamet
String from = exchange.getIn().getHeader("from", String.class);
assertEquals("me", from);
- HttpServletRequest req = exchange.getIn(HttpMessage.class).getRequest();
-
- // TODO: Http/Jetty should support headers with multiple values
- String[] values = req.getParameterValues("to");
+ List values = exchange.getIn().getHeader("to", List.class);
assertNotNull(values);
- assertEquals(2, values.length);
- assertEquals("foo", values[0]);
- assertEquals("bar", values[1]);
+ assertEquals(2, values.size());
+ assertEquals("foo", values.get(0));
+ assertEquals("bar", values.get(1));
+ // response
exchange.getOut().setBody("OK");
+ // use multiple values for the foo header in the reply
+ List list = new ArrayList();
+ list.add(123);
+ list.add(456);
+ exchange.getOut().setHeader("foo", list);
+ exchange.getOut().setHeader("bar", "yes");
}
});
}
Modified: camel/trunk/components/camel-jetty/src/test/resources/log4j.properties
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-jetty/src/test/resources/log4j.properties?rev=1146782&r1=1146781&r2=1146782&view=diff
==============================================================================
--- camel/trunk/components/camel-jetty/src/test/resources/log4j.properties (original)
+++ camel/trunk/components/camel-jetty/src/test/resources/log4j.properties Thu Jul 14 16:37:50 2011
@@ -31,6 +31,8 @@ log4j.rootLogger=INFO, file
#log4j.logger.org.apache.camel=DEBUG
#log4j.logger.org.apache.camel.impl.converter.PropertyEditorTypeConverter=TRACE
+#log4j.logger.org.eclipse.jetty=TRACE
+
# CONSOLE appender not used by default
log4j.appender.out=org.apache.log4j.ConsoleAppender
log4j.appender.out.layout=org.apache.log4j.PatternLayout