Search in sources :

Example 6 with Message

use of org.apache.cxf.common.i18n.Message in project tomee by apache.

the class DataWriterImpl method createMarshaller.

public Marshaller createMarshaller(Object elValue, MessagePartInfo part) {
    // Class<?> cls = null;
    // if (part != null) {
    // cls = part.getTypeClass();
    // }
    // 
    // if (cls == null) {
    // cls = null != elValue ? elValue.getClass() : null;
    // }
    // 
    // if (cls != null && cls.isArray() && elValue instanceof Collection) {
    // Collection<?> col = (Collection<?>)elValue;
    // elValue = col.toArray((Object[])Array.newInstance(cls.getComponentType(), col.size()));
    // }
    Marshaller marshaller;
    try {
        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        marshaller.setListener(databinding.getMarshallerListener());
        databinding.applyEscapeHandler(!noEscape, eh -> JAXBUtils.setEscapeHandler(marshaller, eh));
        if (setEventHandler) {
            ValidationEventHandler h = veventHandler;
            if (veventHandler == null) {
                h = new ValidationEventHandler() {

                    public boolean handleEvent(ValidationEvent event) {
                        // continue on warnings only
                        return event.getSeverity() == ValidationEvent.WARNING;
                    }
                };
            }
            marshaller.setEventHandler(h);
        }
        final Map<String, String> nspref = databinding.getDeclaredNamespaceMappings();
        final Map<String, String> nsctxt = databinding.getContextualNamespaceMap();
        // set the prefix mapper if either of the prefix map is configured
        if (nspref != null || nsctxt != null) {
            Object mapper = JAXBUtils.setNamespaceMapper(bus, nspref != null ? nspref : nsctxt, marshaller);
            if (nsctxt != null) {
                setContextualNamespaceDecls(mapper, nsctxt);
            }
        }
        if (databinding.getMarshallerProperties() != null) {
            for (Map.Entry<String, Object> propEntry : databinding.getMarshallerProperties().entrySet()) {
                try {
                    marshaller.setProperty(propEntry.getKey(), propEntry.getValue());
                } catch (PropertyException pe) {
                    LOG.log(Level.INFO, "PropertyException setting Marshaller properties", pe);
                }
            }
        }
        marshaller.setSchema(schema);
        AttachmentMarshaller atmarsh = getAttachmentMarshaller();
        marshaller.setAttachmentMarshaller(atmarsh);
        if (schema != null && atmarsh instanceof JAXBAttachmentMarshaller) {
            // we need a special even handler for XOP attachments
            marshaller.setEventHandler(new MtomValidationHandler(marshaller.getEventHandler(), (JAXBAttachmentMarshaller) atmarsh));
        }
    } catch (javax.xml.bind.MarshalException ex) {
        Message faultMessage = new Message("MARSHAL_ERROR", LOG, ex.getLinkedException().getMessage());
        throw new Fault(faultMessage, ex);
    } catch (JAXBException ex) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
    }
    for (XmlAdapter<?, ?> adapter : databinding.getConfiguredXmlAdapters()) {
        marshaller.setAdapter(adapter);
    }
    return marshaller;
}
Also used : AttachmentMarshaller(javax.xml.bind.attachment.AttachmentMarshaller) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) Marshaller(javax.xml.bind.Marshaller) AttachmentMarshaller(javax.xml.bind.attachment.AttachmentMarshaller) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) Message(org.apache.cxf.common.i18n.Message) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) Fault(org.apache.cxf.interceptor.Fault) JAXBAttachmentMarshaller(org.apache.cxf.jaxb.attachment.JAXBAttachmentMarshaller) MarshalException(javax.xml.bind.MarshalException) ValidationEvent(javax.xml.bind.ValidationEvent) Map(java.util.Map)

Example 7 with Message

use of org.apache.cxf.common.i18n.Message in project cxf by apache.

the class AbstractWSDLBasedEndpointFactory method createBindingInfo.

