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 2014/12/09 19:39:34 UTC

[2/2] camel git commit: CAMEL-8316: camel-jaxb add option mustBeJAXBElement to relax marshaller to marshal non JAXB classes and fallback to marshal as plain streams, such as when the content is already in XML format.

CAMEL-8316: camel-jaxb add option mustBeJAXBElement to relax marshaller to marshal non JAXB classes and fallback to marshal as plain streams, such as when the content is already in XML format.


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/f97cd5ca
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/f97cd5ca
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/f97cd5ca

Branch: refs/heads/camel-2.14.x
Commit: f97cd5cafa4b36debee78f6f643e135aa417c9d6
Parents: 6f99beb
Author: Claus Ibsen <da...@apache.org>
Authored: Tue Dec 9 19:39:04 2014 +0100
Committer: Claus Ibsen <da...@apache.org>
Committed: Tue Dec 9 19:39:22 2014 +0100

----------------------------------------------------------------------
 .../camel/model/dataformat/JaxbDataFormat.java  | 18 +++-
 .../camel/converter/jaxb/JaxbDataFormat.java    | 59 +++++++++----
 .../JaxbDataFormatMustBeJAXBElementTest.java    | 93 ++++++++++++++++++++
 3 files changed, 150 insertions(+), 20 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/f97cd5ca/camel-core/src/main/java/org/apache/camel/model/dataformat/JaxbDataFormat.java
