Search in sources :

Example 1 with Marshaller

use of javax.xml.bind.Marshaller in project camel by apache.

the class ModelHelper method dumpModelAsXml.

/**
     * Dumps the definition as XML
     *
     * @param context    the CamelContext, if <tt>null</tt> then {@link org.apache.camel.spi.ModelJAXBContextFactory} is not in use
     * @param definition the definition, such as a {@link org.apache.camel.NamedNode}
     * @return the output in XML (is formatted)
     * @throws JAXBException is throw if error marshalling to XML
     */
public static String dumpModelAsXml(CamelContext context, NamedNode definition) throws JAXBException {
    JAXBContext jaxbContext = getJAXBContext(context);
    final Map<String, String> namespaces = new LinkedHashMap<>();
    // gather all namespaces from the routes or route which is stored on the expression nodes
    if (definition instanceof RoutesDefinition) {
        List<RouteDefinition> routes = ((RoutesDefinition) definition).getRoutes();
        for (RouteDefinition route : routes) {
            extractNamespaces(route, namespaces);
        }
    } else if (definition instanceof RouteDefinition) {
        RouteDefinition route = (RouteDefinition) definition;
        extractNamespaces(route, namespaces);
    }
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter buffer = new StringWriter();
    marshaller.marshal(definition, buffer);
    XmlConverter xmlConverter = newXmlConverter(context);
    String xml = buffer.toString();
    Document dom;
    try {
        dom = xmlConverter.toDOMDocument(xml, null);
    } catch (Exception e) {
        throw new TypeConversionException(xml, Document.class, e);
    }
    // Add additional namespaces to the document root element
    Element documentElement = dom.getDocumentElement();
    for (String nsPrefix : namespaces.keySet()) {
        String prefix = nsPrefix.equals("xmlns") ? nsPrefix : "xmlns:" + nsPrefix;
        documentElement.setAttribute(prefix, namespaces.get(nsPrefix));
    }
    // We invoke the type converter directly because we need to pass some custom XML output options
    Properties outputProperties = new Properties();
    outputProperties.put(OutputKeys.INDENT, "yes");
    outputProperties.put(OutputKeys.STANDALONE, "yes");
    try {
        return xmlConverter.toStringFromDocument(dom, outputProperties);
    } catch (TransformerException e) {
        throw new IllegalStateException("Failed converting document object to string", e);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) TypeConversionException(org.apache.camel.TypeConversionException) Element(org.w3c.dom.Element) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) Properties(java.util.Properties) TransformerException(javax.xml.transform.TransformerException) JAXBException(javax.xml.bind.JAXBException) TypeConversionException(org.apache.camel.TypeConversionException) LinkedHashMap(java.util.LinkedHashMap) XmlConverter(org.apache.camel.converter.jaxp.XmlConverter) StringWriter(java.io.StringWriter) TransformerException(javax.xml.transform.TransformerException)

Example 2 with Marshaller

use of javax.xml.bind.Marshaller in project camel by apache.

the class RestContextRefDefinitionHelper method cloneRestDefinition.

private static RestDefinition cloneRestDefinition(JAXBContext jaxbContext, RestDefinition def) throws JAXBException {
    Marshaller marshal = jaxbContext.createMarshaller();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshal.marshal(def, bos);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Object clone = unmarshaller.unmarshal(bis);
    if (clone != null && clone instanceof RestDefinition) {
        RestDefinition def2 = (RestDefinition) clone;
        Iterator<VerbDefinition> verbit1 = def.getVerbs().iterator();
        Iterator<VerbDefinition> verbit2 = def2.getVerbs().iterator();
        while (verbit1.hasNext() && verbit2.hasNext()) {
            VerbDefinition verb1 = verbit1.next();
            VerbDefinition verb2 = verbit2.next();
            if (verb1.getToOrRoute() instanceof RouteDefinition && verb2.getToOrRoute() instanceof RouteDefinition) {
                RouteDefinition route1 = (RouteDefinition) verb1.getToOrRoute();
                RouteDefinition route2 = (RouteDefinition) verb2.getToOrRoute();
                // need to clone the namespaces also as they are not JAXB marshalled (as they are transient)
                Iterator<ExpressionNode> it = ProcessorDefinitionHelper.filterTypeInOutputs(route1.getOutputs(), ExpressionNode.class);
                Iterator<ExpressionNode> it2 = ProcessorDefinitionHelper.filterTypeInOutputs(route2.getOutputs(), ExpressionNode.class);
                while (it.hasNext() && it2.hasNext()) {
                    ExpressionNode node = it.next();
                    ExpressionNode node2 = it2.next();
                    NamespaceAwareExpression name = null;
                    NamespaceAwareExpression name2 = null;
                    if (node.getExpression() instanceof NamespaceAwareExpression) {
                        name = (NamespaceAwareExpression) node.getExpression();
                    }
                    if (node2.getExpression() instanceof NamespaceAwareExpression) {
                        name2 = (NamespaceAwareExpression) node2.getExpression();
                    }
                    if (name != null && name2 != null && name.getNamespaces() != null && !name.getNamespaces().isEmpty()) {
                        Map<String, String> map = new HashMap<String, String>();
                        map.putAll(name.getNamespaces());
                        name2.setNamespaces(map);
                    }
                }
            }
        }
        return def2;
    }
    return null;
}
Also used : Marshaller(javax.xml.bind.Marshaller) RestDefinition(org.apache.camel.model.rest.RestDefinition) VerbDefinition(org.apache.camel.model.rest.VerbDefinition) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Unmarshaller(javax.xml.bind.Unmarshaller) NamespaceAwareExpression(org.apache.camel.model.language.NamespaceAwareExpression)

