org.glassfish.jaxb.runtime.v2.model.impl.RuntimeBuiltinLeafInfoImpl Maven / Gradle / Ivy
/*
* Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package cn.lzgabel.jaxb.runtime.v2.model.impl;
import com.sun.istack.ByteArrayDataSource;
import cn.lzgabel.jaxb.core.Utils;
import cn.lzgabel.jaxb.core.WhiteSpaceProcessor;
import cn.lzgabel.jaxb.runtime.DatatypeConverterImpl;
import cn.lzgabel.jaxb.runtime.api.AccessorException;
import cn.lzgabel.jaxb.core.v2.TODO;
import cn.lzgabel.jaxb.core.v2.WellKnownNamespace;
import cn.lzgabel.jaxb.runtime.v2.model.runtime.RuntimeBuiltinLeafInfo;
import cn.lzgabel.jaxb.runtime.v2.runtime.Name;
import cn.lzgabel.jaxb.runtime.v2.runtime.Transducer;
import cn.lzgabel.jaxb.runtime.v2.runtime.XMLSerializer;
import cn.lzgabel.jaxb.runtime.v2.runtime.output.Pcdata;
import cn.lzgabel.jaxb.runtime.v2.runtime.unmarshaller.Base64Data;
import cn.lzgabel.jaxb.runtime.v2.runtime.unmarshaller.UnmarshallingContext;
import cn.lzgabel.jaxb.runtime.v2.util.ByteArrayOutputStreamEx;
import cn.lzgabel.jaxb.runtime.v2.util.DataSourceSource;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.MimeType;
import jakarta.activation.MimeTypeParseException;
import jakarta.xml.bind.ValidationEvent;
import jakarta.xml.bind.helpers.ValidationEventImpl;
import org.xml.sax.SAXException;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.xml.XMLConstants;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
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.List;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@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 = Utils.getClassLogger();
private RuntimeBuiltinLeafInfoImpl(Class type, QName... typeNames) {
super(type, typeNames);
LEAVES.put(type,this);
}
@Override
public final Class getClazz() {
return (Class)getType();
}
@Override
public final Transducer getTransducer() {
return this;
}
@Override
public boolean useNamespace() {
return false;
}
@Override
public void declareNamespace(T o, XMLSerializer w) throws AccessorException {
}
@Override
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);
}
@Override
public abstract String print(T o) throws AccessorException;
@Override
public void writeText(XMLSerializer w, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.text(print(o),fieldName);
}
@Override
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);
}
@Override
public abstract Pcdata print(T o) throws AccessorException;
@Override
public final void writeText(XMLSerializer w, T o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
w.text(print(o),fieldName);
}
@Override
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(XMLConstants.W3C_XML_SCHEMA_NS_URI,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 {
String MAP_ANYURI_TO_URI_VALUE = AccessController.doPrivileged(
new PrivilegedAction() {
@Override
public String run() {
return System.getProperty(MAP_ANYURI_TO_URI);
}
}
);
QName[] qnames = (MAP_ANYURI_TO_URI_VALUE == 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")) {
@Override
public Character parse(CharSequence text) {
// TODO.checkSpec("default mapping for char is not defined yet");
return (char) DatatypeConverterImpl._parseInt(text);
}
@Override
public String print(Character v) {
return Integer.toString(v);
}
});
secondaryList.add(
new StringImpl(Calendar.class, DatatypeConstants.DATETIME) {
@Override
public Calendar parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString());
}
@Override
public String print(Calendar v) {
return DatatypeConverterImpl._printDateTime(v);
}
});
secondaryList.add(
new StringImpl(GregorianCalendar.class, DatatypeConstants.DATETIME) {
@Override
public GregorianCalendar parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString());
}
@Override
public String print(GregorianCalendar v) {
return DatatypeConverterImpl._printDateTime(v);
}
});
secondaryList.add(
new StringImpl(Date.class, DatatypeConstants.DATETIME) {
@Override
public Date parse(CharSequence text) {
return DatatypeConverterImpl._parseDateTime(text.toString()).getTime();
}
@Override
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) && (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(type.getNamespaceURI())) &&
DATE.equals(type.getLocalPart())) {
return DatatypeConverterImpl._printDate(cal);
} else {
return DatatypeConverterImpl._printDateTime(cal);
}
}
});
secondaryList.add(
new StringImpl(File.class, createXS("string")) {
@Override
public File parse(CharSequence text) {
return new File(WhiteSpaceProcessor.trim(text).toString());
}
@Override
public String print(File v) {
return v.getPath();
}
});
secondaryList.add(
new StringImpl(URL.class, createXS("anyURI")) {
@Override
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;
}
}
@Override
public String print(URL v) {
return v.toExternalForm();
}
});
if (MAP_ANYURI_TO_URI_VALUE == null) {
secondaryList.add(
new StringImpl(URI.class, createXS("string")) {
@Override
public URI parse(CharSequence text) throws SAXException {
try {
return new URI(text.toString());
} catch (URISyntaxException e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
}
}
@Override
public String print(URI v) {
return v.toString();
}
});
}
secondaryList.add(
new StringImpl(Class.class, createXS("string")) {
@Override
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;
}
}
@Override
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")) {
@Override
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;
}
}
@Override
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")) {
@Override
public DataHandler parse(CharSequence text) {
if(text instanceof Base64Data)
return ((Base64Data)text).getDataHandler();
else
return new DataHandler(new ByteArrayDataSource(decodeBase64(text),
UnmarshallingContext.getInstance().getXMIMEContentType()));
}
@Override
public Base64Data print(DataHandler v) {
Base64Data bd = new Base64Data();
bd.set(v);
return bd;
}
});
secondaryList.add(
new PcdataImpl