org.apache.cxf.jaxb.JAXBEncoderDecoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cxf-bundle-minimal Show documentation
Show all versions of cxf-bundle-minimal Show documentation
Apache CXF Minimal Bundle Jar
/**
* 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.cxf.jaxb;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.bind.attachment.AttachmentUnmarshaller;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.common.jaxb.JAXBUtils;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.ReflectionUtil;
import org.apache.cxf.common.util.SOAPConstants;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.service.model.MessagePartInfo;
import org.apache.cxf.service.model.SchemaInfo;
import org.apache.cxf.staxutils.DepthXMLStreamReader;
import org.apache.cxf.staxutils.StaxUtils;
import org.apache.cxf.staxutils.W3CDOMStreamWriter;
import org.apache.cxf.staxutils.W3CNamespaceContext;
import org.apache.ws.commons.schema.XmlSchemaElement;
import org.apache.ws.commons.schema.XmlSchemaSimpleType;
import org.apache.ws.commons.schema.XmlSchemaSimpleTypeList;
/**
* Utility functions for JAXB.
*/
public final class JAXBEncoderDecoder {
private static final class AddXSITypeStreamReader extends StreamReaderDelegate {
private boolean first = true;
private final QName typeQName;
private AddXSITypeStreamReader(XMLStreamReader reader, QName typeQName) {
super(reader);
this.typeQName = typeQName;
}
public int getAttributeCount() {
return super.getAttributeCount() + (first ? 1 : 0);
}
public String getAttributeLocalName(int index) {
if (first && index == 0) {
return "type";
}
return super.getAttributeLocalName(index - 1);
}
public QName getAttributeName(int index) {
if (first && index == 0) {
return new QName(SOAPConstants.XSI_NS, "type");
}
return super.getAttributeName(index - 1);
}
public String getAttributeNamespace(int index) {
if (first && index == 0) {
return SOAPConstants.XSI_NS;
}
return super.getAttributeNamespace(index - 1);
}
public String getAttributePrefix(int index) {
if (first && index == 0) {
return "xsi";
}
return super.getAttributePrefix(index - 1);
}
public String getAttributeType(int index) {
if (first && index == 0) {
return "#TEXT";
}
return super.getAttributeType(index - 1);
}
public String getAttributeValue(int index) {
if (first && index == 0) {
String pfx = this.getNamespaceContext().getPrefix(typeQName.getNamespaceURI());
if (StringUtils.isEmpty(pfx)) {
return typeQName.getLocalPart();
}
return pfx + ":" + typeQName.getLocalPart();
}
return super.getAttributeValue(index);
}
public int next() throws XMLStreamException {
first = false;
return super.next();
}
public String getAttributeValue(String namespaceUri,
String localName) {
if (first
&& SOAPConstants.XSI_NS.equals(namespaceUri)
&& "type".equals(localName)) {
String pfx = this.getNamespaceContext().getPrefix(typeQName.getNamespaceURI());
if (StringUtils.isEmpty(pfx)) {
return typeQName.getLocalPart();
}
return pfx + ":" + typeQName.getLocalPart();
}
return super.getAttributeValue(namespaceUri, localName);
}
}
private static final Logger LOG = LogUtils.getLogger(JAXBEncoderDecoder.class);
private JAXBEncoderDecoder() {
}
public static void marshall(Marshaller marshaller,
Object elValue,
MessagePartInfo part,
Object source) {
try {
// The Marshaller.JAXB_FRAGMENT will tell the Marshaller not to
// generate the xml declaration.
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
} catch (javax.xml.bind.PropertyException e) {
// intentionally empty.
}
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()));
}
try {
Object mObj = elValue;
QName elName = null;
if (part != null) {
elName = part.getConcreteName();
}
if (null != elName) {
if (part != null && part.getXmlSchema() instanceof XmlSchemaElement) {
XmlSchemaElement el = (XmlSchemaElement)part.getXmlSchema();
if (mObj.getClass().isArray()
&& el.getSchemaType() instanceof XmlSchemaSimpleType
&& ((XmlSchemaSimpleType)el.getSchemaType()).
getContent() instanceof XmlSchemaSimpleTypeList) {
mObj = Arrays.asList((Object[])mObj);
writeObject(marshaller, source, newJAXBElement(elName, cls, mObj));
} else if (part.getMessageInfo().getOperation().isUnwrapped()
&& (mObj.getClass().isArray() || mObj instanceof List)
&& el.getMaxOccurs() != 1) {
writeArrayObject(marshaller,
source,
elName,
mObj);
} else {
writeObject(marshaller, source, newJAXBElement(elName, cls, mObj));
}
} else if (byte[].class == cls && part.getTypeQName() != null
&& part.getTypeQName().getLocalPart().equals("hexBinary")) {
mObj = new HexBinaryAdapter().marshal((byte[])mObj);
writeObject(marshaller, source, newJAXBElement(elName, String.class, mObj));
} else if (mObj instanceof JAXBElement) {
writeObject(marshaller, source, mObj);
} else if (marshaller.getSchema() != null) {
//force xsi:type so types can be validated instead of trying to
//use the RPC/lit element names that aren't in the schema
writeObject(marshaller, source, newJAXBElement(elName, Object.class, mObj));
} else {
writeObject(marshaller, source, newJAXBElement(elName, cls, mObj));
}
} else {
writeObject(marshaller, source, mObj);
}
} catch (Fault ex) {
throw ex;
} catch (Exception ex) {
if (ex instanceof javax.xml.bind.MarshalException) {
javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException)ex;
Message faultMessage = new Message("MARSHAL_ERROR", LOG, marshalEx.getLinkedException()
.getMessage());
throw new Fault(faultMessage, ex);
} else {
throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static JAXBElement> newJAXBElement(QName elName, Class> cls, Object mObj) {
return new JAXBElement(elName, cls, mObj);
}
//TODO: cache the JAXBRIContext
public static void marshalWithBridge(QName qname,
Class> cls,
Annotation anns[],
Set> ctxClasses,
Object elValue,
Object source, AttachmentMarshaller am) {
try {
JAXBUtils.BridgeWrapper bridge = JAXBUtils.createBridge(ctxClasses, qname, cls, anns);
if (source instanceof XMLStreamWriter) {
bridge.marshal(elValue, (XMLStreamWriter)source, am);
} else if (source instanceof OutputStream) {
//the namespace is missing when marshal the xsd:QName type
//to the OutputStream directly
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult s1 = new StreamResult(sw);
bridge.marshal(elValue, s1);
((OutputStream)source).write(sw.toString().getBytes());
} else if (source instanceof Node) {
bridge.marshal(elValue, (Node)source, am);
} else {
throw new Fault(new Message("UNKNOWN_SOURCE", LOG, source.getClass().getName()));
}
} catch (Exception ex) {
if (ex instanceof javax.xml.bind.MarshalException) {
javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException)ex;
Message faultMessage = new Message("MARSHAL_ERROR", LOG, marshalEx.getLinkedException()
.getMessage());
throw new Fault(faultMessage, ex);
} else {
throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
}
}
}
// TODO: cache the JAXBRIContext
public static Object unmarshalWithBridge(QName qname,
Class> cls,
Annotation anns[],
Set> ctxClasses,
Object source,
AttachmentUnmarshaller am) {
try {
JAXBUtils.BridgeWrapper bridge = JAXBUtils.createBridge(ctxClasses, qname, cls, anns);
if (source instanceof XMLStreamReader) {
//DOMUtils.writeXml(StaxUtils.read((XMLStreamReader)source), System.out);
return bridge.unmarshal((XMLStreamReader)source, am);
} else if (source instanceof InputStream) {
return bridge.unmarshal((InputStream)source);
} else if (source instanceof Node) {
return bridge.unmarshal((Node)source, am);
} else {
throw new Fault(new Message("UNKNOWN_SOURCE", LOG, source.getClass().getName()));
}
} catch (Exception ex) {
if (ex instanceof javax.xml.bind.MarshalException) {
javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException)ex;
Message faultMessage = new Message("MARSHAL_ERROR", LOG, marshalEx.getLinkedException()
.getMessage());
throw new Fault(faultMessage, ex);
} else {
throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
}
}
}
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();
SchemaInfo sch = part.getMessageInfo().getOperation().getInterface()
.getService().getSchema(namespace);
if (sch != null) {
if (!sch.isElementFormQualified()) {
namespace = null;
}
} else {
LOG.warning("Schema associated with " + namespace + " is null");
}
for (Field f : Utils.getFields(cls, accessType)) {
XmlAttribute at = f.getAnnotation(XmlAttribute.class);
if (at == null) {
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));
}
}
}
for (Method m : Utils.getGetters(cls, accessType)) {
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);
}
}
private static void writeArrayObject(Marshaller marshaller,
Object source,
QName mname,
Object mObj) throws Fault, JAXBException {
// Have to handle this ourselves.... which really
// sucks.... but what can we do?
if (mObj == null) {
return;
}
Object objArray;
Class> cls = null;
if (mObj instanceof List) {
List> l = (List>)mObj;
objArray = l.toArray(new Object[l.size()]);
cls = null;
} else {
objArray = mObj;
cls = objArray.getClass().getComponentType();
}
int len = Array.getLength(objArray);
for (int x = 0; x < len; x++) {
Object o = Array.get(objArray, x);
writeObject(marshaller, source,
newJAXBElement(mname, cls == null ? o.getClass() : cls, o));
}
}
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 = null;
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() == XMLStreamReader.START_ELEMENT) {
QName q = reader.getName();
String fieldName = q.getLocalPart();
Field f = Utils.getField(cls, accessType, fieldName);
if (f != null) {
Type type = f.getGenericType();
f.setAccessible(true);
if (JAXBSchemaInitializer.isArray(type)) {
Class> compType = JAXBSchemaInitializer.getArrayComponentType(type);
List