Example 3 with Marshaller

use of javax.xml.bind.Marshaller in project camel by apache.

the class GenerateXmlTest method dump.

protected void dump(RouteContainer context) throws Exception {
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter buffer = new StringWriter();
    marshaller.marshal(context, buffer);
    log.info("Created: " + buffer);
    assertNotNull(buffer);
    String out = buffer.toString();
    assertTrue("Should contain the description", out.indexOf("This is a description of the route") > 0);
}
Also used : Marshaller(javax.xml.bind.Marshaller) StringWriter(java.io.StringWriter)

Example 4 with Marshaller

use of javax.xml.bind.Marshaller in project camel by apache.

the class JaxbDataFormat method marshal.

public void marshal(Exchange exchange, Object graph, OutputStream stream) throws IOException, SAXException {
    try {
        // must create a new instance of marshaller as its not thread safe
        Marshaller marshaller = createMarshaller();
        if (isPrettyPrint()) {
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }
        // exchange take precedence over encoding option
        String charset = exchange.getProperty(Exchange.CHARSET_NAME, String.class);
        if (charset == null) {
            charset = encoding;
        }
        if (charset != null) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
        }
        if (isFragment()) {
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        }
        if (ObjectHelper.isNotEmpty(schemaLocation)) {
            marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
        }
        if (ObjectHelper.isNotEmpty(noNamespaceSchemaLocation)) {
            marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, noNamespaceSchemaLocation);
        }
        if (namespacePrefixMapper != null) {
            marshaller.setProperty(namespacePrefixMapper.getRegistrationKey(), namespacePrefixMapper);
        }
        // Inject any JAX-RI custom properties from the exchange or from the instance into the marshaller
        Map<String, Object> customProperties = exchange.getProperty(JaxbConstants.JAXB_PROVIDER_PROPERTIES, Map.class);
        if (customProperties == null) {
            customProperties = getJaxbProviderProperties();
        }
        if (customProperties != null) {
            for (Entry<String, Object> property : customProperties.entrySet()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using JAXB Provider Property {}={}", property.getKey(), property.getValue());
                }
                marshaller.setProperty(property.getKey(), property.getValue());
            }
        }
        marshal(exchange, graph, stream, marshaller);
        if (contentTypeHeader) {
            if (exchange.hasOut()) {
                exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/xml");
            } else {
                exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/xml");
            }
        }
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) IOException(java.io.IOException) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) XMLStreamException(javax.xml.stream.XMLStreamException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) InvalidPayloadException(org.apache.camel.InvalidPayloadException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 5 with Marshaller

use of javax.xml.bind.Marshaller in project camel by apache.

the class DataFormatConcurrentTest method createPayloads.

/**
     * the individual size of one record is:
     * fooBarSize = 1  -> 104 bytes
     * fooBarSize = 50 -> 2046 bytes
     * @return the payloads used for this stress test
     * @throws Exception
     */
public ByteArrayInputStream[] createPayloads(int testCount) throws Exception {
    Foo foo = new Foo();
    for (int x = 0; x < fooBarSize; x++) {
        Bar bar = new Bar();
        bar.setName("Name: " + x);
        bar.setValue("value: " + x);
        foo.getBarRefs().add(bar);
    }
    Marshaller m = JAXBContext.newInstance(Foo.class, Bar.class).createMarshaller();
    StringWriter writer = new StringWriter();
    m.marshal(foo, writer);
    byte[] payload = writer.toString().getBytes();
    ByteArrayInputStream[] streams = new ByteArrayInputStream[testCount];
    for (int i = 0; i < testCount; i++) {
        streams[i] = new ByteArrayInputStream(payload);
    }
    return streams;
}
Also used : Marshaller(javax.xml.bind.Marshaller) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) MockEndpoint(org.apache.camel.component.mock.MockEndpoint)

Aggregations

Marshaller (javax.xml.bind.Marshaller)214 JAXBContext (javax.xml.bind.JAXBContext)129 JAXBException (javax.xml.bind.JAXBException)75 StringWriter (java.io.StringWriter)73 ByteArrayOutputStream (java.io.ByteArrayOutputStream)22 File (java.io.File)22 Test (org.junit.Test)21 IOException (java.io.IOException)19 FileOutputStream (java.io.FileOutputStream)18 Unmarshaller (javax.xml.bind.Unmarshaller)18 JAXBElement (javax.xml.bind.JAXBElement)16 ByteArrayInputStream (java.io.ByteArrayInputStream)12 Writer (java.io.Writer)11 Document (org.w3c.dom.Document)8 InputStream (java.io.InputStream)7 QName (javax.xml.namespace.QName)7 Schema (javax.xml.validation.Schema)7 Diff (org.custommonkey.xmlunit.Diff)7 ArrayList (java.util.ArrayList)6 SchemaFactory (javax.xml.validation.SchemaFactory)6