protected BindingInfo createBindingInfo() {
    BindingFactoryManager mgr = bus.getExtension(BindingFactoryManager.class);
    String binding = bindingId;
    if (binding == null && bindingConfig != null) {
        binding = bindingConfig.getBindingId();
    }
    if (binding == null) {
        // default to soap binding
        binding = "http://schemas.xmlsoap.org/soap/";
    }
    try {
        if (binding.contains("/soap")) {
            if (bindingConfig == null) {
                bindingConfig = createSoapBindingConfig();
            }
            if (bindingConfig instanceof SoapBindingConfiguration && !((SoapBindingConfiguration) bindingConfig).isSetStyle()) {
                ((SoapBindingConfiguration) bindingConfig).setStyle(serviceFactory.getStyle());
            }
        }
        bindingFactory = mgr.getBindingFactory(binding);
        BindingInfo inf = bindingFactory.createBindingInfo(serviceFactory.getService(), binding, bindingConfig);
        for (BindingOperationInfo boi : inf.getOperations()) {
            serviceFactory.updateBindingOperation(boi);
            Method m = serviceFactory.getMethodDispatcher().getMethod(boi);
            serviceFactory.sendEvent(FactoryBeanListener.Event.BINDING_OPERATION_CREATED, inf, boi, m);
        }
        serviceFactory.sendEvent(FactoryBeanListener.Event.BINDING_CREATED, inf);
        return inf;
    } catch (BusException ex) {
        throw new ServiceConstructionException(new Message("COULD.NOT.RESOLVE.BINDING", LOG, bindingId), ex);
    }
}
Also used : BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) Message(org.apache.cxf.common.i18n.Message) SoapBindingConfiguration(org.apache.cxf.binding.soap.SoapBindingConfiguration) BindingInfo(org.apache.cxf.service.model.BindingInfo) SoapBindingInfo(org.apache.cxf.binding.soap.model.SoapBindingInfo) BindingFactoryManager(org.apache.cxf.binding.BindingFactoryManager) Method(java.lang.reflect.Method) ServiceConstructionException(org.apache.cxf.service.factory.ServiceConstructionException) BusException(org.apache.cxf.BusException)

Example 8 with Message

use of org.apache.cxf.common.i18n.Message in project cxf by apache.

the class JAXBEncoderDecoder method unmarshallException.

