com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl Maven / Gradle / Ivy
Show all versions of jaxb-runtime Show documentation
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2014 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.bind.v2.model.impl;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.helpers.ValidationEventImpl;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import com.sun.istack.ByteArrayDataSource;
import com.sun.xml.bind.DatatypeConverterImpl;
import com.sun.xml.bind.WhiteSpaceProcessor;
import com.sun.xml.bind.api.AccessorException;
import com.sun.xml.bind.v2.TODO;
import com.sun.xml.bind.v2.WellKnownNamespace;
import com.sun.xml.bind.v2.model.runtime.RuntimeBuiltinLeafInfo;
import com.sun.xml.bind.v2.runtime.Name;
import com.sun.xml.bind.v2.runtime.Transducer;
import com.sun.xml.bind.v2.runtime.XMLSerializer;
import com.sun.xml.bind.v2.runtime.output.Pcdata;
import com.sun.xml.bind.v2.runtime.unmarshaller.Base64Data;
import com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext;
import com.sun.xml.bind.v2.util.ByteArrayOutputStreamEx;
import com.sun.xml.bind.v2.util.DataSourceSource;
import java.util.logging.Logger;
import com.sun.xml.bind.Util;
import java.util.logging.Level;
import org.xml.sax.SAXException;
/**
* {@link BuiltinLeafInfoImpl} with a support for runtime.
*
*
* In particular this class defines {@link Transducer}s for the built-in types.
*
* @author Kohsuke Kawaguchi
*/
public abstract class RuntimeBuiltinLeafInfoImpl extends BuiltinLeafInfoImpl
implements RuntimeBuiltinLeafInfo, Transducer {
private static final Logger logger = Util.getClassLogger();
private RuntimeBuiltinLeafInfoImpl(Class type, QName... typeNames) {
super(type, typeNames);
LEAVES.put(type,this);
}
public final Class getClazz() {
return (Class)getType();
}
public final Transducer getTransducer() {
return this;
}
public boolean useNamespace() {
return false;
}
public final boolean isDefault() {
return true;
}
public void declareNamespace(T o, XMLSerializer w) throws AccessorException {
}
public QName getTypeName(T instance) {
return null;
}
/**
* Those built-in types that print to {@link String}.
*/
private static abstract class StringImpl extends RuntimeBuiltinLeafInfoImpl {
protected StringImpl(Class type, QName... typeNames) {
super(type,typeNames);
}
public abstract String print(T o) throws AccessorException;
public void writeText(XMLSerializer w, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.text(print(o),fieldName);
}
public void writeLeafElement(XMLSerializer w, Name tagName, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.leafElement(tagName,print(o),fieldName);
}
}
/**
* Those built-in types that print to {@link Pcdata}.
*/
private static abstract class PcdataImpl extends RuntimeBuiltinLeafInfoImpl {
protected PcdataImpl(Class type, QName... typeNames) {
super(type,typeNames);
}
public abstract Pcdata print(T o) throws AccessorException;
public final void writeText(XMLSerializer w, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.text(print(o),fieldName);
}
public final void writeLeafElement(XMLSerializer w, Name tagName, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.leafElement(tagName,print(o),fieldName);
}
}
/**
* All instances of {@link RuntimeBuiltinLeafInfoImpl}s keyed by their type.
*/
public static final Map> LEAVES = new HashMap>();
private static QName createXS(String typeName) {
return new QName(WellKnownNamespace.XML_SCHEMA,typeName);
}
public static final RuntimeBuiltinLeafInfoImpl STRING;
private static final String DATE = "date";
/**
* List of all {@link RuntimeBuiltinLeafInfoImpl}s.
*
*
* This corresponds to the built-in Java classes that are specified to be
* handled differently than ordinary classes. See table 8-2 "Mapping of Standard Java classes".
*/
public static final List> builtinBeanInfos;
public static final String MAP_ANYURI_TO_URI = "mapAnyUriToUri";
public static final String USE_OLD_GMONTH_MAPPING = "jaxb.ri.useOldGmonthMapping";
static {
QName[] qnames = (System.getProperty(MAP_ANYURI_TO_URI) == null) ? new QName[] {
createXS("string"),
createXS("anySimpleType"),
createXS("normalizedString"),
createXS("anyURI"),
createXS("token"),
createXS("language"),
createXS("Name"),
createXS("NCName"),
createXS("NMTOKEN"),
createXS("ENTITY")}
:
new QName[] {
createXS("string"),
createXS("anySimpleType"),
createXS("normalizedString"),
createXS("token"),
createXS("language"),
createXS("Name"),
createXS("NCName"),
createXS("NMTOKEN"),
createXS("ENTITY")};
STRING = new StringImplImpl(String.class, qnames);
ArrayList> secondaryList = new ArrayList>();
/*
There are cases where more than one Java classes map to the same XML type.
But when we see the same XML type in an incoming document, we only pick
one of those Java classes to unmarshal. This Java class is called 'primary'.
The rest are called 'secondary'.
Currently we lack the proper infrastructure to handle those nicely.
For now, we rely on a hack.
We define secondary mappings first, then primary ones later. GrammarInfo
builds a map from type name to BeanInfo. By defining primary ones later,
those primary bindings will overwrite the secondary ones.
*/
/*
secondary bindings
*/
secondaryList.add(
new StringImpl(Character.class, createXS("unsignedShort")) {
public Character parse(CharSequence text) {
// TODO.checkSpec("default mapping for char is not defined yet");
return (char)DatatypeConverterImpl._parseInt(text);
}
public String print(Character v) {
return Integer.toString(v);
}
});
secondaryList.add(
new StringImpl(Calendar.class, DatatypeConstants.DATETIME) {
public Calendar parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString());
}
public String print(Calendar v) {
return DatatypeConverterImpl._printDateTime(v);
}
});
secondaryList.add(
new StringImpl(GregorianCalendar.class, DatatypeConstants.DATETIME) {
public GregorianCalendar parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString());
}
public String print(GregorianCalendar v) {
return DatatypeConverterImpl._printDateTime(v);
}
});
secondaryList.add(
new StringImpl(Date.class, DatatypeConstants.DATETIME) {
public Date parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString()).getTime();
}
public String print(Date v) {
XMLSerializer xs = XMLSerializer.getInstance();
QName type = xs.getSchemaType();
GregorianCalendar cal = new GregorianCalendar(0,0,0);
cal.setTime(v);
if ((type != null) && (WellKnownNamespace.XML_SCHEMA.equals(type.getNamespaceURI())) &&
DATE.equals(type.getLocalPart())) {
return DatatypeConverterImpl._printDate(cal);
} else {
return DatatypeConverterImpl._printDateTime(cal);
}
}
});
secondaryList.add(
new StringImpl(File.class, createXS("string")) {
public File parse(CharSequence text) {
return new File(WhiteSpaceProcessor.trim(text).toString());
}
public String print(File v) {
return v.getPath();
}
});
secondaryList.add(
new StringImpl(URL.class, createXS("anyURI")) {
public URL parse(CharSequence text) throws SAXException {
TODO.checkSpec("JSR222 Issue #42");
try {
return new URL(WhiteSpaceProcessor.trim(text).toString());
} catch (MalformedURLException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
public String print(URL v) {
return v.toExternalForm();
}
});
if (System.getProperty(MAP_ANYURI_TO_URI) == null) {
secondaryList.add(
new StringImpl(URI.class, createXS("string")) {
public URI parse(CharSequence text) throws SAXException {
try {
return new URI(text.toString());
} catch (URISyntaxException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
public String print(URI v) {
return v.toString();
}
});
}
secondaryList.add(
new StringImpl(Class.class, createXS("string")) {
public Class parse(CharSequence text) throws SAXException {
TODO.checkSpec("JSR222 Issue #42");
try {
String name = WhiteSpaceProcessor.trim(text).toString();
ClassLoader cl = UnmarshallingContext.getInstance().classLoader;
if(cl==null)
cl = Thread.currentThread().getContextClassLoader();
if(cl!=null)
return cl.loadClass(name);
else
return Class.forName(name);
} catch (ClassNotFoundException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
public String print(Class v) {
return v.getName();
}
});
/*
classes that map to base64Binary / MTOM related classes.
a part of the secondary binding.
*/
secondaryList.add(
new PcdataImpl(Image.class, createXS("base64Binary")) {
public Image parse(CharSequence text) throws SAXException {
try {
InputStream is;
if(text instanceof Base64Data)
is = ((Base64Data)text).getInputStream();
else
is = new ByteArrayInputStream(decodeBase64(text)); // TODO: buffering is inefficient
// technically we should check the MIME type here, but
// normally images can be content-sniffed.
// so the MIME type check will only make us slower and draconian, both of which
// JAXB 2.0 isn't interested.
try {
return ImageIO.read(is);
} finally {
is.close();
}
} catch (IOException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
private BufferedImage convertToBufferedImage(Image image) throws IOException {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
} else {
MediaTracker tracker = new MediaTracker(new Component(){}); // not sure if this is the right thing to do.
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
throw new IOException(e.getMessage());
}
BufferedImage bufImage = new BufferedImage(
image.getWidth(null),
image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufImage.createGraphics();
g.drawImage(image, 0, 0, null);
return bufImage;
}
}
public Base64Data print(Image v) {
ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
XMLSerializer xs = XMLSerializer.getInstance();
String mimeType = xs.getXMIMEContentType();
if(mimeType==null || mimeType.startsWith("image/*"))
// because PNG is lossless, it's a good default
//
// mime type can be a range, in which case we can't just pass that
// to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
// the default of PNG. Not sure if this is complete.
mimeType = "image/png";
try {
Iterator itr = ImageIO.getImageWritersByMIMEType(mimeType);
if(itr.hasNext()) {
ImageWriter w = itr.next();
ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
w.setOutput(os);
w.write(convertToBufferedImage(v));
os.close();
w.dispose();
} else {
// no encoder
xs.handleEvent(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.NO_IMAGE_WRITER.format(mimeType),
xs.getCurrentLocation(null) ));
// TODO: proper error reporting
throw new RuntimeException("no encoder for MIME type "+mimeType);
}
} catch (IOException e) {
xs.handleError(e);
// TODO: proper error reporting
throw new RuntimeException(e);
}
Base64Data bd = new Base64Data();
imageData.set(bd,mimeType);
return bd;
}
});
secondaryList.add(
new PcdataImpl(DataHandler.class, createXS("base64Binary")) {
public DataHandler parse(CharSequence text) {
if(text instanceof Base64Data)
return ((Base64Data)text).getDataHandler();
else
return new DataHandler(new ByteArrayDataSource(decodeBase64(text),
UnmarshallingContext.getInstance().getXMIMEContentType()));
}
public Base64Data print(DataHandler v) {
Base64Data bd = new Base64Data();
bd.set(v);
return bd;
}
});
secondaryList.add(
new PcdataImpl