----------------------------------------------------------------------
diff --git a/camel-core/src/main/java/org/apache/camel/model/dataformat/JaxbDataFormat.java b/camel-core/src/main/java/org/apache/camel/model/dataformat/JaxbDataFormat.java
index 716f9c6..ead4977 100644
--- a/camel-core/src/main/java/org/apache/camel/model/dataformat/JaxbDataFormat.java
+++ b/camel-core/src/main/java/org/apache/camel/model/dataformat/JaxbDataFormat.java
@@ -44,6 +44,8 @@ public class JaxbDataFormat extends DataFormatDefinition {
     @XmlAttribute
     private Boolean ignoreJAXBElement;
     @XmlAttribute
+    private Boolean mustBeJAXBElement;
+    @XmlAttribute
     private Boolean filterNonXmlChars;
     @XmlAttribute
     private String encoding;
@@ -101,7 +103,15 @@ public class JaxbDataFormat extends DataFormatDefinition {
     public void setIgnoreJAXBElement(Boolean ignoreJAXBElement) {
         this.ignoreJAXBElement = ignoreJAXBElement;
     }
-    
+
+    public Boolean getMustBeJAXBElement() {
+        return mustBeJAXBElement;
+    }
+
+    public void setMustBeJAXBElement(Boolean mustBeJAXBElement) {
+        this.mustBeJAXBElement = mustBeJAXBElement;
+    }
+
     public void setFragment(Boolean fragment) {
         this.fragment = fragment;
     }
@@ -180,6 +190,12 @@ public class JaxbDataFormat extends DataFormatDefinition {
         } else { // the default value is true
             setProperty(camelContext, dataFormat, "ignoreJAXBElement", Boolean.TRUE);
         }
+        answer = ObjectHelper.toBoolean(getMustBeJAXBElement());
+        if (answer != null && answer) {
+            setProperty(camelContext, dataFormat, "mustBeJAXBElement", Boolean.TRUE);
+        } else { // the default value is false
+            setProperty(camelContext, dataFormat, "mustBeJAXBElement", Boolean.FALSE);
+        }
         answer = ObjectHelper.toBoolean(getFilterNonXmlChars());
         if (answer != null && answer) {
             setProperty(camelContext, dataFormat, "filterNonXmlChars", Boolean.TRUE);

http://git-wip-us.apache.org/repos/asf/camel/blob/f97cd5ca/components/camel-jaxb/src/main/java/org/apache/camel/converter/jaxb/JaxbDataFormat.java
----------------------------------------------------------------------
diff --git a/components/camel-jaxb/src/main/java/org/apache/camel/converter/jaxb/JaxbDataFormat.java b/components/camel-jaxb/src/main/java/org/apache/camel/converter/jaxb/JaxbDataFormat.java
index ae33062..7e1281a 100644
--- a/components/camel-jaxb/src/main/java/org/apache/camel/converter/jaxb/JaxbDataFormat.java
+++ b/components/camel-jaxb/src/main/java/org/apache/camel/converter/jaxb/JaxbDataFormat.java
@@ -27,11 +27,11 @@ import java.net.URL;
 import java.util.Map;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
-
 import javax.xml.XMLConstants;
 import javax.xml.bind.JAXBContext;
 import javax.xml.bind.JAXBElement;
 import javax.xml.bind.JAXBException;
+import javax.xml.bind.JAXBIntrospector;
 import javax.xml.bind.Marshaller;
 import javax.xml.bind.Unmarshaller;
 import javax.xml.bind.ValidationEvent;
@@ -45,11 +45,11 @@ import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.Schema;
 import javax.xml.validation.SchemaFactory;
 
-import org.xml.sax.SAXException;
-
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
 import org.apache.camel.Exchange;
+import org.apache.camel.InvalidPayloadException;
+import org.apache.camel.NoTypeConversionAvailableException;
 import org.apache.camel.TypeConverter;
 import org.apache.camel.spi.DataFormat;
 import org.apache.camel.support.ServiceSupport;
@@ -59,6 +59,7 @@ import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.ResourceHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.xml.sax.SAXException;
 
 
 /**
@@ -75,12 +76,14 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
     private SchemaFactory schemaFactory;
     private CamelContext camelContext;
     private JAXBContext context;
+    private JAXBIntrospector introspector;
     private String contextPath;
     private String schema;
     private String schemaLocation;
    
     private boolean prettyPrint = true;
     private boolean ignoreJAXBElement = true;
+    private boolean mustBeJAXBElement;
     private boolean filterNonXmlChars;
     private String encoding;
     private boolean fragment;
@@ -107,7 +110,7 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
     }
 
     public void marshal(Exchange exchange, Object graph, OutputStream stream) throws IOException, SAXException {
-        try {            
+        try {
             // must create a new instance of marshaller as its not thread safe
             Marshaller marshaller = createMarshaller();
             
@@ -134,32 +137,42 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
 
             marshal(exchange, graph, stream, marshaller);
 
-        } catch (JAXBException e) {
-            throw new IOException(e);
-        } catch (XMLStreamException e) {
+        } catch (Exception e) {
             throw new IOException(e);
         }
     }
 
     void marshal(Exchange exchange, Object graph, OutputStream stream, Marshaller marshaller)
-        throws XMLStreamException, JAXBException {
+            throws XMLStreamException, JAXBException, NoTypeConversionAvailableException, IOException, InvalidPayloadException {
 
         Object e = graph;
         if (partialClass != null && getPartNamespace() != null) {
             e = new JAXBElement<Object>(getPartNamespace(), partialClass, graph);
         }
 
-        if (asXmlStreamWriter(exchange)) {
-            XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, stream);
-            if (needFiltering(exchange)) {
-                writer = new FilteringXmlStreamWriter(writer);
+        // only marshal if its possible
+        if (introspector.isElement(e)) {
+            if (asXmlStreamWriter(exchange)) {
+                XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, stream);
+                if (needFiltering(exchange)) {
+                    writer = new FilteringXmlStreamWriter(writer);
+                }
+                if (xmlStreamWriterWrapper != null) {
+                    writer = xmlStreamWriterWrapper.wrapWriter(writer);
+                }
+                marshaller.marshal(e, writer);
+            } else {
+                marshaller.marshal(e, stream);
             }
-            if (xmlStreamWriterWrapper != null) {
-                writer = xmlStreamWriterWrapper.wrapWriter(writer);
+        } else if (!mustBeJAXBElement) {
+            // write the graph as is to the output stream
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Attempt to marshalling non JAXBElement with type {} as InputStream", ObjectHelper.classCanonicalName(graph));
             }
-            marshaller.marshal(e, writer);
+            InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);
+            IOHelper.copyAndCloseInput(is, stream);
         } else {
-            marshaller.marshal(e, stream);
+            throw new InvalidPayloadException(exchange, JAXBElement.class);
         }
     }
 
@@ -211,7 +224,15 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
     public void setIgnoreJAXBElement(boolean flag) {
         ignoreJAXBElement = flag;
     }
-    
+
+    public boolean isMustBeJAXBElement() {
+        return mustBeJAXBElement;
+    }
+
+    public void setMustBeJAXBElement(boolean mustBeJAXBElement) {
+        this.mustBeJAXBElement = mustBeJAXBElement;
+    }
+
     public JAXBContext getContext() {
         return context;
     }
@@ -344,6 +365,8 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
             // if context not injected, create one and resolve partial class up front so they are ready to be used
             context = createContext();
         }
+        introspector = context.createJAXBIntrospector();
+
         if (partClass != null) {
             partialClass = camelContext.getClassResolver().resolveMandatoryClass(partClass, Object.class);
         }
@@ -396,7 +419,6 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
                     return event.getSeverity() == ValidationEvent.WARNING;
                 }
             });
-
         }
 
         return unmarshaller;
@@ -413,7 +435,6 @@ public class JaxbDataFormat extends ServiceSupport implements DataFormat, CamelC
                     return event.getSeverity() == ValidationEvent.WARNING;
                 }
             });
-
         }
 
         return marshaller;

http://git-wip-us.apache.org/repos/asf/camel/blob/f97cd5ca/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
----------------------------------------------------------------------
diff --git a/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
new file mode 100644
index 0000000..e2a2971
--- /dev/null
+++ b/components/camel-jaxb/src/test/java/org/apache/camel/jaxb/JaxbDataFormatMustBeJAXBElementTest.java
@@ -0,0 +1,93 @@
+/**
+ * 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.jaxb;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.InvalidPayloadException;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.jaxb.JaxbDataFormat;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Test;
+
+public class JaxbDataFormatMustBeJAXBElementTest extends CamelTestSupport {
+
+    @Test
+    public void testJaxbMarshalling() throws InterruptedException {
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedMessageCount(1);
+        mock.message(0).body().endsWith("<foo><bar>Hello Bar</bar></foo>");
+
+        template.sendBody("direct:start", "<foo><bar>Hello Bar</bar></foo>");
+
+        assertMockEndpointsSatisfied();
+    }
+
+    @Test
+    public void testJaxbMarshalling2() throws InterruptedException {
+        getMockEndpoint("mock:result").expectedMessageCount(0);
+
+        try {
+            template.sendBody("direct:start2", "<foo><bar>Hello Bar</bar></foo>");
+            fail("Should have thrown exception");
+        } catch (CamelExecutionException e) {
+            InvalidPayloadException ipe = assertIsInstanceOf(InvalidPayloadException.class, e.getCause().getCause());
+            assertNotNull(ipe);
+            assertEquals(JAXBElement.class, ipe.getType());
+        }
+
+        assertMockEndpointsSatisfied();
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                JaxbDataFormat jaxb = new JaxbDataFormat(JAXBContext.newInstance(Foo.class));
+                jaxb.setPrettyPrint(false);
+                jaxb.setMustBeJAXBElement(false);
+
+                from("direct:start").marshal(jaxb).to("log:xml", "mock:result");
+
+                JaxbDataFormat jaxb2 = new JaxbDataFormat(JAXBContext.newInstance(Foo.class));
+                jaxb2.setPrettyPrint(false);
+                jaxb2.setMustBeJAXBElement(true);
+
+                from("direct:start2").marshal(jaxb2).to("log:xml", "mock:result2");
+            }
+        };
+    }
+
+    @XmlRootElement
+    public static class Foo {
+        private String bar;
+
+        public String getBar() {
+            return bar;
+        }
+
+        public void setBar(String bar) {
+            this.bar = bar;
+        }
+    }
+
+}