public static Exception unmarshallException(Unmarshaller u, Object source, MessagePartInfo part) {
    XMLStreamReader reader;
    if (source instanceof XMLStreamReader) {
        reader = (XMLStreamReader) source;
    } else if (source instanceof Element) {
        reader = StaxUtils.createXMLStreamReader((Element) source);
        try {
            // advance into the node
            reader.nextTag();
        } catch (XMLStreamException e) {
        // ignore
        }
    } else {
        throw new Fault(new Message("UNKNOWN_SOURCE", LOG, source.getClass().getName()));
    }
    try {
        QName qn = part.getElementQName();
        if (!qn.equals(reader.getName())) {
            throw new Fault(new Message("ELEMENT_NAME_MISMATCH", LOG, qn, reader.getName()));
        }
        Class<?> cls = part.getTypeClass();
        Object obj;
        try {
            Constructor<?> cons = cls.getConstructor();
            obj = cons.newInstance();
        } catch (NoSuchMethodException nse) {
            Constructor<?> cons = cls.getConstructor(new Class[] { String.class });
            obj = cons.newInstance(new Object[1]);
        }
        XmlAccessType accessType = Utils.getXmlAccessType(cls);
        reader.nextTag();
        while (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
            QName q = reader.getName();
            String fieldName = q.getLocalPart();
            Field f = Utils.getField(cls, accessType, fieldName);
            if (f != null) {
                Type type = f.getGenericType();
                ReflectionUtil.setAccessible(f);
                if (JAXBSchemaInitializer.isArray(type)) {
                    Class<?> compType = JAXBSchemaInitializer.getArrayComponentType(type);
                    List<Object> ret = unmarshallArray(u, reader, q, compType, createList(type));
                    Object o = ret;
                    if (!isList(type)) {
                        if (compType.isPrimitive()) {
                            o = java.lang.reflect.Array.newInstance(compType, ret.size());
                            for (int x = 0; x < ret.size(); x++) {
                                Array.set(o, x, ret.get(x));
                            }
                        } else {
                            o = ret.toArray((Object[]) Array.newInstance(compType, ret.size()));
                        }
                    }
                    f.set(obj, o);
                } else {
                    Object o = getElementValue(u.unmarshal(reader, Utils.getFieldType(f)));
                    Utils.setFieldValue(f, obj, o);
                }
            } else {
                String s = StringUtils.capitalize(q.getLocalPart());
                Method m = Utils.getMethod(cls, accessType, "get" + s);
                if (m == null) {
                    m = Utils.getMethod(cls, accessType, "is" + s);
                }
                Type type = m.getGenericReturnType();
                Object o;
                if (JAXBSchemaInitializer.isArray(type)) {
                    Class<?> compType = JAXBSchemaInitializer.getArrayComponentType(type);
                    List<Object> ret = unmarshallArray(u, reader, q, compType, createList(type));
                    o = ret;
                    if (!isList(type)) {
                        if (compType.isPrimitive()) {
                            o = java.lang.reflect.Array.newInstance(compType, ret.size());
                            for (int x = 0; x < ret.size(); x++) {
                                Array.set(o, x, ret.get(x));
                            }
                        } else {
                            o = ret.toArray((Object[]) Array.newInstance(compType, ret.size()));
                        }
                    }
                } else {
                    o = getElementValue(u.unmarshal(reader, Utils.getMethodReturnType(m)));
                }
                Method m2 = Utils.getMethod(cls, accessType, "set" + s, m.getReturnType());
                if (m2 != null) {
                    if (JAXBSchemaInitializer.isArray(type)) {
                        m2.invoke(obj, o);
                    } else {
                        Utils.setMethodValue(m, m2, obj, o);
                    }
                } else {
                    Field fn = ReflectionUtil.getDeclaredField(cls, q.getLocalPart());
                    if (fn != null) {
                        ReflectionUtil.setAccessible(fn);
                        fn.set(obj, o);
                    }
                }
            }
            if (reader.getEventType() == XMLStreamConstants.END_ELEMENT && q.equals(reader.getName())) {
                reader.next();
            }
        }
        return (Exception) obj;
    } catch (Exception e) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) DepthXMLStreamReader(org.apache.cxf.staxutils.DepthXMLStreamReader) Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) Constructor(java.lang.reflect.Constructor) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) PrivilegedActionException(java.security.PrivilegedActionException) Field(java.lang.reflect.Field) GenericArrayType(java.lang.reflect.GenericArrayType) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Type(java.lang.reflect.Type) XmlSchemaSimpleType(org.apache.ws.commons.schema.XmlSchemaSimpleType) XmlType(javax.xml.bind.annotation.XmlType) ParameterizedType(java.lang.reflect.ParameterizedType) XMLStreamException(javax.xml.stream.XMLStreamException) XmlAccessType(javax.xml.bind.annotation.XmlAccessType)

Example 9 with Message

use of org.apache.cxf.common.i18n.Message in project cxf by apache.

the class JAXBEncoderDecoder method marshallException.

