Search in sources :

Example 6 with JAXBException

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

the class CamelNamespaceHandler method parseCamelContextNode.

private Metadata parseCamelContextNode(Element element, ParserContext context) {
    LOG.trace("Parsing CamelContext {}", element);
    // Find the id, generate one if needed
    String contextId = element.getAttribute("id");
    boolean implicitId = false;
    // let's avoid folks having to explicitly give an ID to a camel context
    if (ObjectHelper.isEmpty(contextId)) {
        // if no explicit id was set then use a default auto generated name
        CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy();
        contextId = strategy.getName();
        element.setAttributeNS(null, "id", contextId);
        implicitId = true;
    }
    // now let's parse the routes with JAXB
    Binder<Node> binder;
    try {
        binder = getJaxbContext().createBinder();
    } catch (JAXBException e) {
        throw new ComponentDefinitionException("Failed to create the JAXB binder : " + e, e);
    }
    Object value = parseUsingJaxb(element, context, binder);
    if (!(value instanceof CamelContextFactoryBean)) {
        throw new ComponentDefinitionException("Expected an instance of " + CamelContextFactoryBean.class);
    }
    CamelContextFactoryBean ccfb = (CamelContextFactoryBean) value;
    ccfb.setImplicitId(implicitId);
    // The properties component is always used / created by the CamelContextFactoryBean
    // so we need to ensure that the resolver is ready to use
    ComponentMetadata propertiesComponentResolver = getComponentResolverReference(context, "properties");
    MutablePassThroughMetadata factory = context.createMetadata(MutablePassThroughMetadata.class);
    factory.setId(".camelBlueprint.passThrough." + contextId);
    factory.setObject(new PassThroughCallable<Object>(value));
    MutableBeanMetadata factory2 = context.createMetadata(MutableBeanMetadata.class);
    factory2.setId(".camelBlueprint.factory." + contextId);
    factory2.setFactoryComponent(factory);
    factory2.setFactoryMethod("call");
    factory2.setInitMethod("afterPropertiesSet");
    factory2.setDestroyMethod("destroy");
    factory2.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    factory2.addProperty("bundleContext", createRef(context, "blueprintBundleContext"));
    factory2.addDependsOn(propertiesComponentResolver.getId());
    // We need to add other components which the camel context dependsOn
    if (ObjectHelper.isNotEmpty(ccfb.getDependsOn())) {
        factory2.setDependsOn(Arrays.asList(ccfb.getDependsOn().split(" |,")));
    }
    context.getComponentDefinitionRegistry().registerComponentDefinition(factory2);
    MutableBeanMetadata ctx = context.createMetadata(MutableBeanMetadata.class);
    ctx.setId(contextId);
    ctx.setRuntimeClass(BlueprintCamelContext.class);
    ctx.setFactoryComponent(factory2);
    ctx.setFactoryMethod("getContext");
    ctx.setInitMethod("init");
    ctx.setDestroyMethod("destroy");
    // Register factory beans
    registerBeans(context, contextId, ccfb.getThreadPools());
    registerBeans(context, contextId, ccfb.getEndpoints());
    registerBeans(context, contextId, ccfb.getRedeliveryPolicies());
    registerBeans(context, contextId, ccfb.getBeansFactory());
    // Register processors
    MutablePassThroughMetadata beanProcessorFactory = context.createMetadata(MutablePassThroughMetadata.class);
    beanProcessorFactory.setId(".camelBlueprint.processor.bean.passThrough." + contextId);
    beanProcessorFactory.setObject(new PassThroughCallable<Object>(new CamelInjector(contextId)));
    MutableBeanMetadata beanProcessor = context.createMetadata(MutableBeanMetadata.class);
    beanProcessor.setId(".camelBlueprint.processor.bean." + contextId);
    beanProcessor.setRuntimeClass(CamelInjector.class);
    beanProcessor.setFactoryComponent(beanProcessorFactory);
    beanProcessor.setFactoryMethod("call");
    beanProcessor.setProcessor(true);
    beanProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    context.getComponentDefinitionRegistry().registerComponentDefinition(beanProcessor);
    MutablePassThroughMetadata regProcessorFactory = context.createMetadata(MutablePassThroughMetadata.class);
    regProcessorFactory.setId(".camelBlueprint.processor.registry.passThrough." + contextId);
    regProcessorFactory.setObject(new PassThroughCallable<Object>(new CamelDependenciesFinder(contextId, context)));
    MutableBeanMetadata regProcessor = context.createMetadata(MutableBeanMetadata.class);
    regProcessor.setId(".camelBlueprint.processor.registry." + contextId);
    regProcessor.setRuntimeClass(CamelDependenciesFinder.class);
    regProcessor.setFactoryComponent(regProcessorFactory);
    regProcessor.setFactoryMethod("call");
    regProcessor.setProcessor(true);
    regProcessor.addDependsOn(".camelBlueprint.processor.bean." + contextId);
    regProcessor.addProperty("blueprintContainer", createRef(context, "blueprintContainer"));
    context.getComponentDefinitionRegistry().registerComponentDefinition(regProcessor);
    // lets inject the namespaces into any namespace aware POJOs
    injectNamespaces(element, binder);
    LOG.trace("Parsing CamelContext done, returning {}", ctx);
    return ctx;
}
Also used : MutablePassThroughMetadata(org.apache.aries.blueprint.mutable.MutablePassThroughMetadata) ComponentDefinitionException(org.osgi.service.blueprint.container.ComponentDefinitionException) ExpressionNode(org.apache.camel.model.ExpressionNode) Node(org.w3c.dom.Node) JAXBException(javax.xml.bind.JAXBException) ComponentMetadata(org.osgi.service.blueprint.reflect.ComponentMetadata) MutableBeanMetadata(org.apache.aries.blueprint.mutable.MutableBeanMetadata) DefaultCamelContextNameStrategy(org.apache.camel.impl.DefaultCamelContextNameStrategy) CamelContextNameStrategy(org.apache.camel.spi.CamelContextNameStrategy) DefaultCamelContextNameStrategy(org.apache.camel.impl.DefaultCamelContextNameStrategy) CamelContextFactoryBean(org.apache.camel.blueprint.CamelContextFactoryBean)