public static void marshallException(Marshaller marshaller, Exception elValue, MessagePartInfo part, Object source) {
    XMLStreamWriter writer = getStreamWriter(source);
    QName qn = part.getElementQName();
    try {
        writer.writeStartElement("ns1", qn.getLocalPart(), qn.getNamespaceURI());
        Class<?> cls = part.getTypeClass();
        XmlAccessType accessType = Utils.getXmlAccessType(cls);
        String namespace = part.getElementQName().getNamespaceURI();
        String attNs = namespace;
        SchemaInfo sch = part.getMessageInfo().getOperation().getInterface().getService().getSchema(namespace);
        if (sch == null) {
            LOG.warning("Schema associated with " + namespace + " is null");
            namespace = null;
            attNs = null;
        } else {
            if (!sch.isElementFormQualified()) {
                namespace = null;
            }
            if (!sch.isAttributeFormQualified()) {
                attNs = null;
            }
        }
        List<Member> combinedMembers = new ArrayList<>();
        for (Field f : Utils.getFields(cls, accessType)) {
            XmlAttribute at = f.getAnnotation(XmlAttribute.class);
            if (at == null) {
                combinedMembers.add(f);
            } else {
                QName fname = new QName(attNs, StringUtils.isEmpty(at.name()) ? f.getName() : at.name());
                ReflectionUtil.setAccessible(f);
                Object o = Utils.getFieldValue(f, elValue);
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                writeObject(marshaller, frag, newJAXBElement(fname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, fname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(fname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        for (Method m : Utils.getGetters(cls, accessType)) {
            if (!m.isAnnotationPresent(XmlAttribute.class)) {
                combinedMembers.add(m);
            } else {
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                XmlAttribute at = m.getAnnotation(XmlAttribute.class);
                QName mname = new QName(namespace, StringUtils.isEmpty(at.name()) ? name : at.name());
                DocumentFragment frag = DOMUtils.getEmptyDocument().createDocumentFragment();
                Object o = Utils.getMethodValue(m, elValue);
                writeObject(marshaller, frag, newJAXBElement(mname, String.class, o));
                if (attNs != null) {
                    writer.writeAttribute(attNs, mname.getLocalPart(), DOMUtils.getAllContent(frag));
                } else {
                    writer.writeAttribute(mname.getLocalPart(), DOMUtils.getAllContent(frag));
                }
            }
        }
        XmlAccessorOrder xmlAccessorOrder = cls.getAnnotation(XmlAccessorOrder.class);
        if (xmlAccessorOrder != null && xmlAccessorOrder.value().equals(XmlAccessOrder.ALPHABETICAL)) {
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    return m1.getName().compareTo(m2.getName());
                }
            });
        }
        XmlType xmlType = cls.getAnnotation(XmlType.class);
        if (xmlType != null && xmlType.propOrder().length > 1 && !xmlType.propOrder()[0].isEmpty()) {
            final List<String> orderList = Arrays.asList(xmlType.propOrder());
            Collections.sort(combinedMembers, new Comparator<Member>() {

                public int compare(Member m1, Member m2) {
                    String m1Name = getName(m1);
                    String m2Name = getName(m2);
                    int m1Index = orderList.indexOf(m1Name);
                    int m2Index = orderList.indexOf(m2Name);
                    if (m1Index != -1 && m2Index != -1) {
                        return m1Index - m2Index;
                    }
                    if (m1Index == -1 && m2Index != -1) {
                        return 1;
                    }
                    if (m1Index != -1 && m2Index == -1) {
                        return -1;
                    }
                    return 0;
                }
            });
        }
        for (Member member : combinedMembers) {
            if (member instanceof Field) {
                Field f = (Field) member;
                QName fname = new QName(namespace, f.getName());
                ReflectionUtil.setAccessible(f);
                if (JAXBSchemaInitializer.isArray(f.getGenericType())) {
                    writeArrayObject(marshaller, writer, fname, f.get(elValue));
                } else {
                    Object o = Utils.getFieldValue(f, elValue);
                    writeObject(marshaller, writer, newJAXBElement(fname, String.class, o));
                }
            } else {
                // it's a Method
                Method m = (Method) member;
                int idx = m.getName().startsWith("get") ? 3 : 2;
                String name = m.getName().substring(idx);
                name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
                QName mname = new QName(namespace, name);
                if (JAXBSchemaInitializer.isArray(m.getGenericReturnType())) {
                    writeArrayObject(marshaller, writer, mname, m.invoke(elValue));
                } else {
                    Object o = Utils.getMethodValue(m, elValue);
                    writeObject(marshaller, writer, newJAXBElement(mname, String.class, o));
                }
            }
        }
        writer.writeEndElement();
        writer.flush();
    } catch (Exception e) {
        throw new Fault(new Message("MARSHAL_ERROR", LOG, e.getMessage()), e);
    } finally {
        StaxUtils.close(writer);
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessorOrder) Message(org.apache.cxf.common.i18n.Message) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Fault(org.apache.cxf.interceptor.Fault) Method(java.lang.reflect.Method) XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) PrivilegedActionException(java.security.PrivilegedActionException) XmlType(javax.xml.bind.annotation.XmlType) Field(java.lang.reflect.Field) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) XmlAccessType(javax.xml.bind.annotation.XmlAccessType) Member(java.lang.reflect.Member) DocumentFragment(org.w3c.dom.DocumentFragment) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Example 10 with Message

use of org.apache.cxf.common.i18n.Message in project cxf by apache.

the class JAXBSchemaInitializer method createBridgeXsElement.

private void createBridgeXsElement(MessagePartInfo part, QName qn, QName typeName) {
    SchemaInfo schemaInfo = serviceInfo.getSchema(qn.getNamespaceURI());
    if (schemaInfo != null) {
        XmlSchemaElement el = schemaInfo.getElementByQName(qn);
        if (el == null) {
            createXsElement(schemaInfo.getSchema(), part, typeName, schemaInfo);
        } else if (!typeName.equals(el.getSchemaTypeName())) {
            throw new Fault(new Message("CANNOT_CREATE_ELEMENT", LOG, qn, typeName, el.getSchemaTypeName()));
        }
        return;
    }
    XmlSchema schema = schemas.newXmlSchemaInCollection(qn.getNamespaceURI());
    if (qualifiedSchemas) {
        schema.setElementFormDefault(XmlSchemaForm.QUALIFIED);
    }
    schemaInfo = new SchemaInfo(qn.getNamespaceURI(), qualifiedSchemas, false);
    schemaInfo.setSchema(schema);
    createXsElement(schema, part, typeName, schemaInfo);
    NamespaceMap nsMap = new NamespaceMap();
    nsMap.add(WSDLConstants.CONVENTIONAL_TNS_PREFIX, schema.getTargetNamespace());
    nsMap.add(WSDLConstants.NP_SCHEMA_XSD, WSDLConstants.NS_SCHEMA_XSD);
    schema.setNamespaceContext(nsMap);
    serviceInfo.addSchema(schemaInfo);
}
Also used : Message(org.apache.cxf.common.i18n.Message) XmlSchema(org.apache.ws.commons.schema.XmlSchema) XmlSchemaElement(org.apache.ws.commons.schema.XmlSchemaElement) NamespaceMap(org.apache.ws.commons.schema.utils.NamespaceMap) Fault(org.apache.cxf.interceptor.Fault) SchemaInfo(org.apache.cxf.service.model.SchemaInfo)

Aggregations

Message (org.apache.cxf.common.i18n.Message)201 ToolException (org.apache.cxf.tools.common.ToolException)69 IOException (java.io.IOException)45 QName (javax.xml.namespace.QName)42 Fault (org.apache.cxf.interceptor.Fault)34 XMLStreamException (javax.xml.stream.XMLStreamException)27 JAXBException (javax.xml.bind.JAXBException)23 ArrayList (java.util.ArrayList)19 XmlSchemaElement (org.apache.ws.commons.schema.XmlSchemaElement)17 Element (org.w3c.dom.Element)17 File (java.io.File)16 WSDLException (javax.wsdl.WSDLException)15 Method (java.lang.reflect.Method)14 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)13 ServiceInfo (org.apache.cxf.service.model.ServiceInfo)12 InputStream (java.io.InputStream)11 HashMap (java.util.HashMap)11 List (java.util.List)11 Map (java.util.Map)11 ServiceConstructionException (org.apache.cxf.service.factory.ServiceConstructionException)11