Example 7 with JAXBException

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

the class ModelHelper method loadRoutesDefinition.

/**
     * Marshal the xml to the model definition
     *
     * @param context the CamelContext, if <tt>null</tt> then {@link org.apache.camel.spi.ModelJAXBContextFactory} is not in use
     * @param node the xml node
     * @throws Exception is thrown if an error is encountered unmarshalling from xml to model
     */
public static RoutesDefinition loadRoutesDefinition(CamelContext context, Node node) throws Exception {
    JAXBContext jaxbContext = getJAXBContext(context);
    Map<String, String> namespaces = new LinkedHashMap<>();
    Document dom = node instanceof Document ? (Document) node : node.getOwnerDocument();
    extractNamespaces(dom, namespaces);
    Binder<Node> binder = jaxbContext.createBinder();
    Object result = binder.unmarshal(node);
    if (result == null) {
        throw new JAXBException("Cannot unmarshal to RoutesDefinition using JAXB");
    }
    // can either be routes or a single route
    RoutesDefinition answer;
    if (result instanceof RouteDefinition) {
        RouteDefinition route = (RouteDefinition) result;
        answer = new RoutesDefinition();
        applyNamespaces(route, namespaces);
        answer.getRoutes().add(route);
    } else if (result instanceof RoutesDefinition) {
        answer = (RoutesDefinition) result;
        for (RouteDefinition route : answer.getRoutes()) {
            applyNamespaces(route, namespaces);
        }
    } else {
        throw new IllegalArgumentException("Unmarshalled object is an unsupported type: " + ObjectHelper.className(result) + " -> " + result);
    }
    return answer;
}
Also used : Node(org.w3c.dom.Node) NamedNode(org.apache.camel.NamedNode) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with JAXBException

use of javax.xml.bind.JAXBException 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 9 with JAXBException

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

the class JaxbDataFormat method unmarshal.

public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, SAXException {
    try {
        Object answer;
        XMLStreamReader xmlReader;
        if (needFiltering(exchange)) {
            xmlReader = typeConverter.convertTo(XMLStreamReader.class, createNonXmlFilterReader(exchange, stream));
        } else {
            xmlReader = typeConverter.convertTo(XMLStreamReader.class, stream);
        }
        if (partialClass != null) {
            // partial unmarshalling
            answer = createUnmarshaller().unmarshal(xmlReader, partialClass);
        } else {
            answer = createUnmarshaller().unmarshal(xmlReader);
        }
        if (answer instanceof JAXBElement && isIgnoreJAXBElement()) {
            answer = ((JAXBElement<?>) answer).getValue();
        }
        return answer;
    } catch (JAXBException e) {
        throw new IOException(e);
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) JAXBException(javax.xml.bind.JAXBException) JAXBElement(javax.xml.bind.JAXBElement) IOException(java.io.IOException)

Example 10 with JAXBException

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

the class LinkedInExceptionResponseFilter method filter.

@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (responseContext.getStatus() != Response.Status.OK.getStatusCode() && responseContext.hasEntity()) {
        try {
            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            final Error error = (Error) unmarshaller.unmarshal(responseContext.getEntityStream());
            final Response.ResponseBuilder builder = Response.status(responseContext.getStatusInfo());
            builder.entity(error);
            // copy response headers
            for (Map.Entry<String, List<String>> header : responseContext.getHeaders().entrySet()) {
                builder.header(header.getKey(), header.getValue());
            }
            throw new LinkedInException(error, builder.build());
        } catch (JAXBException e) {
            // log and ignore
            LOG.warn("Unable to parse LinkedIn error: " + e.getMessage(), e);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) JAXBException(javax.xml.bind.JAXBException) Error(org.apache.camel.component.linkedin.api.model.Error) List(java.util.List) Unmarshaller(javax.xml.bind.Unmarshaller) Map(java.util.Map)

Aggregations

JAXBException (javax.xml.bind.JAXBException)402 JAXBContext (javax.xml.bind.JAXBContext)126 IOException (java.io.IOException)93 Unmarshaller (javax.xml.bind.Unmarshaller)91 Marshaller (javax.xml.bind.Marshaller)69 ArrayList (java.util.ArrayList)38 StringWriter (java.io.StringWriter)35 List (java.util.List)35 Map (java.util.Map)33 SAXException (org.xml.sax.SAXException)32 File (java.io.File)29 InputStream (java.io.InputStream)29 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)28 HashSet (java.util.HashSet)28 JAXBElement (javax.xml.bind.JAXBElement)24 XMLStreamException (javax.xml.stream.XMLStreamException)23 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)22 StringReader (java.io.StringReader)21 HashMap (java.util.HashMap)21 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)20