feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,421 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import org.w3c.dom.Node;
import javax.xml.validation.Schema;
/**
* Enable synchronization between XML infoset nodes and JAXB objects
* representing same XML document.
*
* <p>
* An instance of this class maintains the association between XML nodes of
* an infoset preserving view and a JAXB representation of an XML document.
* Navigation between the two views is provided by the methods
* {@link #getXMLNode(Object)} and {@link #getJAXBNode(Object)}.
*
* <p>
* Modifications can be made to either the infoset preserving view or the
* JAXB representation of the document while the other view remains
* unmodified. The binder is able to synchronize the changes made in the
* modified view back into the other view using the appropriate
* Binder update methods, {@link #updateXML(Object, Object)} or
* {@link #updateJAXB(Object)}.
*
* <p>
* A typical usage scenario is the following:
* <ul>
* <li>load XML document into an XML infoset representation</li>
* <li>{@link #unmarshal(Object)} XML infoset view to JAXB view.
* (Note to conserve resources, it is possible to only unmarshal a
* subtree of the XML infoset view to the JAXB view.)</li>
* <li>application access/updates JAXB view of XML document.</li>
* <li>{@link #updateXML(Object)} synchronizes modifications to JAXB view
* back into the XML infoset view. Update operation preserves as
* much of original XML infoset as possible (i.e. comments, PI, ...)</li>
* </ul>
*
* <p>
* A Binder instance is created using the factory method
* {@link JAXBContext#createBinder()} or {@link JAXBContext#createBinder(Class)}.
*
* <p>
* The template parameter, <code>XmlNode</code>, is the
* root interface/class for the XML infoset preserving representation.
* A Binder implementation is required to minimally support
* an <code>XmlNode</code> value of <code>org.w3c.dom.Node.class</code>.
* A Binder implementation can support alternative XML infoset
* preserving representations.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* Joseph Fialli
*
* @since JAXB 2.0
*/
public abstract class Binder<XmlNode> {
/**
* Unmarshal XML infoset view to a JAXB object tree.
*
* <p>
* This method is similar to {@link Unmarshaller#unmarshal(Node)}
* with the addition of maintaining the association between XML nodes
* and the produced JAXB objects, enabling future update operations,
* {@link #updateXML(Object, Object)} or {@link #updateJAXB(Object)}.
*
* <p>
* When {@link #getSchema()} is non-null, <code>xmlNode</code>
* and its descendants is validated during this operation.
*
* <p>
* This method throws {@link UnmarshalException} when the Binder's
* {@link JAXBContext} does not have a mapping for the XML element name
* or the type, specifiable via <tt>@xsi:type</tt>, of <tt>xmlNode</tt>
* to a JAXB mapped class. The method {@link #unmarshal(Object, Class)}
* enables an application to specify the JAXB mapped class that
* the <tt>xmlNode</tt> should be mapped to.
*
* @param xmlNode
* the document/element to unmarshal XML data from.
*
* @return
* the newly created root object of the JAXB object tree.
*
* @throws JAXBException
* If any unexpected errors occur while unmarshalling
* @throws UnmarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Binder</tt> is unable to perform the XML to Java
* binding.
* @throws IllegalArgumentException
* If the node parameter is null
*/
public abstract Object unmarshal( XmlNode xmlNode ) throws JAXBException;
/**
* Unmarshal XML root element by provided <tt>declaredType</tt>
* to a JAXB object tree.
*
* <p>
* Implements <a href="Unmarshaller.html#unmarshalByDeclaredType">Unmarshal by Declared Type</a>
*
* <p>
* This method is similar to {@link Unmarshaller#unmarshal(Node, Class)}
* with the addition of maintaining the association between XML nodes
* and the produced JAXB objects, enabling future update operations,
* {@link #updateXML(Object, Object)} or {@link #updateJAXB(Object)}.
*
* <p>
* When {@link #getSchema()} is non-null, <code>xmlNode</code>
* and its descendants is validated during this operation.
*
* @param xmlNode
* the document/element to unmarshal XML data from.
* @param declaredType
* appropriate JAXB mapped class to hold <tt>node</tt>'s XML data.
*
* @return
* <a href="JAXBElement.html">JAXB Element</a> representation
* of <tt>node</tt>
*
* @throws JAXBException
* If any unexpected errors occur while unmarshalling
* @throws UnmarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Binder</tt> is unable to perform the XML to Java
* binding.
* @throws IllegalArgumentException
* If any of the input parameters are null
* @since JAXB2.0
*/
public abstract <T> JAXBElement<T>
unmarshal( XmlNode xmlNode, Class<T> declaredType )
throws JAXBException;
/**
* Marshal a JAXB object tree to a new XML document.
*
* <p>
* This method is similar to {@link Marshaller#marshal(Object, Node)}
* with the addition of maintaining the association between JAXB objects
* and the produced XML nodes,
* enabling future update operations such as
* {@link #updateXML(Object, Object)} or {@link #updateJAXB(Object)}.
*
* <p>
* When {@link #getSchema()} is non-null, the marshalled
* xml content is validated during this operation.
*
* @param jaxbObject
* The content tree to be marshalled.
* @param xmlNode
* The parameter must be a Node that accepts children.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Binder</tt> is unable to marshal <tt>jaxbObject</tt> (or any
* object reachable from <tt>jaxbObject</tt>).
*
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public abstract void marshal( Object jaxbObject, XmlNode xmlNode ) throws JAXBException;
/**
* Gets the XML element associated with the given JAXB object.
*
* <p>
* Once a JAXB object tree is associated with an XML fragment,
* this method enables navigation between the two trees.
*
* <p>
* An association between an XML element and a JAXB object is
* established by the bind methods and the update methods.
* Note that this association is partial; not all XML elements
* have associated JAXB objects, and not all JAXB objects have
* associated XML elements.
*
* @param jaxbObject An instance that is reachable from a prior
* call to a bind or update method that returned
* a JAXB object tree.
*
* @return
* null if the specified JAXB object is not known to this
* {@link Binder}, or if it is not associated with an
* XML element.
*
* @throws IllegalArgumentException
* If the jaxbObject parameter is null
*/
public abstract XmlNode getXMLNode( Object jaxbObject );
/**
* Gets the JAXB object associated with the given XML element.
*
* <p>
* Once a JAXB object tree is associated with an XML fragment,
* this method enables navigation between the two trees.
*
* <p>
* An association between an XML element and a JAXB object is
* established by the unmarshal, marshal and update methods.
* Note that this association is partial; not all XML elements
* have associated JAXB objects, and not all JAXB objects have
* associated XML elements.
*
* @return
* null if the specified XML node is not known to this
* {@link Binder}, or if it is not associated with a
* JAXB object.
*
* @throws IllegalArgumentException
* If the node parameter is null
*/
public abstract Object getJAXBNode( XmlNode xmlNode );
/**
* Takes an JAXB object and updates
* its associated XML node and its descendants.
*
* <p>
* This is a convenience method of:
* <pre>
* updateXML( jaxbObject, getXMLNode(jaxbObject));
* </pre>
*
* @throws JAXBException
* If any unexpected problem occurs updating corresponding XML content.
* @throws IllegalArgumentException
* If the jaxbObject parameter is null
*/
public abstract XmlNode updateXML( Object jaxbObject ) throws JAXBException;
/**
* Changes in JAXB object tree are updated in its associated XML parse tree.
*
* <p>
* This operation can be thought of as an "in-place" marshalling.
* The difference is that instead of creating a whole new XML tree,
* this operation updates an existing tree while trying to preserve
* the XML as much as possible.
*
* <p>
* For example, unknown elements/attributes in XML that were not bound
* to JAXB will be left untouched (whereas a marshalling operation
* would create a new tree that doesn't contain any of those.)
*
* <p>
* As a side-effect, this operation updates the association between
* XML nodes and JAXB objects.
*
* @param jaxbObject root of potentially modified JAXB object tree
* @param xmlNode root of update target XML parse tree
*
* @return
* Returns the updated XML node. Typically, this is the same
* node you passed in as <i>xmlNode</i>, but it maybe
* a different object, for example when the tag name of the object
* has changed.
*
* @throws JAXBException
* If any unexpected problem occurs updating corresponding XML content.
* @throws IllegalArgumentException
* If any of the input parameters are null
*/
public abstract XmlNode updateXML( Object jaxbObject, XmlNode xmlNode ) throws JAXBException;
/**
* Takes an XML node and updates its associated JAXB object and its descendants.
*
* <p>
* This operation can be thought of as an "in-place" unmarshalling.
* The difference is that instead of creating a whole new JAXB tree,
* this operation updates an existing tree, reusing as much JAXB objects
* as possible.
*
* <p>
* As a side-effect, this operation updates the association between
* XML nodes and JAXB objects.
*
* @return
* Returns the updated JAXB object. Typically, this is the same
* object that was returned from earlier
* {@link #marshal(Object,Object)} or
* {@link #updateJAXB(Object)} method invocation,
* but it maybe
* a different object, for example when the name of the XML
* element has changed.
*
* @throws JAXBException
* If any unexpected problem occurs updating corresponding JAXB mapped content.
* @throws IllegalArgumentException
* If node parameter is null
*/
public abstract Object updateJAXB( XmlNode xmlNode ) throws JAXBException;
/**
* Specifies whether marshal, unmarshal and update methods
* performs validation on their XML content.
*
* @param schema set to null to disable validation.
*
* @see Unmarshaller#setSchema(Schema)
*/
public abstract void setSchema( Schema schema );
/**
* Gets the last {@link Schema} object (including null) set by the
* {@link #setSchema(Schema)} method.
*
* @return the Schema object for validation or null if not present
*/
public abstract Schema getSchema();
/**
* Allow an application to register a <tt>ValidationEventHandler</tt>.
* <p>
* The <tt>ValidationEventHandler</tt> will be called by the JAXB Provider
* if any validation errors are encountered during calls to any of the
* Binder unmarshal, marshal and update methods.
*
* <p>
* Calling this method with a null parameter will cause the Binder
* to revert back to the default default event handler.
*
* @param handler the validation event handler
* @throws JAXBException if an error was encountered while setting the
* event handler
*/
public abstract void setEventHandler( ValidationEventHandler handler ) throws JAXBException;
/**
* Return the current event handler or the default event handler if one
* hasn't been set.
*
* @return the current ValidationEventHandler or the default event handler
* if it hasn't been set
* @throws JAXBException if an error was encountered while getting the
* current event handler
*/
public abstract ValidationEventHandler getEventHandler() throws JAXBException;
/**
*
* Set the particular property in the underlying implementation of
* <tt>Binder</tt>. This method can only be used to set one of
* the standard JAXB defined unmarshal/marshal properties
* or a provider specific property for binder, unmarshal or marshal.
* Attempting to set an undefined property will result in
* a PropertyException being thrown. See
* <a href="Unmarshaller.html#supportedProps">Supported Unmarshal Properties</a>
* and
* <a href="Marshaller.html#supportedProps">Supported Marshal Properties</a>.
*
* @param name the name of the property to be set. This value can either
* be specified using one of the constant fields or a user
* supplied string.
* @param value the value of the property to be set
*
* @throws PropertyException when there is an error processing the given
* property or value
* @throws IllegalArgumentException
* If the name parameter is null
*/
abstract public void setProperty( String name, Object value ) throws PropertyException;
/**
* Get the particular property in the underlying implementation of
* <tt>Binder</tt>. This method can only
* be used to get one of
* the standard JAXB defined unmarshal/marshal properties
* or a provider specific property for binder, unmarshal or marshal.
* Attempting to get an undefined property will result in
* a PropertyException being thrown. See
* <a href="Unmarshaller.html#supportedProps">Supported Unmarshal Properties</a>
* and
* <a href="Marshaller.html#supportedProps">Supported Marshal Properties</a>.
*
* @param name the name of the property to retrieve
* @return the value of the requested property
*
* @throws PropertyException
* when there is an error retrieving the given property or value
* property name
* @throws IllegalArgumentException
* If the name parameter is null
*/
abstract public Object getProperty( String name ) throws PropertyException;
}

View File

@@ -0,0 +1,629 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import java.util.Iterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.security.AccessController;
import static javax.xml.bind.JAXBContext.JAXB_CONTEXT_FACTORY;
/**
* This class is package private and therefore is not exposed as part of the
* JAXB API.
*
* This code is designed to implement the JAXB 1.0 spec pluggability feature
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see JAXBContext
*/
class ContextFinder {
private static final Logger logger;
static {
logger = Logger.getLogger("javax.xml.bind");
try {
if (AccessController.doPrivileged(new GetPropertyAction("jaxb.debug")) != null) {
// disconnect the logger from a bigger framework (if any)
// and take the matters into our own hands
logger.setUseParentHandlers(false);
logger.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
logger.addHandler(handler);
} else {
// don't change the setting of this logger
// to honor what other frameworks
// have done on configurations.
}
} catch(Throwable t) {
// just to be extra safe. in particular System.getProperty may throw
// SecurityException.
}
}
/**
* If the {@link InvocationTargetException} wraps an exception that shouldn't be wrapped,
* throw the wrapped exception.
*/
private static void handleInvocationTargetException(InvocationTargetException x) throws JAXBException {
Throwable t = x.getTargetException();
if( t != null ) {
if( t instanceof JAXBException )
// one of our exceptions, just re-throw
throw (JAXBException)t;
if( t instanceof RuntimeException )
// avoid wrapping exceptions unnecessarily
throw (RuntimeException)t;
if( t instanceof Error )
throw (Error)t;
}
}
/**
* Determine if two types (JAXBContext in this case) will generate a ClassCastException.
*
* For example, (targetType)originalType
*
* @param originalType
* The Class object of the type being cast
* @param targetType
* The Class object of the type that is being cast to
* @return JAXBException to be thrown.
*/
private static JAXBException handleClassCastException(Class originalType, Class targetType) {
final URL targetTypeURL = which(targetType);
return new JAXBException(Messages.format(Messages.ILLEGAL_CAST,
// we don't care where the impl class is, we want to know where JAXBContext lives in the impl
// class' ClassLoader
getClassClassLoader(originalType).getResource("javax/xml/bind/JAXBContext.class"),
targetTypeURL));
}
/**
* Create an instance of a class using the specified ClassLoader
*/
static JAXBContext newInstance( String contextPath,
String className,
ClassLoader classLoader,
Map properties )
throws JAXBException {
try {
Class spFactory = safeLoadClass(className,classLoader);
return newInstance(contextPath, spFactory, classLoader, properties);
} catch (ClassNotFoundException x) {
throw new JAXBException(
Messages.format( Messages.PROVIDER_NOT_FOUND, className ),
x);
} catch (RuntimeException x) {
// avoid wrapping RuntimeException to JAXBException,
// because it indicates a bug in this code.
throw x;
} catch (Exception x) {
// can't catch JAXBException because the method is hidden behind
// reflection. Root element collisions detected in the call to
// createContext() are reported as JAXBExceptions - just re-throw it
// some other type of exception - just wrap it
throw new JAXBException(
Messages.format( Messages.COULD_NOT_INSTANTIATE, className, x ),
x);
}
}
static JAXBContext newInstance( String contextPath,
Class spFactory,
ClassLoader classLoader,
Map properties )
throws JAXBException
{
try {
/*
* javax.xml.bind.context.factory points to a class which has a
* static method called 'createContext' that
* returns a javax.xml.JAXBContext.
*/
Object context = null;
// first check the method that takes Map as the third parameter.
// this is added in 2.0.
try {
Method m = spFactory.getMethod("createContext",String.class,ClassLoader.class,Map.class);
// any failure in invoking this method would be considered fatal
context = m.invoke(null,contextPath,classLoader,properties);
} catch (NoSuchMethodException e) {
// it's not an error for the provider not to have this method.
}
if(context==null) {
// try the old method that doesn't take properties. compatible with 1.0.
// it is an error for an implementation not to have both forms of the createContext method.
Method m = spFactory.getMethod("createContext",String.class,ClassLoader.class);
// any failure in invoking this method would be considered fatal
context = m.invoke(null,contextPath,classLoader);
}
if(!(context instanceof JAXBContext)) {
// the cast would fail, so generate an exception with a nice message
throw handleClassCastException(context.getClass(), JAXBContext.class);
}
return (JAXBContext)context;
} catch (InvocationTargetException x) {
handleInvocationTargetException(x);
// for other exceptions, wrap the internal target exception
// with a JAXBException
Throwable e = x;
if(x.getTargetException()!=null)
e = x.getTargetException();
throw new JAXBException( Messages.format( Messages.COULD_NOT_INSTANTIATE, spFactory, e ), e );
} catch (RuntimeException x) {
// avoid wrapping RuntimeException to JAXBException,
// because it indicates a bug in this code.
throw x;
} catch (Exception x) {
// can't catch JAXBException because the method is hidden behind
// reflection. Root element collisions detected in the call to
// createContext() are reported as JAXBExceptions - just re-throw it
// some other type of exception - just wrap it
throw new JAXBException(
Messages.format( Messages.COULD_NOT_INSTANTIATE, spFactory, x ),
x);
}
}
/**
* Create an instance of a class using the thread context ClassLoader
*/
static JAXBContext newInstance(
Class[] classes,
Map properties,
String className) throws JAXBException {
ClassLoader cl = getContextClassLoader();
Class spi;
try {
spi = safeLoadClass(className,cl);
} catch (ClassNotFoundException e) {
throw new JAXBException(e);
}
if(logger.isLoggable(Level.FINE)) {
// extra check to avoid costly which operation if not logged
logger.log(Level.FINE, "loaded {0} from {1}", new Object[]{className, which(spi)});
}
return newInstance(classes, properties, spi);
}
static JAXBContext newInstance(Class[] classes,
Map properties,
Class spFactory) throws JAXBException {
Method m;
try {
m = spFactory.getMethod("createContext", Class[].class, Map.class);
} catch (NoSuchMethodException e) {
throw new JAXBException(e);
}
try {
Object context = m.invoke(null, classes, properties);
if(!(context instanceof JAXBContext)) {
// the cast would fail, so generate an exception with a nice message
throw handleClassCastException(context.getClass(), JAXBContext.class);
}
return (JAXBContext)context;
} catch (IllegalAccessException e) {
throw new JAXBException(e);
} catch (InvocationTargetException e) {
handleInvocationTargetException(e);
Throwable x = e;
if (e.getTargetException() != null)
x = e.getTargetException();
throw new JAXBException(x);
}
}
static JAXBContext find(String factoryId, String contextPath, ClassLoader classLoader, Map properties ) throws JAXBException {
// TODO: do we want/need another layer of searching in $java.home/lib/jaxb.properties like JAXP?
final String jaxbContextFQCN = JAXBContext.class.getName();
// search context path for jaxb.properties first
StringBuilder propFileName;
StringTokenizer packages = new StringTokenizer( contextPath, ":" );
String factoryClassName;
if(!packages.hasMoreTokens())
// no context is specified
throw new JAXBException(Messages.format(Messages.NO_PACKAGE_IN_CONTEXTPATH));
logger.fine("Searching jaxb.properties");
while( packages.hasMoreTokens() ) {
String packageName = packages.nextToken(":").replace('.','/');
// com.acme.foo - > com/acme/foo/jaxb.properties
propFileName = new StringBuilder().append(packageName).append("/jaxb.properties");
Properties props = loadJAXBProperties( classLoader, propFileName.toString() );
if (props != null) {
if (props.containsKey(factoryId)) {
factoryClassName = props.getProperty(factoryId);
return newInstance( contextPath, factoryClassName, classLoader, properties );
} else {
throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, factoryId));
}
}
}
logger.fine("Searching the system property");
// search for a system property second (javax.xml.bind.JAXBContext)
factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY));
if( factoryClassName != null ) {
return newInstance( contextPath, factoryClassName, classLoader, properties );
} else { // leave this here to assure compatibility
factoryClassName = AccessController.doPrivileged(new GetPropertyAction(jaxbContextFQCN));
if( factoryClassName != null ) {
return newInstance( contextPath, factoryClassName, classLoader, properties );
}
}
// OSGi search
Class jaxbContext = lookupJaxbContextUsingOsgiServiceLoader();
if (jaxbContext != null) {
logger.fine("OSGi environment detected");
return newInstance(contextPath, jaxbContext, classLoader, properties);
}
logger.fine("Searching META-INF/services");
// search META-INF services next
BufferedReader r = null;
try {
final StringBuilder resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN);
final InputStream resourceStream =
classLoader.getResourceAsStream(resource.toString());
if (resourceStream != null) {
r = new BufferedReader(new InputStreamReader(resourceStream, "UTF-8"));
factoryClassName = r.readLine();
if (factoryClassName != null) {
factoryClassName = factoryClassName.trim();
}
r.close();
return newInstance(contextPath, factoryClassName, classLoader, properties);
} else {
logger.log(Level.FINE, "Unable to load:{0}", resource.toString());
}
} catch (UnsupportedEncodingException e) {
// should never happen
throw new JAXBException(e);
} catch (IOException e) {
throw new JAXBException(e);
} finally {
try {
if (r != null) {
r.close();
}
} catch (IOException ex) {
Logger.getLogger(ContextFinder.class.getName()).log(Level.SEVERE, null, ex);
}
}
// else no provider found
logger.fine("Trying to create the platform default provider");
return newInstance(contextPath, PLATFORM_DEFAULT_FACTORY_CLASS, classLoader, properties);
}
static JAXBContext find( Class[] classes, Map properties ) throws JAXBException {
final String jaxbContextFQCN = JAXBContext.class.getName();
String factoryClassName;
// search for jaxb.properties in the class loader of each class first
for (final Class c : classes) {
// this classloader is used only to load jaxb.properties, so doing this should be safe.
ClassLoader classLoader = getClassClassLoader(c);
Package pkg = c.getPackage();
if(pkg==null)
continue; // this is possible for primitives, arrays, and classes that are loaded by poorly implemented ClassLoaders
String packageName = pkg.getName().replace('.', '/');
// TODO: do we want to optimize away searching the same package? org.Foo, org.Bar, com.Baz
// classes from the same package might come from different class loades, so it might be a bad idea
// TODO: it's easier to look things up from the class
// c.getResourceAsStream("jaxb.properties");
// build the resource name and use the property loader code
String resourceName = packageName+"/jaxb.properties";
logger.log(Level.FINE, "Trying to locate {0}", resourceName);
Properties props = loadJAXBProperties(classLoader, resourceName);
if (props == null) {
logger.fine(" not found");
} else {
logger.fine(" found");
if (props.containsKey(JAXB_CONTEXT_FACTORY)) {
// trim() seems redundant, but adding to satisfy customer complaint
factoryClassName = props.getProperty(JAXB_CONTEXT_FACTORY).trim();
return newInstance(classes, properties, factoryClassName);
} else {
throw new JAXBException(Messages.format(Messages.MISSING_PROPERTY, packageName, JAXB_CONTEXT_FACTORY));
}
}
}
// search for a system property second (javax.xml.bind.JAXBContext)
logger.log(Level.FINE, "Checking system property {0}", JAXBContext.JAXB_CONTEXT_FACTORY);
factoryClassName = AccessController.doPrivileged(new GetPropertyAction(JAXBContext.JAXB_CONTEXT_FACTORY));
if (factoryClassName != null) {
logger.log(Level.FINE, " found {0}", factoryClassName);
return newInstance( classes, properties, factoryClassName );
} else { // leave it here for compatibility reasons
logger.fine(" not found");
logger.log(Level.FINE, "Checking system property {0}", jaxbContextFQCN);
factoryClassName = AccessController.doPrivileged(new GetPropertyAction(jaxbContextFQCN));
if (factoryClassName != null) {
logger.log(Level.FINE, " found {0}", factoryClassName);
return newInstance( classes, properties, factoryClassName );
} else {
logger.fine(" not found");
}
}
// OSGi search
Class jaxbContext = lookupJaxbContextUsingOsgiServiceLoader();
if (jaxbContext != null) {
logger.fine("OSGi environment detected");
return newInstance(classes, properties, jaxbContext);
}
// search META-INF services next
logger.fine("Checking META-INF/services");
BufferedReader r = null;
try {
final String resource = new StringBuilder("META-INF/services/").append(jaxbContextFQCN).toString();
ClassLoader classLoader = getContextClassLoader();
URL resourceURL;
if(classLoader==null)
resourceURL = ClassLoader.getSystemResource(resource);
else
resourceURL = classLoader.getResource(resource);
if (resourceURL != null) {
logger.log(Level.FINE, "Reading {0}", resourceURL);
r = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "UTF-8"));
factoryClassName = r.readLine();
if (factoryClassName != null) {
factoryClassName = factoryClassName.trim();
}
return newInstance(classes, properties, factoryClassName);
} else {
logger.log(Level.FINE, "Unable to find: {0}", resource);
}
} catch (UnsupportedEncodingException e) {
// should never happen
throw new JAXBException(e);
} catch (IOException e) {
throw new JAXBException(e);
} finally {
if (r != null) {
try {
r.close();
} catch (IOException ex) {
logger.log(Level.FINE, "Unable to close stream", ex);
}
}
}
// else no provider found
logger.fine("Trying to create the platform default provider");
return newInstance(classes, properties, PLATFORM_DEFAULT_FACTORY_CLASS);
}
private static Class lookupJaxbContextUsingOsgiServiceLoader() {
try {
// Use reflection to avoid having any dependency on ServiceLoader class
Class target = Class.forName("com.sun.org.glassfish.hk2.osgiresourcelocator.ServiceLoader");
Method m = target.getMethod("lookupProviderClasses", Class.class);
Iterator iter = ((Iterable) m.invoke(null, JAXBContext.class)).iterator();
return iter.hasNext() ? (Class)iter.next() : null;
} catch(Exception e) {
logger.log(Level.FINE, "Unable to find from OSGi: javax.xml.bind.JAXBContext");
return null;
}
}
private static Properties loadJAXBProperties( ClassLoader classLoader,
String propFileName )
throws JAXBException {
Properties props = null;
try {
URL url;
if(classLoader==null)
url = ClassLoader.getSystemResource(propFileName);
else
url = classLoader.getResource( propFileName );
if( url != null ) {
logger.log(Level.FINE, "loading props from {0}", url);
props = new Properties();
InputStream is = url.openStream();
props.load( is );
is.close();
}
} catch( IOException ioe ) {
logger.log(Level.FINE,"Unable to load "+propFileName,ioe);
throw new JAXBException( ioe.toString(), ioe );
}
return props;
}
/**
* Search the given ClassLoader for an instance of the specified class and
* return a string representation of the URL that points to the resource.
*
* @param clazz
* The class to search for
* @param loader
* The ClassLoader to search. If this parameter is null, then the
* system class loader will be searched
* @return
* the URL for the class or null if it wasn't found
*/
static URL which(Class clazz, ClassLoader loader) {
String classnameAsResource = clazz.getName().replace('.', '/') + ".class";
if(loader == null) {
loader = getSystemClassLoader();
}
return loader.getResource(classnameAsResource);
}
/**
* Get the URL for the Class from it's ClassLoader.
*
* Convenience method for {@link #which(Class, ClassLoader)}.
*
* Equivalent to calling: which(clazz, clazz.getClassLoader())
*
* @param clazz
* The class to search for
* @return
* the URL for the class or null if it wasn't found
*/
static URL which(Class clazz) {
return which(clazz, getClassClassLoader(clazz));
}
/**
* When JAXB is in J2SE, rt.jar has to have a JAXB implementation.
* However, rt.jar cannot have META-INF/services/javax.xml.bind.JAXBContext
* because if it has, it will take precedence over any file that applications have
* in their jar files.
*
* <p>
* When the user bundles his own JAXB implementation, we'd like to use it, and we
* want the platform default to be used only when there's no other JAXB provider.
*
* <p>
* For this reason, we have to hard-code the class name into the API.
*/
private static final String PLATFORM_DEFAULT_FACTORY_CLASS = "com.sun.xml.internal.bind.v2.ContextFactory";
/**
* Loads the class, provided that the calling thread has an access to the class being loaded.
*/
private static Class safeLoadClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
logger.log(Level.FINE, "Trying to load {0}", className);
try {
// make sure that the current thread has an access to the package of the given name.
SecurityManager s = System.getSecurityManager();
if (s != null) {
int i = className.lastIndexOf('.');
if (i != -1) {
s.checkPackageAccess(className.substring(0,i));
}
}
if (classLoader == null) {
return Class.forName(className);
} else {
return classLoader.loadClass(className);
}
} catch (SecurityException se) {
// anyone can access the platform default factory class without permission
if (PLATFORM_DEFAULT_FACTORY_CLASS.equals(className)) {
return Class.forName(className);
}
throw se;
}
}
private static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
}
private static ClassLoader getClassClassLoader(final Class c) {
if (System.getSecurityManager() == null) {
return c.getClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return c.getClassLoader();
}
});
}
}
private static ClassLoader getSystemClassLoader() {
if (System.getSecurityManager() == null) {
return ClassLoader.getSystemClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return ClassLoader.getSystemClassLoader();
}
});
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* Exception that represents a failure in a JAXB operation.
*
* <p>
* This exception differs from {@link JAXBException} in that
* this is an unchecked exception, while <tt>JAXBException</tt>
* is a checked exception.
*
* @see JAXB
* @since JAXB2.1
*/
public class DataBindingException extends RuntimeException {
public DataBindingException(String message, Throwable cause) {
super(message, cause);
}
public DataBindingException(Throwable cause) {
super(cause);
}
}

View File

@@ -0,0 +1,695 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.namespace.NamespaceContext;
/**
* <p>
* The javaType binding declaration can be used to customize the binding of
* an XML schema datatype to a Java datatype. Customizations can involve
* writing a parse and print method for parsing and printing lexical
* representations of a XML schema datatype respectively. However, writing
* parse and print methods requires knowledge of the lexical representations (
* <a href="http://www.w3.org/TR/xmlschema-2/"> XML Schema Part2: Datatypes
* specification </a>) and hence may be difficult to write.
* </p>
* <p>
* This class makes it easier to write parse and print methods. It defines
* static parse and print methods that provide access to a JAXB provider's
* implementation of parse and print methods. These methods are invoked by
* custom parse and print methods. For example, the binding of xsd:dateTime
* to a long can be customized using parse and print methods as follows:
* <blockquote>
* <pre>
* // Customized parse method
* public long myParseCal( String dateTimeString ) {
* java.util.Calendar cal = DatatypeConverter.parseDateTime(dateTimeString);
* long longval = convert_calendar_to_long(cal); //application specific
* return longval;
* }
*
* // Customized print method
* public String myPrintCal( Long longval ) {
* java.util.Calendar cal = convert_long_to_calendar(longval) ; //application specific
* String dateTimeString = DatatypeConverter.printDateTime(cal);
* return dateTimeString;
* }
* </pre>
* </blockquote>
* <p>
* There is a static parse and print method corresponding to each parse and
* print method respectively in the {@link DatatypeConverterInterface
* DatatypeConverterInterface}.
* <p>
* The static methods defined in the class can also be used to specify
* a parse or a print method in a javaType binding declaration.
* </p>
* <p>
* JAXB Providers are required to call the
* {@link #setDatatypeConverter(DatatypeConverterInterface)
* setDatatypeConverter} api at some point before the first marshal or unmarshal
* operation (perhaps during the call to JAXBContext.newInstance). This step is
* necessary to configure the converter that should be used to perform the
* print and parse functionality.
* </p>
*
* <p>
* A print method for a XML schema datatype can output any lexical
* representation that is valid with respect to the XML schema datatype.
* If an error is encountered during conversion, then an IllegalArgumentException,
* or a subclass of IllegalArgumentException must be thrown by the method.
* </p>
*
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Ryan Shoemaker,Sun Microsystems Inc.</li></ul>
* @see DatatypeConverterInterface
* @see ParseConversionEvent
* @see PrintConversionEvent
* @since JAXB1.0
*/
final public class DatatypeConverter {
// delegate to this instance of DatatypeConverter
private static volatile DatatypeConverterInterface theConverter = null;
private final static JAXBPermission SET_DATATYPE_CONVERTER_PERMISSION =
new JAXBPermission("setDatatypeConverter");
private DatatypeConverter() {
// private constructor
}
/**
* This method is for JAXB provider use only.
* <p>
* JAXB Providers are required to call this method at some point before
* allowing any of the JAXB client marshal or unmarshal operations to
* occur. This is necessary to configure the datatype converter that
* should be used to perform the print and parse conversions.
*
* <p>
* Calling this api repeatedly will have no effect - the
* DatatypeConverterInterface instance passed into the first invocation is
* the one that will be used from then on.
*
* @param converter an instance of a class that implements the
* DatatypeConverterInterface class - this parameter must not be null.
* @throws IllegalArgumentException if the parameter is null
* @throws SecurityException
* If the {@link SecurityManager} in charge denies the access to
* set the datatype converter.
* @see JAXBPermission
*/
public static void setDatatypeConverter( DatatypeConverterInterface converter ) {
if( converter == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.CONVERTER_MUST_NOT_BE_NULL ) );
} else if( theConverter == null ) {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(SET_DATATYPE_CONVERTER_PERMISSION);
theConverter = converter;
}
}
private static synchronized void initConverter() {
theConverter = new DatatypeConverterImpl();
}
/**
* <p>
* Convert the lexical XSD string argument into a String value.
* @param lexicalXSDString
* A string containing a lexical representation of
* xsd:string.
* @return
* A String value represented by the string argument.
*/
public static String parseString( String lexicalXSDString ) {
if (theConverter == null) initConverter();
return theConverter.parseString( lexicalXSDString );
}
/**
* <p>
* Convert the string argument into a BigInteger value.
* @param lexicalXSDInteger
* A string containing a lexical representation of
* xsd:integer.
* @return
* A BigInteger value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDInteger</code> is not a valid string representation of a {@link java.math.BigInteger} value.
*/
public static java.math.BigInteger parseInteger( String lexicalXSDInteger ) {
if (theConverter == null) initConverter();
return theConverter.parseInteger( lexicalXSDInteger );
}
/**
* <p>
* Convert the string argument into an int value.
* @param lexicalXSDInt
* A string containing a lexical representation of
* xsd:int.
* @return
* A int value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDInt</code> is not a valid string representation of an <code>int</code> value.
*/
public static int parseInt( String lexicalXSDInt ) {
if (theConverter == null) initConverter();
return theConverter.parseInt( lexicalXSDInt );
}
/**
* <p>
* Converts the string argument into a long value.
* @param lexicalXSDLong
* A string containing lexical representation of
* xsd:long.
* @return
* A long value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDLong</code> is not a valid string representation of a <code>long</code> value.
*/
public static long parseLong( String lexicalXSDLong ) {
if (theConverter == null) initConverter();
return theConverter.parseLong( lexicalXSDLong );
}
/**
* <p>
* Converts the string argument into a short value.
* @param lexicalXSDShort
* A string containing lexical representation of
* xsd:short.
* @return
* A short value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDShort</code> is not a valid string representation of a <code>short</code> value.
*/
public static short parseShort( String lexicalXSDShort ) {
if (theConverter == null) initConverter();
return theConverter.parseShort( lexicalXSDShort );
}
/**
* <p>
* Converts the string argument into a BigDecimal value.
* @param lexicalXSDDecimal
* A string containing lexical representation of
* xsd:decimal.
* @return
* A BigDecimal value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDDecimal</code> is not a valid string representation of {@link java.math.BigDecimal}.
*/
public static java.math.BigDecimal parseDecimal( String lexicalXSDDecimal ) {
if (theConverter == null) initConverter();
return theConverter.parseDecimal( lexicalXSDDecimal );
}
/**
* <p>
* Converts the string argument into a float value.
* @param lexicalXSDFloat
* A string containing lexical representation of
* xsd:float.
* @return
* A float value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDFloat</code> is not a valid string representation of a <code>float</code> value.
*/
public static float parseFloat( String lexicalXSDFloat ) {
if (theConverter == null) initConverter();
return theConverter.parseFloat( lexicalXSDFloat );
}
/**
* <p>
* Converts the string argument into a double value.
* @param lexicalXSDDouble
* A string containing lexical representation of
* xsd:double.
* @return
* A double value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDDouble</code> is not a valid string representation of a <code>double</code> value.
*/
public static double parseDouble( String lexicalXSDDouble ) {
if (theConverter == null) initConverter();
return theConverter.parseDouble( lexicalXSDDouble );
}
/**
* <p>
* Converts the string argument into a boolean value.
* @param lexicalXSDBoolean
* A string containing lexical representation of
* xsd:boolean.
* @return
* A boolean value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:boolean.
*/
public static boolean parseBoolean( String lexicalXSDBoolean ) {
if (theConverter == null) initConverter();
return theConverter.parseBoolean( lexicalXSDBoolean );
}
/**
* <p>
* Converts the string argument into a byte value.
* @param lexicalXSDByte
* A string containing lexical representation of
* xsd:byte.
* @return
* A byte value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:byte.
*/
public static byte parseByte( String lexicalXSDByte ) {
if (theConverter == null) initConverter();
return theConverter.parseByte( lexicalXSDByte );
}
/**
* <p>
* Converts the string argument into a byte value.
*
* <p>
* String parameter <tt>lexicalXSDQname</tt> must conform to lexical value space specifed at
* <a href="http://www.w3.org/TR/xmlschema-2/#QName">XML Schema Part 2:Datatypes specification:QNames</a>
*
* @param lexicalXSDQName
* A string containing lexical representation of xsd:QName.
* @param nsc
* A namespace context for interpreting a prefix within a QName.
* @return
* A QName value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to XML Schema Part 2 specification or
* if namespace prefix of <tt>lexicalXSDQname</tt> is not bound to a URI in NamespaceContext <tt>nsc</tt>.
*/
public static javax.xml.namespace.QName parseQName( String lexicalXSDQName,
NamespaceContext nsc) {
if (theConverter == null) initConverter();
return theConverter.parseQName( lexicalXSDQName, nsc );
}
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDDateTime
* A string containing lexical representation of
* xsd:datetime.
* @return
* A Calendar object represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:dateTime.
*/
public static java.util.Calendar parseDateTime( String lexicalXSDDateTime ) {
if (theConverter == null) initConverter();
return theConverter.parseDateTime( lexicalXSDDateTime );
}
/**
* <p>
* Converts the string argument into an array of bytes.
* @param lexicalXSDBase64Binary
* A string containing lexical representation
* of xsd:base64Binary.
* @return
* An array of bytes represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary
*/
public static byte[] parseBase64Binary( String lexicalXSDBase64Binary ) {
if (theConverter == null) initConverter();
return theConverter.parseBase64Binary( lexicalXSDBase64Binary );
}
/**
* <p>
* Converts the string argument into an array of bytes.
* @param lexicalXSDHexBinary
* A string containing lexical representation of
* xsd:hexBinary.
* @return
* An array of bytes represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:hexBinary.
*/
public static byte[] parseHexBinary( String lexicalXSDHexBinary ) {
if (theConverter == null) initConverter();
return theConverter.parseHexBinary( lexicalXSDHexBinary );
}
/**
* <p>
* Converts the string argument into a long value.
* @param lexicalXSDUnsignedInt
* A string containing lexical representation
* of xsd:unsignedInt.
* @return
* A long value represented by the string argument.
* @throws NumberFormatException if string parameter can not be parsed into a <tt>long</tt> value.
*/
public static long parseUnsignedInt( String lexicalXSDUnsignedInt ) {
if (theConverter == null) initConverter();
return theConverter.parseUnsignedInt( lexicalXSDUnsignedInt );
}
/**
* <p>
* Converts the string argument into an int value.
* @param lexicalXSDUnsignedShort
* A string containing lexical
* representation of xsd:unsignedShort.
* @return
* An int value represented by the string argument.
* @throws NumberFormatException if string parameter can not be parsed into an <tt>int</tt> value.
*/
public static int parseUnsignedShort( String lexicalXSDUnsignedShort ) {
if (theConverter == null) initConverter();
return theConverter.parseUnsignedShort( lexicalXSDUnsignedShort );
}
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDTime
* A string containing lexical representation of
* xsd:time.
* @return
* A Calendar value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Time.
*/
public static java.util.Calendar parseTime( String lexicalXSDTime ) {
if (theConverter == null) initConverter();
return theConverter.parseTime( lexicalXSDTime );
}
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDDate
* A string containing lexical representation of
* xsd:Date.
* @return
* A Calendar value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Date.
*/
public static java.util.Calendar parseDate( String lexicalXSDDate ) {
if (theConverter == null) initConverter();
return theConverter.parseDate( lexicalXSDDate );
}
/**
* <p>
* Return a string containing the lexical representation of the
* simple type.
* @param lexicalXSDAnySimpleType
* A string containing lexical
* representation of the simple type.
* @return
* A string containing the lexical representation of the
* simple type.
*/
public static String parseAnySimpleType( String lexicalXSDAnySimpleType ) {
if (theConverter == null) initConverter();
return theConverter.parseAnySimpleType( lexicalXSDAnySimpleType );
}
/**
* <p>
* Converts the string argument into a string.
* @param val
* A string value.
* @return
* A string containing a lexical representation of xsd:string.
*/
// also indicate the print methods produce a lexical
// representation for given Java datatypes.
public static String printString( String val ) {
if (theConverter == null) initConverter();
return theConverter.printString( val );
}
/**
* <p>
* Converts a BigInteger value into a string.
* @param val
* A BigInteger value
* @return
* A string containing a lexical representation of xsd:integer
* @throws IllegalArgumentException <tt>val</tt> is null.
*/
public static String printInteger( java.math.BigInteger val ) {
if (theConverter == null) initConverter();
return theConverter.printInteger( val );
}
/**
* <p>
* Converts an int value into a string.
* @param val
* An int value
* @return
* A string containing a lexical representation of xsd:int
*/
public static String printInt( int val ) {
if (theConverter == null) initConverter();
return theConverter.printInt( val );
}
/**
* <p>
* Converts A long value into a string.
* @param val
* A long value
* @return
* A string containing a lexical representation of xsd:long
*/
public static String printLong( long val ) {
if (theConverter == null) initConverter();
return theConverter.printLong( val );
}
/**
* <p>
* Converts a short value into a string.
* @param val
* A short value
* @return
* A string containing a lexical representation of xsd:short
*/
public static String printShort( short val ) {
if (theConverter == null) initConverter();
return theConverter.printShort( val );
}
/**
* <p>
* Converts a BigDecimal value into a string.
* @param val
* A BigDecimal value
* @return
* A string containing a lexical representation of xsd:decimal
* @throws IllegalArgumentException <tt>val</tt> is null.
*/
public static String printDecimal( java.math.BigDecimal val ) {
if (theConverter == null) initConverter();
return theConverter.printDecimal( val );
}
/**
* <p>
* Converts a float value into a string.
* @param val
* A float value
* @return
* A string containing a lexical representation of xsd:float
*/
public static String printFloat( float val ) {
if (theConverter == null) initConverter();
return theConverter.printFloat( val );
}
/**
* <p>
* Converts a double value into a string.
* @param val
* A double value
* @return
* A string containing a lexical representation of xsd:double
*/
public static String printDouble( double val ) {
if (theConverter == null) initConverter();
return theConverter.printDouble( val );
}
/**
* <p>
* Converts a boolean value into a string.
* @param val
* A boolean value
* @return
* A string containing a lexical representation of xsd:boolean
*/
public static String printBoolean( boolean val ) {
if (theConverter == null) initConverter();
return theConverter.printBoolean( val );
}
/**
* <p>
* Converts a byte value into a string.
* @param val
* A byte value
* @return
* A string containing a lexical representation of xsd:byte
*/
public static String printByte( byte val ) {
if (theConverter == null) initConverter();
return theConverter.printByte( val );
}
/**
* <p>
* Converts a QName instance into a string.
* @param val
* A QName value
* @param nsc
* A namespace context for interpreting a prefix within a QName.
* @return
* A string containing a lexical representation of QName
* @throws IllegalArgumentException if <tt>val</tt> is null or
* if <tt>nsc</tt> is non-null or <tt>nsc.getPrefix(nsprefixFromVal)</tt> is null.
*/
public static String printQName( javax.xml.namespace.QName val,
NamespaceContext nsc ) {
if (theConverter == null) initConverter();
return theConverter.printQName( val, nsc );
}
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:dateTime
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public static String printDateTime( java.util.Calendar val ) {
if (theConverter == null) initConverter();
return theConverter.printDateTime( val );
}
/**
* <p>
* Converts an array of bytes into a string.
* @param val
* An array of bytes
* @return
* A string containing a lexical representation of xsd:base64Binary
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public static String printBase64Binary( byte[] val ) {
if (theConverter == null) initConverter();
return theConverter.printBase64Binary( val );
}
/**
* <p>
* Converts an array of bytes into a string.
* @param val
* An array of bytes
* @return
* A string containing a lexical representation of xsd:hexBinary
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public static String printHexBinary( byte[] val ) {
if (theConverter == null) initConverter();
return theConverter.printHexBinary( val );
}
/**
* <p>
* Converts a long value into a string.
* @param val
* A long value
* @return
* A string containing a lexical representation of xsd:unsignedInt
*/
public static String printUnsignedInt( long val ) {
if (theConverter == null) initConverter();
return theConverter.printUnsignedInt( val );
}
/**
* <p>
* Converts an int value into a string.
* @param val
* An int value
* @return
* A string containing a lexical representation of xsd:unsignedShort
*/
public static String printUnsignedShort( int val ) {
if (theConverter == null) initConverter();
return theConverter.printUnsignedShort( val );
}
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:time
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public static String printTime( java.util.Calendar val ) {
if (theConverter == null) initConverter();
return theConverter.printTime( val );
}
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:date
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public static String printDate( java.util.Calendar val ) {
if (theConverter == null) initConverter();
return theConverter.printDate( val );
}
/**
* <p>
* Converts a string value into a string.
* @param val
* A string value
* @return
* A string containing a lexical representation of xsd:AnySimpleType
*/
public static String printAnySimpleType( String val ) {
if (theConverter == null) initConverter();
return theConverter.printAnySimpleType( val );
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,523 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* <p>
* The DatatypeConverterInterface is for JAXB provider use only. A
* JAXB provider must supply a class that implements this interface.
* JAXB Providers are required to call the
* {@link DatatypeConverter#setDatatypeConverter(DatatypeConverterInterface)
* DatatypeConverter.setDatatypeConverter} api at
* some point before the first marshal or unmarshal operation (perhaps during
* the call to JAXBContext.newInstance). This step is necessary to configure
* the converter that should be used to perform the print and parse
* functionality. Calling this api repeatedly will have no effect - the
* DatatypeConverter instance passed into the first invocation is the one that
* will be used from then on.
* </p>
*
* <p>
* This interface defines the parse and print methods. There is one
* parse and print method for each XML schema datatype specified in the
* the default binding Table 5-1 in the JAXB specification.
* </p>
*
* <p>
* The parse and print methods defined here are invoked by the static parse
* and print methods defined in the {@link DatatypeConverter DatatypeConverter}
* class.
* </p>
*
* <p>
* A parse method for a XML schema datatype must be capable of converting any
* lexical representation of the XML schema datatype ( specified by the
* <a href="http://www.w3.org/TR/xmlschema-2/"> XML Schema Part2: Datatypes
* specification</a> into a value in the value space of the XML schema datatype.
* If an error is encountered during conversion, then an IllegalArgumentException
* or a subclass of IllegalArgumentException must be thrown by the method.
*
* </p>
*
* <p>
* A print method for a XML schema datatype can output any lexical
* representation that is valid with respect to the XML schema datatype.
* If an error is encountered during conversion, then an IllegalArgumentException,
* or a subclass of IllegalArgumentException must be thrown by the method.
* </p>
*
* The prefix xsd: is used to refer to XML schema datatypes
* <a href="http://www.w3.org/TR/xmlschema-2/"> XML Schema Part2: Datatypes
* specification.</a>
*
* <p>
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Ryan Shoemaker,Sun Microsystems Inc.</li></ul>
* @see DatatypeConverter
* @see ParseConversionEvent
* @see PrintConversionEvent
* @since JAXB1.0
*/
public interface DatatypeConverterInterface {
/**
* <p>
* Convert the string argument into a string.
* @param lexicalXSDString
* A lexical representation of the XML Schema datatype xsd:string
* @return
* A string that is the same as the input string.
*/
public String parseString( String lexicalXSDString );
/**
* <p>
* Convert the string argument into a BigInteger value.
* @param lexicalXSDInteger
* A string containing a lexical representation of
* xsd:integer.
* @return
* A BigInteger value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDInteger</code> is not a valid string representation of a {@link java.math.BigInteger} value.
*/
public java.math.BigInteger parseInteger( String lexicalXSDInteger );
/**
* <p>
* Convert the string argument into an int value.
* @param lexicalXSDInt
* A string containing a lexical representation of
* xsd:int.
* @return
* An int value represented byte the string argument.
* @throws NumberFormatException <code>lexicalXSDInt</code> is not a valid string representation of an <code>int</code> value.
*/
public int parseInt( String lexicalXSDInt );
/**
* <p>
* Converts the string argument into a long value.
* @param lexicalXSDLong
* A string containing lexical representation of
* xsd:long.
* @return
* A long value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDLong</code> is not a valid string representation of a <code>long</code> value.
*/
public long parseLong( String lexicalXSDLong );
/**
* <p>
* Converts the string argument into a short value.
* @param lexicalXSDShort
* A string containing lexical representation of
* xsd:short.
* @return
* A short value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDShort</code> is not a valid string representation of a <code>short</code> value.
*/
public short parseShort( String lexicalXSDShort );
/**
* <p>
* Converts the string argument into a BigDecimal value.
* @param lexicalXSDDecimal
* A string containing lexical representation of
* xsd:decimal.
* @return
* A BigDecimal value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDDecimal</code> is not a valid string representation of {@link java.math.BigDecimal}.
*/
public java.math.BigDecimal parseDecimal( String lexicalXSDDecimal );
/**
* <p>
* Converts the string argument into a float value.
* @param lexicalXSDFloat
* A string containing lexical representation of
* xsd:float.
* @return
* A float value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDFloat</code> is not a valid string representation of a <code>float</code> value.
*/
public float parseFloat( String lexicalXSDFloat );
/**
* <p>
* Converts the string argument into a double value.
* @param lexicalXSDDouble
* A string containing lexical representation of
* xsd:double.
* @return
* A double value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDDouble</code> is not a valid string representation of a <code>double</code> value.
*/
public double parseDouble( String lexicalXSDDouble );
/**
* <p>
* Converts the string argument into a boolean value.
* @param lexicalXSDBoolean
* A string containing lexical representation of
* xsd:boolean.
* @return
* A boolean value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:boolean.
*/
public boolean parseBoolean( String lexicalXSDBoolean );
/**
* <p>
* Converts the string argument into a byte value.
* @param lexicalXSDByte
* A string containing lexical representation of
* xsd:byte.
* @return
* A byte value represented by the string argument.
* @throws NumberFormatException <code>lexicalXSDByte</code> does not contain a parseable byte.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:byte.
*/
public byte parseByte( String lexicalXSDByte );
/**
* <p>
* Converts the string argument into a QName value.
*
* <p>
* String parameter <tt>lexicalXSDQname</tt> must conform to lexical value space specifed at
* <a href="http://www.w3.org/TR/xmlschema-2/#QName">XML Schema Part 2:Datatypes specification:QNames</a>
*
* @param lexicalXSDQName
* A string containing lexical representation of xsd:QName.
* @param nsc
* A namespace context for interpreting a prefix within a QName.
* @return
* A QName value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to XML Schema Part 2 specification or
* if namespace prefix of <tt>lexicalXSDQname</tt> is not bound to a URI in NamespaceContext <tt>nsc</tt>.
*/
public javax.xml.namespace.QName parseQName( String lexicalXSDQName,
javax.xml.namespace.NamespaceContext nsc);
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDDateTime
* A string containing lexical representation of
* xsd:datetime.
* @return
* A Calendar object represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:dateTime.
*/
public java.util.Calendar parseDateTime( String lexicalXSDDateTime );
/**
* <p>
* Converts the string argument into an array of bytes.
* @param lexicalXSDBase64Binary
* A string containing lexical representation
* of xsd:base64Binary.
* @return
* An array of bytes represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary
*/
public byte[] parseBase64Binary( String lexicalXSDBase64Binary );
/**
* <p>
* Converts the string argument into an array of bytes.
* @param lexicalXSDHexBinary
* A string containing lexical representation of
* xsd:hexBinary.
* @return
* An array of bytes represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:hexBinary.
*/
public byte[] parseHexBinary( String lexicalXSDHexBinary );
/**
* <p>
* Converts the string argument into a long value.
* @param lexicalXSDUnsignedInt
* A string containing lexical representation
* of xsd:unsignedInt.
* @return
* A long value represented by the string argument.
* @throws NumberFormatException if string parameter can not be parsed into a <tt>long</tt> value.
*/
public long parseUnsignedInt( String lexicalXSDUnsignedInt );
/**
* <p>
* Converts the string argument into an int value.
* @param lexicalXSDUnsignedShort
* A string containing lexical
* representation of xsd:unsignedShort.
* @return
* An int value represented by the string argument.
* @throws NumberFormatException if string parameter can not be parsed into an <tt>int</tt> value.
*/
public int parseUnsignedShort( String lexicalXSDUnsignedShort );
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDTime
* A string containing lexical representation of
* xsd:Time.
* @return
* A Calendar value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Time.
*/
public java.util.Calendar parseTime( String lexicalXSDTime );
/**
* <p>
* Converts the string argument into a Calendar value.
* @param lexicalXSDDate
* A string containing lexical representation of
* xsd:Date.
* @return
* A Calendar value represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:Date.
*/
public java.util.Calendar parseDate( String lexicalXSDDate );
/**
* <p>
* Return a string containing the lexical representation of the
* simple type.
* @param lexicalXSDAnySimpleType
* A string containing lexical
* representation of the simple type.
* @return
* A string containing the lexical representation of the
* simple type.
*/
public String parseAnySimpleType( String lexicalXSDAnySimpleType );
/**
* <p>
* Converts the string argument into a string.
* @param val
* A string value.
* @return
* A string containing a lexical representation of xsd:string
*/
public String printString( String val );
/**
* <p>
* Converts a BigInteger value into a string.
* @param val
* A BigInteger value
* @return
* A string containing a lexical representation of xsd:integer
* @throws IllegalArgumentException <tt>val</tt> is null.
*/
public String printInteger( java.math.BigInteger val );
/**
* <p>
* Converts an int value into a string.
* @param val
* An int value
* @return
* A string containing a lexical representation of xsd:int
*/
public String printInt( int val );
/**
* <p>
* Converts a long value into a string.
* @param val
* A long value
* @return
* A string containing a lexical representation of xsd:long
*/
public String printLong( long val );
/**
* <p>
* Converts a short value into a string.
* @param val
* A short value
* @return
* A string containing a lexical representation of xsd:short
*/
public String printShort( short val );
/**
* <p>
* Converts a BigDecimal value into a string.
* @param val
* A BigDecimal value
* @return
* A string containing a lexical representation of xsd:decimal
* @throws IllegalArgumentException <tt>val</tt> is null.
*/
public String printDecimal( java.math.BigDecimal val );
/**
* <p>
* Converts a float value into a string.
* @param val
* A float value
* @return
* A string containing a lexical representation of xsd:float
*/
public String printFloat( float val );
/**
* <p>
* Converts a double value into a string.
* @param val
* A double value
* @return
* A string containing a lexical representation of xsd:double
*/
public String printDouble( double val );
/**
* <p>
* Converts a boolean value into a string.
* @param val
* A boolean value
* @return
* A string containing a lexical representation of xsd:boolean
*/
public String printBoolean( boolean val );
/**
* <p>
* Converts a byte value into a string.
* @param val
* A byte value
* @return
* A string containing a lexical representation of xsd:byte
*/
public String printByte( byte val );
/**
* <p>
* Converts a QName instance into a string.
* @param val
* A QName value
* @param nsc
* A namespace context for interpreting a prefix within a QName.
* @return
* A string containing a lexical representation of QName
* @throws IllegalArgumentException if <tt>val</tt> is null or
* if <tt>nsc</tt> is non-null or <tt>nsc.getPrefix(nsprefixFromVal)</tt> is null.
*/
public String printQName( javax.xml.namespace.QName val,
javax.xml.namespace.NamespaceContext nsc );
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:dateTime
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public String printDateTime( java.util.Calendar val );
/**
* <p>
* Converts an array of bytes into a string.
* @param val
* an array of bytes
* @return
* A string containing a lexical representation of xsd:base64Binary
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public String printBase64Binary( byte[] val );
/**
* <p>
* Converts an array of bytes into a string.
* @param val
* an array of bytes
* @return
* A string containing a lexical representation of xsd:hexBinary
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public String printHexBinary( byte[] val );
/**
* <p>
* Converts a long value into a string.
* @param val
* A long value
* @return
* A string containing a lexical representation of xsd:unsignedInt
*/
public String printUnsignedInt( long val );
/**
* <p>
* Converts an int value into a string.
* @param val
* An int value
* @return
* A string containing a lexical representation of xsd:unsignedShort
*/
public String printUnsignedShort( int val );
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:time
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public String printTime( java.util.Calendar val );
/**
* <p>
* Converts a Calendar value into a string.
* @param val
* A Calendar value
* @return
* A string containing a lexical representation of xsd:date
* @throws IllegalArgumentException if <tt>val</tt> is null.
*/
public String printDate( java.util.Calendar val );
/**
* <p>
* Converts a string value into a string.
* @param val
* A string value
* @return
* A string containing a lexical representation of xsd:AnySimpleType
*/
public String printAnySimpleType( String val );
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This is an element marker interface.
*
* Under certain circumstances, it is necessary for the binding compiler to
* generate derived java content classes that implement this interface. In
* those cases, client applications must supply element instances rather than
* types of elements. For more detail, see section 5.7 "Element Declaration"
* and 5.7.1 "Bind to Java Element Interface" of the specification.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @since JAXB1.0
*/
public interface Element {
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import java.security.PrivilegedAction;
/**
* {@link PrivilegedAction} that gets the system property value.
* @author Kohsuke Kawaguchi
*/
final class GetPropertyAction implements PrivilegedAction<String> {
private final String propertyName;
public GetPropertyAction(String propertyName) {
this.propertyName = propertyName;
}
public String run() {
return System.getProperty(propertyName);
}
}

View File

@@ -0,0 +1,629 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.beans.Introspector;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
/**
* Class that defines convenience methods for common, simple use of JAXB.
*
* <p>
* Methods defined in this class are convenience methods that combine several basic operations
* in the {@link JAXBContext}, {@link Unmarshaller}, and {@link Marshaller}.
*
* They are designed
* to be the prefered methods for developers new to JAXB. They have
* the following characterstics:
*
* <ol>
* <li>Generally speaking, the performance is not necessarily optimal.
* It is expected that people who need to write performance
* critical code will use the rest of the JAXB API directly.
* <li>Errors that happen during the processing is wrapped into
* {@link DataBindingException} (which will have {@link JAXBException}
* as its {@link Throwable#getCause() cause}. It is expected that
* people who prefer the checked exception would use
* the rest of the JAXB API directly.
* </ol>
*
* <p>
* In addition, the <tt>unmarshal</tt> methods have the following characteristic:
*
* <ol>
* <li>Schema validation is not performed on the input XML.
* The processing will try to continue even if there
* are errors in the XML, as much as possible. Only as
* the last resort, this method fails with {@link DataBindingException}.
* </ol>
*
* <p>
* Similarly, the <tt>marshal</tt> methods have the following characteristic:
* <ol>
* <li>The processing will try to continue even if the Java object tree
* does not meet the validity requirement. Only as
* the last resort, this method fails with {@link DataBindingException}.
* </ol>
*
*
* <p>
* All the methods on this class require non-null arguments to all parameters.
* The <tt>unmarshal</tt> methods either fail with an exception or return
* a non-null value.
*
* @author Kohsuke Kawaguchi
* @since 2.1
*/
public final class JAXB {
/**
* No instanciation is allowed.
*/
private JAXB() {}
/**
* To improve the performance, we'll cache the last {@link JAXBContext} used.
*/
private static final class Cache {
final Class type;
final JAXBContext context;
public Cache(Class type) throws JAXBException {
this.type = type;
this.context = JAXBContext.newInstance(type);
}
}
/**
* Cache. We don't want to prevent the {@link Cache#type} from GC-ed,
* hence {@link WeakReference}.
*/
private static volatile WeakReference<Cache> cache;
/**
* Obtains the {@link JAXBContext} from the given type,
* by using the cache if possible.
*
* <p>
* We don't use locks to control access to {@link #cache}, but this code
* should be thread-safe thanks to the immutable {@link Cache} and {@code volatile}.
*/
private static <T> JAXBContext getContext(Class<T> type) throws JAXBException {
WeakReference<Cache> c = cache;
if(c!=null) {
Cache d = c.get();
if(d!=null && d.type==type)
return d.context;
}
// overwrite the cache
Cache d = new Cache(type);
cache = new WeakReference<Cache>(d);
return d.context;
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* Reads the entire file as XML.
*/
public static <T> T unmarshal( File xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(new StreamSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The resource pointed by the URL is read in its entirety.
*/
public static <T> T unmarshal( URL xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The URI is {@link URI#toURL() turned into URL} and then
* follows the handling of <tt>URL</tt>.
*/
public static <T> T unmarshal( URI xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The string is first interpreted as an absolute <tt>URI</tt>.
* If it's not {@link URI#isAbsolute() a valid absolute URI},
* then it's interpreted as a <tt>File</tt>
*/
public static <T> T unmarshal( String xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The entire stream is read as an XML infoset.
* Upon a successful completion, the stream will be closed by this method.
*/
public static <T> T unmarshal( InputStream xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The character stream is read as an XML infoset.
* The encoding declaration in the XML will be ignored.
* Upon a successful completion, the stream will be closed by this method.
*/
public static <T> T unmarshal( Reader xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Reads in a Java object tree from the given XML input.
*
* @param xml
* The XML infoset that the {@link Source} represents is read.
*/
public static <T> T unmarshal( Source xml, Class<T> type ) {
try {
JAXBElement<T> item = getContext(type).createUnmarshaller().unmarshal(toSource(xml), type);
return item.getValue();
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
/**
* Creates {@link Source} from various XML representation.
* See {@link #unmarshal} for the conversion rules.
*/
private static Source toSource(Object xml) throws IOException {
if(xml==null)
throw new IllegalArgumentException("no XML is given");
if (xml instanceof String) {
try {
xml=new URI((String)xml);
} catch (URISyntaxException e) {
xml=new File((String)xml);
}
}
if (xml instanceof File) {
File file = (File) xml;
return new StreamSource(file);
}
if (xml instanceof URI) {
URI uri = (URI) xml;
xml=uri.toURL();
}
if (xml instanceof URL) {
URL url = (URL) xml;
return new StreamSource(url.toExternalForm());
}
if (xml instanceof InputStream) {
InputStream in = (InputStream) xml;
return new StreamSource(in);
}
if (xml instanceof Reader) {
Reader r = (Reader) xml;
return new StreamSource(r);
}
if (xml instanceof Source) {
return (Source) xml;
}
throw new IllegalArgumentException("I don't understand how to handle "+xml.getClass());
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* XML will be written to this file. If it already exists,
* it will be overwritten.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, File xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The XML will be {@link URLConnection#getOutputStream() sent} to the
* resource pointed by this URL. Note that not all <tt>URL</tt>s support
* such operation, and exact semantics depends on the <tt>URL</tt>
* implementations. In case of {@link HttpURLConnection HTTP URLs},
* this will perform HTTP POST.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, URL xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The URI is {@link URI#toURL() turned into URL} and then
* follows the handling of <tt>URL</tt>. See above.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, URI xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The string is first interpreted as an absolute <tt>URI</tt>.
* If it's not {@link URI#isAbsolute() a valid absolute URI},
* then it's interpreted as a <tt>File</tt>
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, String xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The XML will be sent to the given {@link OutputStream}.
* Upon a successful completion, the stream will be closed by this method.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, OutputStream xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The XML will be sent as a character stream to the given {@link Writer}.
* Upon a successful completion, the stream will be closed by this method.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, Writer xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* The XML will be sent to the {@link Result} object.
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
public static void marshal( Object jaxbObject, Result xml ) {
_marshal(jaxbObject,xml);
}
/**
* Writes a Java object tree to XML and store it to the specified location.
*
* <p>
* This method is a convenience method that combines several basic operations
* in the {@link JAXBContext} and {@link Marshaller}. This method is designed
* to be the prefered method for developers new to JAXB. This method
* has the following characterstics:
*
* <ol>
* <li>Generally speaking, the performance is not necessarily optimal.
* It is expected that those people who need to write performance
* critical code will use the rest of the JAXB API directly.
* <li>Errors that happen during the processing is wrapped into
* {@link DataBindingException} (which will have {@link JAXBException}
* as its {@link Throwable#getCause() cause}. It is expected that
* those people who prefer the checked exception would use
* the rest of the JAXB API directly.
* </ol>
*
* @param jaxbObject
* The Java object to be marshalled into XML. If this object is
* a {@link JAXBElement}, it will provide the root tag name and
* the body. If this object has {@link XmlRootElement}
* on its class definition, that will be used as the root tag name
* and the given object will provide the body. Otherwise,
* the root tag name is {@link Introspector#decapitalize(String) infered} from
* {@link Class#getSimpleName() the short class name}.
* This parameter must not be null.
*
* @param xml
* Represents the receiver of XML. Objects of the following types are allowed.
*
* <table><tr>
* <th>Type</th>
* <th>Operation</th>
* </tr><tr>
* <td>{@link File}</td>
* <td>XML will be written to this file. If it already exists,
* it will be overwritten.</td>
* </tr><tr>
* <td>{@link URL}</td>
* <td>The XML will be {@link URLConnection#getOutputStream() sent} to the
* resource pointed by this URL. Note that not all <tt>URL</tt>s support
* such operation, and exact semantics depends on the <tt>URL</tt>
* implementations. In case of {@link HttpURLConnection HTTP URLs},
* this will perform HTTP POST.</td>
* </tr><tr>
* <td>{@link URI}</td>
* <td>The URI is {@link URI#toURL() turned into URL} and then
* follows the handling of <tt>URL</tt>. See above.</td>
* </tr><tr>
* <td>{@link String}</td>
* <td>The string is first interpreted as an absolute <tt>URI</tt>.
* If it's not {@link URI#isAbsolute() a valid absolute URI},
* then it's interpreted as a <tt>File</tt></td>
* </tr><tr>
* <td>{@link OutputStream}</td>
* <td>The XML will be sent to the given {@link OutputStream}.
* Upon a successful completion, the stream will be closed by this method.</td>
* </tr><tr>
* <td>{@link Writer}</td>
* <td>The XML will be sent as a character stream to the given {@link Writer}.
* Upon a successful completion, the stream will be closed by this method.</td>
* </tr><tr>
* <td>{@link Result}</td>
* <td>The XML will be sent to the {@link Result} object.</td>
* </tr></table>
*
* @throws DataBindingException
* If the operation fails, such as due to I/O error, unbindable classes.
*/
private static void _marshal( Object jaxbObject, Object xml ) {
try {
JAXBContext context;
if(jaxbObject instanceof JAXBElement) {
context = getContext(((JAXBElement<?>)jaxbObject).getDeclaredType());
} else {
Class<?> clazz = jaxbObject.getClass();
XmlRootElement r = clazz.getAnnotation(XmlRootElement.class);
context = getContext(clazz);
if(r==null) {
// we need to infer the name
jaxbObject = new JAXBElement(new QName(inferName(clazz)),clazz,jaxbObject);
}
}
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
m.marshal(jaxbObject, toResult(xml));
} catch (JAXBException e) {
throw new DataBindingException(e);
} catch (IOException e) {
throw new DataBindingException(e);
}
}
private static String inferName(Class clazz) {
return Introspector.decapitalize(clazz.getSimpleName());
}
/**
* Creates {@link Result} from various XML representation.
* See {@link #_marshal(Object,Object)} for the conversion rules.
*/
private static Result toResult(Object xml) throws IOException {
if(xml==null)
throw new IllegalArgumentException("no XML is given");
if (xml instanceof String) {
try {
xml=new URI((String)xml);
} catch (URISyntaxException e) {
xml=new File((String)xml);
}
}
if (xml instanceof File) {
File file = (File) xml;
return new StreamResult(file);
}
if (xml instanceof URI) {
URI uri = (URI) xml;
xml=uri.toURL();
}
if (xml instanceof URL) {
URL url = (URL) xml;
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setDoInput(false);
con.connect();
return new StreamResult(con.getOutputStream());
}
if (xml instanceof OutputStream) {
OutputStream os = (OutputStream) xml;
return new StreamResult(os);
}
if (xml instanceof Writer) {
Writer w = (Writer)xml;
return new StreamResult(w);
}
if (xml instanceof Result) {
return (Result) xml;
}
throw new IllegalArgumentException("I don't understand how to handle "+xml.getClass());
}
}

View File

@@ -0,0 +1,768 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import org.w3c.dom.Node;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>
* The <tt>JAXBContext</tt> class provides the client's entry point to the
* JAXB API. It provides an abstraction for managing the XML/Java binding
* information necessary to implement the JAXB binding framework operations:
* unmarshal, marshal and validate.
*
* <p>A client application normally obtains new instances of this class using
* one of these two styles for newInstance methods, although there are other
* specialized forms of the method available:
*
* <ul>
* <li>{@link #newInstance(String,ClassLoader) JAXBContext.newInstance( "com.acme.foo:com.acme.bar" )} <br/>
* The JAXBContext instance is initialized from a list of colon
* separated Java package names. Each java package contains
* JAXB mapped classes, schema-derived classes and/or user annotated
* classes. Additionally, the java package may contain JAXB package annotations
* that must be processed. (see JLS, Section 7.4.1 "Named Packages").
* </li>
* <li>{@link #newInstance(Class...) JAXBContext.newInstance( com.acme.foo.Foo.class )} <br/>
* The JAXBContext instance is initialized with class(es)
* passed as parameter(s) and classes that are statically reachable from
* these class(es). See {@link #newInstance(Class...)} for details.
* </li>
* </ul>
*
* <p>
* <i><B>SPEC REQUIREMENT:</B> the provider must supply an implementation
* class containing the following method signatures:</i>
*
* <pre>
* public static JAXBContext createContext( String contextPath, ClassLoader classLoader, Map&lt;String,Object> properties ) throws JAXBException
* public static JAXBContext createContext( Class[] classes, Map&lt;String,Object> properties ) throws JAXBException
* </pre>
*
* <p><i>
* The following JAXB 1.0 requirement is only required for schema to
* java interface/implementation binding. It does not apply to JAXB annotated
* classes. JAXB Providers must generate a <tt>jaxb.properties</tt> file in
* each package containing schema derived classes. The property file must
* contain a property named <tt>javax.xml.bind.context.factory</tt> whose
* value is the name of the class that implements the <tt>createContext</tt>
* APIs.</i>
*
* <p><i>
* The class supplied by the provider does not have to be assignable to
* <tt>javax.xml.bind.JAXBContext</tt>, it simply has to provide a class that
* implements the <tt>createContext</tt> APIs.</i>
*
* <p><i>
* In addition, the provider must call the
* {@link DatatypeConverter#setDatatypeConverter(DatatypeConverterInterface)
* DatatypeConverter.setDatatypeConverter} api prior to any client
* invocations of the marshal and unmarshal methods. This is necessary to
* configure the datatype converter that will be used during these operations.</i>
*
* <a name="Unmarshalling"></a>
* <h3>Unmarshalling</h3>
* <p>
* The {@link Unmarshaller} class provides the client application the ability
* to convert XML data into a tree of Java content objects.
* The unmarshal method allows for
* any global XML element declared in the schema to be unmarshalled as
* the root of an instance document.
* Additionally, the unmarshal method allows for an unrecognized root element that
* has an xsi:type attribute's value that references a type definition declared in
* the schema to be unmarshalled as the root of an instance document.
* The <tt>JAXBContext</tt> object
* allows the merging of global elements and type definitions across a set of schemas (listed
* in the <tt>contextPath</tt>). Since each schema in the schema set can belong
* to distinct namespaces, the unification of schemas to an unmarshalling
* context should be namespace independent. This means that a client
* application is able to unmarshal XML documents that are instances of
* any of the schemas listed in the <tt>contextPath</tt>. For example:
*
* <pre>
* JAXBContext jc = JAXBContext.newInstance( "com.acme.foo:com.acme.bar" );
* Unmarshaller u = jc.createUnmarshaller();
* FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) ); // ok
* BarObject barObj = (BarObject)u.unmarshal( new File( "bar.xml" ) ); // ok
* BazObject bazObj = (BazObject)u.unmarshal( new File( "baz.xml" ) ); // error, "com.acme.baz" not in contextPath
* </pre>
*
* <p>
* The client application may also generate Java content trees explicitly rather
* than unmarshalling existing XML data. For all JAXB-annotated value classes,
* an application can create content using constructors.
* For schema-derived interface/implementation classes and for the
* creation of elements that are not bound to a JAXB-annotated
* class, an application needs to have access and knowledge about each of
* the schema derived <tt> ObjectFactory</tt> classes that exist in each of
* java packages contained in the <tt>contextPath</tt>. For each schema
* derived java class, there is a static factory method that produces objects
* of that type. For example,
* assume that after compiling a schema, you have a package <tt>com.acme.foo</tt>
* that contains a schema derived interface named <tt>PurchaseOrder</tt>. In
* order to create objects of that type, the client application would use the
* factory method like this:
*
* <pre>
* com.acme.foo.PurchaseOrder po =
* com.acme.foo.ObjectFactory.createPurchaseOrder();
* </pre>
*
* <p>
* Once the client application has an instance of the the schema derived object,
* it can use the mutator methods to set content on it.
*
* <p>
* For more information on the generated <tt>ObjectFactory</tt> classes, see
* Section 4.2 <i>Java Package</i> of the specification.
*
* <p>
* <i><B>SPEC REQUIREMENT:</B> the provider must generate a class in each
* package that contains all of the necessary object factory methods for that
* package named ObjectFactory as well as the static
* <tt>newInstance( javaContentInterface )</tt> method</i>
*
* <h3>Marshalling</h3>
* <p>
* The {@link Marshaller} class provides the client application the ability
* to convert a Java content tree back into XML data. There is no difference
* between marshalling a content tree that is created manually using the factory
* methods and marshalling a content tree that is the result an <tt>unmarshal
* </tt> operation. Clients can marshal a java content tree back to XML data
* to a <tt>java.io.OutputStream</tt> or a <tt>java.io.Writer</tt>. The
* marshalling process can alternatively produce SAX2 event streams to a
* registered <tt>ContentHandler</tt> or produce a DOM Node object.
* Client applications have control over the output encoding as well as
* whether or not to marshal the XML data as a complete document or
* as a fragment.
*
* <p>
* Here is a simple example that unmarshals an XML document and then marshals
* it back out:
*
* <pre>
* JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
*
* // unmarshal from foo.xml
* Unmarshaller u = jc.createUnmarshaller();
* FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) );
*
* // marshal to System.out
* Marshaller m = jc.createMarshaller();
* m.marshal( fooObj, System.out );
* </pre>
*
*
* <h3>Validation</h3>
* <p>
* Validation has been changed significantly since JAXB 1.0. The {@link Validator}
* class has been deprecated and made optional. This means that you are advised
* not to use this class and, in fact, it may not even be available depending on
* your JAXB provider. JAXB 1.0 client applications that rely on <tt>Validator</tt>
* will still work properly when deployed with the JAXB 1.0 runtime system.
*
* In JAXB 2.0, the {@link Unmarshaller} has included convenince methods that expose
* the JAXP 1.3 {@link javax.xml.validation} framework. Please refer to the
* {@link Unmarshaller#setSchema(javax.xml.validation.Schema)} API for more
* information.
*
*
* <h3>JAXB Runtime Binding Framework Compatibility</h3>
* <p>
* The following JAXB 1.0 restriction only applies to binding schema to
* interfaces/implementation classes.
* Since this binding does not require a common runtime system, a JAXB
* client application must not attempt to mix runtime objects (<tt>JAXBContext,
* Marshaller</tt>, etc. ) from different providers. This does not
* mean that the client application isn't portable, it simply means that a
* client has to use a runtime system provided by the same provider that was
* used to compile the schema.
*
*
* <h3>Discovery of JAXB implementation</h3>
* <p>
* When one of the <tt>newInstance</tt> methods is called, a JAXB implementation is discovered
* by the following steps.
*
* <ol>
* <li>
* For each package/class explicitly passed in to the {@link #newInstance} method, in the order they are specified,
* <tt>jaxb.properties</tt> file is looked up in its package, by using the associated classloader &mdash;
* this is {@link Class#getClassLoader() the owner class loader} for a {@link Class} argument, and for a package
* the specified {@link ClassLoader}.
*
* <p>
* If such a file is discovered, it is {@link Properties#load(InputStream) loaded} as a property file, and
* the value of the {@link #JAXB_CONTEXT_FACTORY} key will be assumed to be the provider factory class.
* This class is then loaded by the associated classloader discussed above.
*
* <p>
* This phase of the look up allows some packages to force the use of a certain JAXB implementation.
* (For example, perhaps the schema compiler has generated some vendor extension in the code.)
*
* <li>
* If the system property {@link #JAXB_CONTEXT_FACTORY} exists, then its value is assumed to be the provider
* factory class. This phase of the look up enables per-JVM override of the JAXB implementation.
*
* <li>
* Look for <tt>/META-INF/services/javax.xml.bind.JAXBContext</tt> file in the associated classloader.
* This file follows the standard service descriptor convention, and if such a file exists, its content
* is assumed to be the provider factory class. This phase of the look up is for automatic discovery.
* It allows users to just put a JAXB implementation in a classpath and use it without any furhter configuration.
*
* <li>
* Finally, if all the steps above fail, then the rest of the look up is unspecified. That said,
* the recommended behavior is to simply look for some hard-coded platform default JAXB implementation.
* This phase of the look up is so that JavaSE can have its own JAXB implementation as the last resort.
* </ol>
*
* <p>
* Once the provider factory class is discovered, its
* <tt>public static JAXBContext createContext(String,ClassLoader,Map)</tt> method
* (see {@link #newInstance(String, ClassLoader, Map)} for the parameter semantics.)
* or <tt>public static JAXBContext createContet(Class[],Map)</tt> method
* (see {@link #newInstance(Class[], Map)} for the parameter semantics) are invoked
* to create a {@link JAXBContext}.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see Marshaller
* @see Unmarshaller
* @see S 7.4.1 "Named Packages" in Java Language Specification</a>
* @since JAXB1.0
*/
public abstract class JAXBContext {
/**
* The name of the property that contains the name of the class capable
* of creating new <tt>JAXBContext</tt> objects.
*/
public static final String JAXB_CONTEXT_FACTORY =
"javax.xml.bind.context.factory";
protected JAXBContext() {
}
/**
* <p>
* Obtain a new instance of a <tt>JAXBContext</tt> class.
*
* <p>
* This is a convenience method to invoke the
* {@link #newInstance(String,ClassLoader)} method with
* the context class loader of the current thread.
*
* @throws JAXBException if an error was encountered while creating the
* <tt>JAXBContext</tt> such as
* <ol>
* <li>failure to locate either ObjectFactory.class or jaxb.index in the packages</li>
* <li>an ambiguity among global elements contained in the contextPath</li>
* <li>failure to locate a value for the context factory provider property</li>
* <li>mixing schema derived packages from different providers on the same contextPath</li>
* </ol>
*/
public static JAXBContext newInstance( String contextPath )
throws JAXBException {
//return newInstance( contextPath, JAXBContext.class.getClassLoader() );
return newInstance( contextPath, getContextClassLoader());
}
/**
* <p>
* Obtain a new instance of a <tt>JAXBContext</tt> class.
*
* <p>
* The client application must supply a context path which is a list of
* colon (':', \u005Cu003A) separated java package names that contain
* schema-derived classes and/or fully qualified JAXB-annotated classes.
* Schema-derived
* code is registered with the JAXBContext by the
* ObjectFactory.class generated per package.
* Alternatively than being listed in the context path, programmer
* annotated JAXB mapped classes can be listed in a
* <tt>jaxb.index</tt> resource file, format described below.
* Note that a java package can contain both schema-derived classes and
* user annotated JAXB classes. Additionally, the java package may
* contain JAXB package annotations that must be processed. (see JLS,
* Section 7.4.1 "Named Packages").
* </p>
*
* <p>
* Every package listed on the contextPath must meet <b>one or both</b> of the
* following conditions otherwise a <tt>JAXBException</tt> will be thrown:
* </p>
* <ol>
* <li>it must contain ObjectFactory.class</li>
* <li>it must contain jaxb.index</li>
* </ol>
*
* <p>
* <b>Format for jaxb.index</b>
* <p>
* The file contains a newline-separated list of class names.
* Space and tab characters, as well as blank
* lines, are ignored. The comment character
* is '#' (0x23); on each line all characters following the first comment
* character are ignored. The file must be encoded in UTF-8. Classes that
* are reachable, as defined in {@link #newInstance(Class...)}, from the
* listed classes are also registered with JAXBContext.
* <p>
* Constraints on class name occuring in a <tt>jaxb.index</tt> file are:
* <ul>
* <li>Must not end with ".class".</li>
* <li>Class names are resolved relative to package containing
* <tt>jaxb.index</tt> file. Only classes occuring directly in package
* containing <tt>jaxb.index</tt> file are allowed.</li>
* <li>Fully qualified class names are not allowed.
* A qualified class name,relative to current package,
* is only allowed to specify a nested or inner class.</li>
* </ul>
*
* <p>
* To maintain compatibility with JAXB 1.0 schema to java
* interface/implementation binding, enabled by schema customization
* <tt>&lt;jaxb:globalBindings valueClass="false"></tt>,
* the JAXB provider will ensure that each package on the context path
* has a <tt>jaxb.properties</tt> file which contains a value for the
* <tt>javax.xml.bind.context.factory</tt> property and that all values
* resolve to the same provider. This requirement does not apply to
* JAXB annotated classes.
*
* <p>
* If there are any global XML element name collisions across the various
* packages listed on the <tt>contextPath</tt>, a <tt>JAXBException</tt>
* will be thrown.
*
* <p>
* Mixing generated interface/impl bindings from multiple JAXB Providers
* in the same context path may result in a <tt>JAXBException</tt>
* being thrown.
*
* <p>
* The steps involved in discovering the JAXB implementation is discussed in the class javadoc.
*
* @param contextPath list of java package names that contain schema
* derived class and/or java to schema (JAXB-annotated)
* mapped classes
* @param classLoader
* This class loader will be used to locate the implementation
* classes.
*
* @return a new instance of a <tt>JAXBContext</tt>
* @throws JAXBException if an error was encountered while creating the
* <tt>JAXBContext</tt> such as
* <ol>
* <li>failure to locate either ObjectFactory.class or jaxb.index in the packages</li>
* <li>an ambiguity among global elements contained in the contextPath</li>
* <li>failure to locate a value for the context factory provider property</li>
* <li>mixing schema derived packages from different providers on the same contextPath</li>
* </ol>
*/
public static JAXBContext newInstance( String contextPath, ClassLoader classLoader ) throws JAXBException {
return newInstance(contextPath,classLoader,Collections.<String,Object>emptyMap());
}
/**
* <p>
* Obtain a new instance of a <tt>JAXBContext</tt> class.
*
* <p>
* This is mostly the same as {@link JAXBContext#newInstance(String, ClassLoader)},
* but this version allows you to pass in provider-specific properties to configure
* the instantiation of {@link JAXBContext}.
*
* <p>
* The interpretation of properties is up to implementations. Implementations should
* throw <tt>JAXBException</tt> if it finds properties that it doesn't understand.
*
* @param contextPath list of java package names that contain schema derived classes
* @param classLoader
* This class loader will be used to locate the implementation classes.
* @param properties
* provider-specific properties. Can be null, which means the same thing as passing
* in an empty map.
*
* @return a new instance of a <tt>JAXBContext</tt>
* @throws JAXBException if an error was encountered while creating the
* <tt>JAXBContext</tt> such as
* <ol>
* <li>failure to locate either ObjectFactory.class or jaxb.index in the packages</li>
* <li>an ambiguity among global elements contained in the contextPath</li>
* <li>failure to locate a value for the context factory provider property</li>
* <li>mixing schema derived packages from different providers on the same contextPath</li>
* </ol>
* @since JAXB2.0
*/
public static JAXBContext newInstance( String contextPath, ClassLoader classLoader, Map<String,?> properties )
throws JAXBException {
return ContextFinder.find(
/* The default property name according to the JAXB spec */
JAXB_CONTEXT_FACTORY,
/* the context path supplied by the client app */
contextPath,
/* class loader to be used */
classLoader,
properties );
}
// TODO: resurrect this once we introduce external annotations
// /**
// * <p>
// * Obtain a new instance of a <tt>JAXBContext</tt> class.
// *
// * <p>
// * The client application must supply a list of classes that the new
// * context object needs to recognize.
// *
// * Not only the new context will recognize all the classes specified,
// * but it will also recognize any classes that are directly/indirectly
// * referenced statically from the specified classes.
// *
// * For example, in the following Java code, if you do
// * <tt>newInstance(Foo.class)</tt>, the newly created {@link JAXBContext}
// * will recognize both <tt>Foo</tt> and <tt>Bar</tt>, but not <tt>Zot</tt>:
// * <pre>
// * class Foo {
// * Bar b;
// * }
// * class Bar { int x; }
// * class Zot extends Bar { int y; }
// * </pre>
// *
// * Therefore, a typical client application only needs to specify the
// * top-level classes, but it needs to be careful.
// *
// * TODO: if we are to define other mechanisms, refer to them.
// *
// * @param externalBindings
// * list of external binding files. Can be null or empty if none is used.
// * when specified, those files determine how the classes are bound.
// *
// * @param classesToBeBound
// * list of java classes to be recognized by the new {@link JAXBContext}.
// * Can be empty, in which case a {@link JAXBContext} that only knows about
// * spec-defined classes will be returned.
// *
// * @return
// * A new instance of a <tt>JAXBContext</tt>. Always non-null valid object.
// *
// * @throws JAXBException
// * if an error was encountered while creating the
// * <tt>JAXBContext</tt>, such as (but not limited to):
// * <ol>
// * <li>No JAXB implementation was discovered
// * <li>Classes use JAXB annotations incorrectly
// * <li>Classes have colliding annotations (i.e., two classes with the same type name)
// * <li>Specified external bindings are incorrect
// * <li>The JAXB implementation was unable to locate
// * provider-specific out-of-band information (such as additional
// * files generated at the development time.)
// * </ol>
// *
// * @throws IllegalArgumentException
// * if the parameter contains {@code null} (i.e., {@code newInstance(null);})
// *
// * @since JAXB2.0
// */
// public static JAXBContext newInstance( Source[] externalBindings, Class... classesToBeBound )
// throws JAXBException {
//
// // empty class list is not an error, because the context will still include
// // spec-specified classes like String and Integer.
// // if(classesToBeBound.length==0)
// // throw new IllegalArgumentException();
//
// // but it is an error to have nulls in it.
// for( int i=classesToBeBound.length-1; i>=0; i-- )
// if(classesToBeBound[i]==null)
// throw new IllegalArgumentException();
//
// return ContextFinder.find(externalBindings,classesToBeBound);
// }
/**
* <p>
* Obtain a new instance of a <tt>JAXBContext</tt> class.
*
* <p>
* The client application must supply a list of classes that the new
* context object needs to recognize.
*
* Not only the new context will recognize all the classes specified,
* but it will also recognize any classes that are directly/indirectly
* referenced statically from the specified classes. Subclasses of
* referenced classes nor <tt>&#64;XmlTransient</tt> referenced classes
* are not registered with JAXBContext.
*
* For example, in the following Java code, if you do
* <tt>newInstance(Foo.class)</tt>, the newly created {@link JAXBContext}
* will recognize both <tt>Foo</tt> and <tt>Bar</tt>, but not <tt>Zot</tt> or <tt>FooBar</tt>:
* <pre>
* class Foo {
* &#64;XmlTransient FooBar c;
* Bar b;
* }
* class Bar { int x; }
* class Zot extends Bar { int y; }
* class FooBar { }
* </pre>
*
* Therefore, a typical client application only needs to specify the
* top-level classes, but it needs to be careful.
*
* <p>
* Note that for each java package registered with JAXBContext,
* when the optional package annotations exist, they must be processed.
* (see JLS, Section 7.4.1 "Named Packages").
*
* <p>
* The steps involved in discovering the JAXB implementation is discussed in the class javadoc.
*
* @param classesToBeBound
* list of java classes to be recognized by the new {@link JAXBContext}.
* Can be empty, in which case a {@link JAXBContext} that only knows about
* spec-defined classes will be returned.
*
* @return
* A new instance of a <tt>JAXBContext</tt>. Always non-null valid object.
*
* @throws JAXBException
* if an error was encountered while creating the
* <tt>JAXBContext</tt>, such as (but not limited to):
* <ol>
* <li>No JAXB implementation was discovered
* <li>Classes use JAXB annotations incorrectly
* <li>Classes have colliding annotations (i.e., two classes with the same type name)
* <li>The JAXB implementation was unable to locate
* provider-specific out-of-band information (such as additional
* files generated at the development time.)
* </ol>
*
* @throws IllegalArgumentException
* if the parameter contains {@code null} (i.e., {@code newInstance(null);})
*
* @since JAXB2.0
*/
public static JAXBContext newInstance( Class... classesToBeBound )
throws JAXBException {
return newInstance(classesToBeBound,Collections.<String,Object>emptyMap());
}
/**
* <p>
* Obtain a new instance of a <tt>JAXBContext</tt> class.
*
* <p>
* An overloading of {@link JAXBContext#newInstance(Class...)}
* to configure 'properties' for this instantiation of {@link JAXBContext}.
*
* <p>
* The interpretation of properties is up to implementations. Implementations should
* throw <tt>JAXBException</tt> if it finds properties that it doesn't understand.
*
* @param classesToBeBound
* list of java classes to be recognized by the new {@link JAXBContext}.
* Can be empty, in which case a {@link JAXBContext} that only knows about
* spec-defined classes will be returned.
* @param properties
* provider-specific properties. Can be null, which means the same thing as passing
* in an empty map.
*
* @return
* A new instance of a <tt>JAXBContext</tt>. Always non-null valid object.
*
* @throws JAXBException
* if an error was encountered while creating the
* <tt>JAXBContext</tt>, such as (but not limited to):
* <ol>
* <li>No JAXB implementation was discovered
* <li>Classes use JAXB annotations incorrectly
* <li>Classes have colliding annotations (i.e., two classes with the same type name)
* <li>The JAXB implementation was unable to locate
* provider-specific out-of-band information (such as additional
* files generated at the development time.)
* </ol>
*
* @throws IllegalArgumentException
* if the parameter contains {@code null} (i.e., {@code newInstance(null,someMap);})
*
* @since JAXB2.0
*/
public static JAXBContext newInstance( Class[] classesToBeBound, Map<String,?> properties )
throws JAXBException {
if (classesToBeBound == null) {
throw new IllegalArgumentException();
}
// but it is an error to have nulls in it.
for (int i = classesToBeBound.length - 1; i >= 0; i--) {
if (classesToBeBound[i] == null) {
throw new IllegalArgumentException();
}
}
return ContextFinder.find(classesToBeBound,properties);
}
/**
* Create an <tt>Unmarshaller</tt> object that can be used to convert XML
* data into a java content tree.
*
* @return an <tt>Unmarshaller</tt> object
*
* @throws JAXBException if an error was encountered while creating the
* <tt>Unmarshaller</tt> object
*/
public abstract Unmarshaller createUnmarshaller() throws JAXBException;
/**
* Create a <tt>Marshaller</tt> object that can be used to convert a
* java content tree into XML data.
*
* @return a <tt>Marshaller</tt> object
*
* @throws JAXBException if an error was encountered while creating the
* <tt>Marshaller</tt> object
*/
public abstract Marshaller createMarshaller() throws JAXBException;
/**
* {@link Validator} has been made optional and deprecated in JAXB 2.0. Please
* refer to the javadoc for {@link Validator} for more detail.
* <p>
* Create a <tt>Validator</tt> object that can be used to validate a
* java content tree against its source schema.
*
* @return a <tt>Validator</tt> object
*
* @throws JAXBException if an error was encountered while creating the
* <tt>Validator</tt> object
* @deprecated since JAXB2.0
*/
public abstract Validator createValidator() throws JAXBException;
/**
* Creates a <tt>Binder</tt> object that can be used for
* associative/in-place unmarshalling/marshalling.
*
* @param domType select the DOM API to use by passing in its DOM Node class.
*
* @return always a new valid <tt>Binder</tt> object.
*
* @throws UnsupportedOperationException
* if DOM API corresponding to <tt>domType</tt> is not supported by
* the implementation.
*
* @since JAXB2.0
*/
public <T> Binder<T> createBinder(Class<T> domType) {
// to make JAXB 1.0 implementations work, this method must not be
// abstract
throw new UnsupportedOperationException();
}
/**
* Creates a <tt>Binder</tt> for W3C DOM.
*
* @return always a new valid <tt>Binder</tt> object.
*
* @since JAXB2.0
*/
public Binder<Node> createBinder() {
return createBinder(Node.class);
}
/**
* Creates a <tt>JAXBIntrospector</tt> object that can be used to
* introspect JAXB objects.
*
* @return
* always return a non-null valid <tt>JAXBIntrospector</tt> object.
*
* @throws UnsupportedOperationException
* Calling this method on JAXB 1.0 implementations will throw
* an UnsupportedOperationException.
*
* @since JAXB2.0
*/
public JAXBIntrospector createJAXBIntrospector() {
// to make JAXB 1.0 implementations work, this method must not be
// abstract
throw new UnsupportedOperationException();
}
/**
* Generates the schema documents for this context.
*
* @param outputResolver
* this object controls the output to which schemas
* will be sent.
*
* @throws IOException
* if {@link SchemaOutputResolver} throws an {@link IOException}.
*
* @throws UnsupportedOperationException
* Calling this method on JAXB 1.0 implementations will throw
* an UnsupportedOperationException.
*
* @since JAXB 2.0
*/
public void generateSchema(SchemaOutputResolver outputResolver) throws IOException {
// to make JAXB 1.0 implementations work, this method must not be
// abstract
throw new UnsupportedOperationException();
}
private static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
}
}

View File

@@ -0,0 +1,218 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.namespace.QName;
import java.io.Serializable;
/**
* <p>JAXB representation of an Xml Element.</p>
*
* <p>This class represents information about an Xml Element from both the element
* declaration within a schema and the element instance value within an xml document
* with the following properties
* <ul>
* <li>element's xml tag <b><tt>name</tt></b></li>
* <li><b><tt>value</tt></b> represents the element instance's atttribute(s) and content model</li>
* <li>element declaration's <b><tt>declaredType</tt></b> (<tt>xs:element @type</tt> attribute)</li>
* <li><b><tt>scope</tt></b> of element declaration</li>
* <li>boolean <b><tt>nil</tt></b> property. (element instance's <tt><b>xsi:nil</b></tt> attribute)</li>
* </ul>
*
* <p>The <tt>declaredType</tt> and <tt>scope</tt> property are the
* JAXB class binding for the xml type definition.
* </p>
*
* <p><b><tt>Scope</tt></b> is either {@link GlobalScope} or the Java class representing the
* complex type definition containing the schema element declaration.
* </p>
*
* <p>There is a property constraint that if <b><tt>value</tt></b> is <tt>null</tt>,
* then <tt>nil</tt> must be <tt>true</tt>. The converse is not true to enable
* representing a nil element with attribute(s). If <tt>nil</tt> is true, it is possible
* that <tt>value</tt> is non-null so it can hold the value of the attributes
* associated with a nil element.
* </p>
*
* @author Kohsuke Kawaguchi, Joe Fialli
* @since JAXB 2.0
*/
public class JAXBElement<T> implements Serializable {
/** xml element tag name */
final protected QName name;
/** Java datatype binding for xml element declaration's type. */
final protected Class<T> declaredType;
/** Scope of xml element declaration representing this xml element instance.
* Can be one of the following values:
* - {@link GlobalScope} for global xml element declaration.
* - local element declaration has a scope set to the Java class
* representation of complex type defintion containing
* xml element declaration.
*/
final protected Class scope;
/** xml element value.
Represents content model and attributes of an xml element instance. */
protected T value;
/** true iff the xml element instance has xsi:nil="true". */
protected boolean nil = false;
/**
* Designates global scope for an xml element.
*/
public static final class GlobalScope {}
/**
* <p>Construct an xml element instance.</p>
*
* @param name Java binding of xml element tag name
* @param declaredType Java binding of xml element declaration's type
* @param scope
* Java binding of scope of xml element declaration.
* Passing null is the same as passing <tt>GlobalScope.class</tt>
* @param value
* Java instance representing xml element's value.
* @see #getScope()
* @see #isTypeSubstituted()
*/
public JAXBElement(QName name,
Class<T> declaredType,
Class scope,
T value) {
if(declaredType==null || name==null)
throw new IllegalArgumentException();
this.declaredType = declaredType;
if(scope==null) scope = GlobalScope.class;
this.scope = scope;
this.name = name;
setValue(value);
}
/**
* Construct an xml element instance.
*
* This is just a convenience method for <tt>new JAXBElement(name,declaredType,GlobalScope.class,value)</tt>
*/
public JAXBElement(QName name, Class<T> declaredType, T value ) {
this(name,declaredType,GlobalScope.class,value);
}
/**
* Returns the Java binding of the xml element declaration's type attribute.
*/
public Class<T> getDeclaredType() {
return declaredType;
}
/**
* Returns the xml element tag name.
*/
public QName getName() {
return name;
}
/**
* <p>Set the content model and attributes of this xml element.</p>
*
* <p>When this property is set to <tt>null</tt>, <tt>isNil()</tt> must by <tt>true</tt>.
* Details of constraint are described at {@link #isNil()}.</p>
*
* @see #isTypeSubstituted()
*/
public void setValue(T t) {
this.value = t;
}
/**
* <p>Return the content model and attribute values for this element.</p>
*
* <p>See {@link #isNil()} for a description of a property constraint when
* this value is <tt>null</tt></p>
*/
public T getValue() {
return value;
}
/**
* Returns scope of xml element declaration.
*
* @see #isGlobalScope()
* @return <tt>GlobalScope.class</tt> if this element is of global scope.
*/
public Class getScope() {
return scope;
}
/**
* <p>Returns <tt>true</tt> iff this element instance content model
* is nil.</p>
*
* <p>This property always returns <tt>true</tt> when {@link #getValue()} is null.
* Note that the converse is not true, when this property is <tt>true</tt>,
* {@link #getValue()} can contain a non-null value for attribute(s). It is
* valid for a nil xml element to have attribute(s).</p>
*/
public boolean isNil() {
return (value == null) || nil;
}
/**
* <p>Set whether this element has nil content.</p>
*
* @see #isNil()
*/
public void setNil(boolean value) {
this.nil = value;
}
/* Convenience methods
* (Not necessary but they do unambiguously conceptualize
* the rationale behind this class' fields.)
*/
/**
* Returns true iff this xml element declaration is global.
*/
public boolean isGlobalScope() {
return this.scope == GlobalScope.class;
}
/**
* Returns true iff this xml element instance's value has a different
* type than xml element declaration's declared type.
*/
public boolean isTypeSubstituted() {
if(value==null) return false;
return value.getClass() != declaredType;
}
private static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,184 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import java.io.PrintWriter;
/**
* This is the root exception class for all JAXB exceptions.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see JAXBContext
* @see Marshaller
* @see Unmarshaller
* @since JAXB1.0
*/
public class JAXBException extends Exception {
/**
* Vendor specific error code
*
*/
private String errorCode;
/**
* Exception reference
*
*/
private volatile Throwable linkedException;
static final long serialVersionUID = -5621384651494307979L;
/**
* Construct a JAXBException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public JAXBException(String message) {
this( message, null, null );
}
/**
* Construct a JAXBException with the specified detail message and vendor
* specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public JAXBException(String message, String errorCode) {
this( message, errorCode, null );
}
/**
* Construct a JAXBException with a linkedException. The detail message and
* vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public JAXBException(Throwable exception) {
this( null, null, exception );
}
/**
* Construct a JAXBException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public JAXBException(String message, Throwable exception) {
this( message, null, exception );
}
/**
* Construct a JAXBException with the specified detail message, vendor
* specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public JAXBException(String message, String errorCode, Throwable exception) {
super( message );
this.errorCode = errorCode;
this.linkedException = exception;
}
/**
* Get the vendor specific error code
*
* @return a string specifying the vendor specific error code
*/
public String getErrorCode() {
return this.errorCode;
}
/**
* Get the linked exception
*
* @return the linked Exception, null if none exists
*/
public Throwable getLinkedException() {
return linkedException;
}
/**
* Add a linked Exception.
*
* @param exception the linked Exception (A null value is permitted and
* indicates that the linked exception does not exist or
* is unknown).
*/
public void setLinkedException( Throwable exception ) {
this.linkedException = exception;
}
/**
* Returns a short description of this JAXBException.
*
*/
public String toString() {
return linkedException == null ?
super.toString() :
super.toString() + "\n - with linked exception:\n[" +
linkedException.toString()+ "]";
}
/**
* Prints this JAXBException and its stack trace (including the stack trace
* of the linkedException if it is non-null) to the PrintStream.
*
* @param s PrintStream to use for output
*/
public void printStackTrace( java.io.PrintStream s ) {
super.printStackTrace(s);
}
/**
* Prints this JAXBException and its stack trace (including the stack trace
* of the linkedException if it is non-null) to <tt>System.err</tt>.
*
*/
public void printStackTrace() {
super.printStackTrace();
}
/**
* Prints this JAXBException and its stack trace (including the stack trace
* of the linkedException if it is non-null) to the PrintWriter.
*
* @param s PrintWriter to use for output
*/
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
}
@Override
public Throwable getCause() {
return linkedException;
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.namespace.QName;
/**
* Provide access to JAXB xml binding data for a JAXB object.
*
* <p>
* Intially, the intent of this class is to just conceptualize how
* a JAXB application developer can access xml binding information,
* independent if binding model is java to schema or schema to java.
* Since accessing the XML element name related to a JAXB element is
* a highly requested feature, demonstrate access to this
* binding information.
*
* The factory method to get a <code>JAXBIntrospector</code> instance is
* {@link JAXBContext#createJAXBIntrospector()}.
*
* @see JAXBContext#createJAXBIntrospector()
* @since JAXB2.0
*/
public abstract class JAXBIntrospector {
/**
* <p>Return true if <code>object</code> represents a JAXB element.</p>
* <p>Parameter <code>object</code> is a JAXB element for following cases:
* <ol>
* <li>It is an instance of <code>javax.xml.bind.JAXBElement</code>.</li>
* <li>The class of <code>object</code> is annotated with
* <code>&#64XmlRootElement</code>.
* </li>
* </ol>
*
* @see #getElementName(Object)
*/
public abstract boolean isElement(Object object);
/**
* <p>Get xml element qname for <code>jaxbElement</code>.</p>
*
* @param jaxbElement is an object that {@link #isElement(Object)} returned true.
*
* @return xml element qname associated with jaxbElement;
* null if <code>jaxbElement</code> is not a JAXB Element.
*/
public abstract QName getElementName(Object jaxbElement);
/**
* <p>Get the element value of a JAXB element.</p>
*
* <p>Convenience method to abstract whether working with either
* a javax.xml.bind.JAXBElement instance or an instance of
* <tt>&#64XmlRootElement</tt> annotated Java class.</p>
*
* @param jaxbElement object that #isElement(Object) returns true.
*
* @return The element value of the <code>jaxbElement</code>.
*/
public static Object getValue(Object jaxbElement) {
if (jaxbElement instanceof JAXBElement) {
return ((JAXBElement)jaxbElement).getValue();
} else {
// assume that class of this instance is
// annotated with @XmlRootElement.
return jaxbElement;
}
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import java.security.BasicPermission;
/**
* This class is for JAXB permissions. A {@code JAXBPermission}
* contains a name (also referred to as a "target name") but
* no actions list; you either have the named permission
* or you don't.
*
* <P>
* The target name is the name of the JAXB permission (see below).
*
* <P>
* The following table lists all the possible {@code JAXBPermission} target names,
* and for each provides a description of what the permission allows
* and a discussion of the risks of granting code the permission.
* <P>
*
* <table border=1 cellpadding=5 summary="Permission target name, what the permission allows, and associated risks">
* <tr>
* <th>Permission Target Name</th>
* <th>What the Permission Allows</th>
* <th>Risks of Allowing this Permission</th>
* </tr>
*
* <tr>
* <td>setDatatypeConverter</td>
* <td>
* Allows the code to set VM-wide {@link DatatypeConverterInterface}
* via {@link DatatypeConverter#setDatatypeConverter(DatatypeConverterInterface) the setDatatypeConverter method}
* that all the methods on {@link DatatypeConverter} uses.
* </td>
* <td>
* Malicious code can set {@link DatatypeConverterInterface}, which has
* VM-wide singleton semantics, before a genuine JAXB implementation sets one.
* This allows malicious code to gain access to objects that it may otherwise
* not have access to, such as {@link java.awt.Frame#getFrames()} that belongs to
* another application running in the same JVM.
* </td>
* </tr>
* </table>
*
* @see java.security.BasicPermission
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionCollection
* @see java.lang.SecurityManager
*
* @author Joe Fialli
* @since JAXB 2.2
*/
/* code was borrowed originally from java.lang.RuntimePermission. */
public final class JAXBPermission extends BasicPermission {
/**
* Creates a new JAXBPermission with the specified name.
*
* @param name
* The name of the JAXBPermission. As of 2.2 only "setDatatypeConverter"
* is defined.
*/
public JAXBPermission(String name) {
super(name);
}
private static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This exception indicates that an error has occurred while performing
* a marshal operation that the provider is unable to recover from.
*
* <p>
* The <tt>ValidationEventHandler</tt> can cause this exception to be thrown
* during the marshal operations. See
* {@link ValidationEventHandler#handleEvent(ValidationEvent)
* ValidationEventHandler.handleEvent(ValidationEvent)}.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see JAXBException
* @see Marshaller
* @since JAXB1.0
*/
public class MarshalException extends JAXBException {
/**
* Construct a MarshalException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public MarshalException( String message ) {
this( message, null, null );
}
/**
* Construct a MarshalException with the specified detail message and vendor
* specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public MarshalException( String message, String errorCode ) {
this( message, errorCode, null );
}
/**
* Construct a MarshalException with a linkedException. The detail message and
* vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public MarshalException( Throwable exception ) {
this( null, null, exception );
}
/**
* Construct a MarshalException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public MarshalException( String message, Throwable exception ) {
this( message, null, exception );
}
/**
* Construct a MarshalException with the specified detail message, vendor
* specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public MarshalException( String message, String errorCode, Throwable exception ) {
super( message, errorCode, exception );
}
}

View File

@@ -0,0 +1,821 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.validation.Schema;
import java.io.File;
/**
* <p>
* The <tt>Marshaller</tt> class is responsible for governing the process
* of serializing Java content trees back into XML data. It provides the basic
* marshalling methods:
*
* <p>
* <i>Assume the following setup code for all following code fragments:</i>
* <blockquote>
* <pre>
* JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
* Unmarshaller u = jc.createUnmarshaller();
* Object element = u.unmarshal( new File( "foo.xml" ) );
* Marshaller m = jc.createMarshaller();
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a File:
* <blockquote>
* <pre>
* OutputStream os = new FileOutputStream( "nosferatu.xml" );
* m.marshal( element, os );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a SAX ContentHandler:
* <blockquote>
* <pre>
* // assume MyContentHandler instanceof ContentHandler
* m.marshal( element, new MyContentHandler() );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a DOM Node:
* <blockquote>
* <pre>
* DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
* dbf.setNamespaceAware(true);
* DocumentBuilder db = dbf.newDocumentBuilder();
* Document doc = db.newDocument();
*
* m.marshal( element, doc );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a java.io.OutputStream:
* <blockquote>
* <pre>
* m.marshal( element, System.out );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a java.io.Writer:
* <blockquote>
* <pre>
* m.marshal( element, new PrintWriter( System.out ) );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a javax.xml.transform.SAXResult:
* <blockquote>
* <pre>
* // assume MyContentHandler instanceof ContentHandler
* SAXResult result = new SAXResult( new MyContentHandler() );
*
* m.marshal( element, result );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a javax.xml.transform.DOMResult:
* <blockquote>
* <pre>
* DOMResult result = new DOMResult();
*
* m.marshal( element, result );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a javax.xml.transform.StreamResult:
* <blockquote>
* <pre>
* StreamResult result = new StreamResult( System.out );
*
* m.marshal( element, result );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a javax.xml.stream.XMLStreamWriter:
* <blockquote>
* <pre>
* XMLStreamWriter xmlStreamWriter =
* XMLOutputFactory.newInstance().createXMLStreamWriter( ... );
*
* m.marshal( element, xmlStreamWriter );
* </pre>
* </blockquote>
*
* <p>
* Marshalling to a javax.xml.stream.XMLEventWriter:
* <blockquote>
* <pre>
* XMLEventWriter xmlEventWriter =
* XMLOutputFactory.newInstance().createXMLEventWriter( ... );
*
* m.marshal( element, xmlEventWriter );
* </pre>
* </blockquote>
*
* <p>
* <a name="elementMarshalling"></a>
* <b>Marshalling content tree rooted by a JAXB element</b><br>
* <blockquote>
* The first parameter of the overloaded
* <tt>Marshaller.marshal(java.lang.Object, ...)</tt> methods must be a
* JAXB element as computed by
* {@link JAXBIntrospector#isElement(java.lang.Object)};
* otherwise, a <tt>Marshaller.marshal</tt> method must throw a
* {@link MarshalException}. There exist two mechanisms
* to enable marshalling an instance that is not a JAXB element.
* One method is to wrap the instance as a value of a {@link JAXBElement},
* and pass the wrapper element as the first parameter to
* a <tt>Marshaller.marshal</tt> method. For java to schema binding, it
* is also possible to simply annotate the instance's class with
* &#64;{@link XmlRootElement}.
* </blockquote>
*
* <p>
* <b>Encoding</b><br>
* <blockquote>
* By default, the Marshaller will use UTF-8 encoding when generating XML data
* to a <tt>java.io.OutputStream</tt>, or a <tt>java.io.Writer</tt>. Use the
* {@link #setProperty(String,Object) setProperty} API to change the output
* encoding used during these marshal operations. Client applications are
* expected to supply a valid character encoding name as defined in the
* <a href="http://www.w3.org/TR/2000/REC-xml-20001006#charencoding">W3C XML 1.0
* Recommendation</a> and supported by your Java Platform</a>.
* </blockquote>
*
* <p>
* <b>Validation and Well-Formedness</b><br>
* <blockquote>
* <p>
* Client applications are not required to validate the Java content tree prior
* to calling any of the marshal API's. Furthermore, there is no requirement
* that the Java content tree be valid with respect to its original schema in
* order to marshal it back into XML data. Different JAXB Providers will
* support marshalling invalid Java content trees at varying levels, however
* all JAXB Providers must be able to marshal a valid content tree back to
* XML data. A JAXB Provider must throw a <tt>MarshalException</tt> when it
* is unable to complete the marshal operation due to invalid content. Some
* JAXB Providers will fully allow marshalling invalid content, others will fail
* on the first validation error.
* <p>
* Even when schema validation is not explictly enabled for the marshal operation,
* it is possible that certain types of validation events will be detected
* during the operation. Validation events will be reported to the registered
* event handler. If the client application has not registered an event handler
* prior to invoking one of the marshal API's, then events will be delivered to
* a default event handler which will terminate the marshal operation after
* encountering the first error or fatal error. Note that for JAXB 2.0 and
* later versions, {@link javax.xml.bind.helpers.DefaultValidationEventHandler} is
* no longer used.
*
* </blockquote>
*
* <p>
* <a name="supportedProps"></a>
* <b>Supported Properties</b><br>
* <blockquote>
* <p>
* All JAXB Providers are required to support the following set of properties.
* Some providers may support additional properties.
* <dl>
* <dt><tt>jaxb.encoding</tt> - value must be a java.lang.String</dt>
* <dd>The output encoding to use when marshalling the XML data. The
* Marshaller will use "UTF-8" by default if this property is not
* specified.</dd>
* <dt><tt>jaxb.formatted.output</tt> - value must be a java.lang.Boolean</dt>
* <dd>This property controls whether or not the Marshaller will format
* the resulting XML data with line breaks and indentation. A
* true value for this property indicates human readable indented
* xml data, while a false value indicates unformatted xml data.
* The Marshaller will default to false (unformatted) if this
* property is not specified.</dd>
* <dt><tt>jaxb.schemaLocation</tt> - value must be a java.lang.String</dt>
* <dd>This property allows the client application to specify an
* xsi:schemaLocation attribute in the generated XML data. The format of
* the schemaLocation attribute value is discussed in an easy to
* understand, non-normative form in
* <a href="http://www.w3.org/TR/xmlschema-0/#schemaLocation">Section 5.6
* of the W3C XML Schema Part 0: Primer</a> and specified in
* <a href="http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions">
* Section 2.6 of the W3C XML Schema Part 1: Structures</a>.</dd>
* <dt><tt>jaxb.noNamespaceSchemaLocation</tt> - value must be a java.lang.String</dt>
* <dd>This property allows the client application to specify an
* xsi:noNamespaceSchemaLocation attribute in the generated XML
* data. The format of the schemaLocation attribute value is discussed in
* an easy to understand, non-normative form in
* <a href="http://www.w3.org/TR/xmlschema-0/#schemaLocation">Section 5.6
* of the W3C XML Schema Part 0: Primer</a> and specified in
* <a href="http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions">
* Section 2.6 of the W3C XML Schema Part 1: Structures</a>.</dd>
* <dt><tt>jaxb.fragment</tt> - value must be a java.lang.Boolean</dt>
* <dd>This property determines whether or not document level events will be
* generated by the Marshaller. If the property is not specified, the
* default is <tt>false</tt>. This property has different implications depending
* on which marshal api you are using - when this property is set to true:<br>
* <ul>
* <li>{@link #marshal(Object,org.xml.sax.ContentHandler) marshal(Object,ContentHandler)} - the Marshaller won't
* invoke {@link org.xml.sax.ContentHandler#startDocument()} and
* {@link org.xml.sax.ContentHandler#endDocument()}.</li>
* <li>{@link #marshal(Object,org.w3c.dom.Node) marshal(Object,Node)} - the property has no effect on this
* API.</li>
* <li>{@link #marshal(Object,java.io.OutputStream) marshal(Object,OutputStream)} - the Marshaller won't
* generate an xml declaration.</li>
* <li>{@link #marshal(Object,java.io.Writer) marshal(Object,Writer)} - the Marshaller won't
* generate an xml declaration.</li>
* <li>{@link #marshal(Object,javax.xml.transform.Result) marshal(Object,Result)} - depends on the kind of
* Result object, see semantics for Node, ContentHandler, and Stream APIs</li>
* <li>{@link #marshal(Object,javax.xml.stream.XMLEventWriter) marshal(Object,XMLEventWriter)} - the
* Marshaller will not generate {@link javax.xml.stream.events.XMLEvent#START_DOCUMENT} and
* {@link javax.xml.stream.events.XMLEvent#END_DOCUMENT} events.</li>
* <li>{@link #marshal(Object,javax.xml.stream.XMLStreamWriter) marshal(Object,XMLStreamWriter)} - the
* Marshaller will not generate {@link javax.xml.stream.events.XMLEvent#START_DOCUMENT} and
* {@link javax.xml.stream.events.XMLEvent#END_DOCUMENT} events.</li>
* </ul>
* </dd>
* </dl>
* </blockquote>
*
* <p>
* <a name="marshalEventCallback"></a>
* <b>Marshal Event Callbacks</b><br>
* <blockquote>
* "The {@link Marshaller} provides two styles of callback mechanisms
* that allow application specific processing during key points in the
* unmarshalling process. In 'class defined' event callbacks, application
* specific code placed in JAXB mapped classes is triggered during
* marshalling. 'External listeners' allow for centralized processing
* of marshal events in one callback method rather than by type event callbacks.
*
* <p>
* Class defined event callback methods allow any JAXB mapped class to specify
* its own specific callback methods by defining methods with the following method signatures:
* <blockquote>
* <pre>
* // Invoked by Marshaller after it has created an instance of this object.
* boolean beforeMarshal(Marshaller);
*
* // Invoked by Marshaller after it has marshalled all properties of this object.
* void afterMarshal(Marshaller);
* </pre>
* </blockquote>
* The class defined event callback methods should be used when the callback method requires
* access to non-public methods and/or fields of the class.
* <p>
* The external listener callback mechanism enables the registration of a {@link Listener}
* instance with a {@link Marshaller#setListener(Listener)}. The external listener receives all callback events,
* allowing for more centralized processing than per class defined callback methods.
* <p>
* The 'class defined' and external listener event callback methods are independent of each other,
* both can be called for one event. The invocation ordering when both listener callback methods exist is
* defined in {@link Listener#beforeMarshal(Object)} and {@link Listener#afterMarshal(Object)}.
* <p>
* An event callback method throwing an exception terminates the current marshal process.
* </blockquote>
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see JAXBContext
* @see Validator
* @see Unmarshaller
* @since JAXB1.0
*/
public interface Marshaller {
/**
* The name of the property used to specify the output encoding in
* the marshalled XML data.
*/
public static final String JAXB_ENCODING =
"jaxb.encoding";
/**
* The name of the property used to specify whether or not the marshalled
* XML data is formatted with linefeeds and indentation.
*/
public static final String JAXB_FORMATTED_OUTPUT =
"jaxb.formatted.output";
/**
* The name of the property used to specify the xsi:schemaLocation
* attribute value to place in the marshalled XML output.
*/
public static final String JAXB_SCHEMA_LOCATION =
"jaxb.schemaLocation";
/**
* The name of the property used to specify the
* xsi:noNamespaceSchemaLocation attribute value to place in the marshalled
* XML output.
*/
public static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION =
"jaxb.noNamespaceSchemaLocation";
/**
* The name of the property used to specify whether or not the marshaller
* will generate document level events (ie calling startDocument or endDocument).
*/
public static final String JAXB_FRAGMENT =
"jaxb.fragment";
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into the specified
* <tt>javax.xml.transform.Result</tt>.
*
* <p>
* All JAXB Providers must at least support
* {@link javax.xml.transform.dom.DOMResult},
* {@link javax.xml.transform.sax.SAXResult}, and
* {@link javax.xml.transform.stream.StreamResult}. It can
* support other derived classes of <tt>Result</tt> as well.
*
* @param jaxbElement
* The root of content tree to be marshalled.
* @param result
* XML will be sent to this Result
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public void marshal( Object jaxbElement, javax.xml.transform.Result result )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into an output stream.
*
* @param jaxbElement
* The root of content tree to be marshalled.
* @param os
* XML will be added to this stream.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public void marshal( Object jaxbElement, java.io.OutputStream os )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into a file.
*
* @param jaxbElement
* The root of content tree to be marshalled.
* @param output
* File to be written. If this file already exists, it will be overwritten.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
* @since JAXB2.1
*/
public void marshal( Object jaxbElement, File output )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into a Writer.
*
* @param jaxbElement
* The root of content tree to be marshalled.
* @param writer
* XML will be sent to this writer.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public void marshal( Object jaxbElement, java.io.Writer writer )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into SAX2 events.
*
* @param jaxbElement
* The root of content tree to be marshalled.
* @param handler
* XML will be sent to this handler as SAX2 events.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public void marshal( Object jaxbElement, org.xml.sax.ContentHandler handler )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into a DOM tree.
*
* @param jaxbElement
* The content tree to be marshalled.
* @param node
* DOM nodes will be added as children of this node.
* This parameter must be a Node that accepts children
* ({@link org.w3c.dom.Document},
* {@link org.w3c.dom.DocumentFragment}, or
* {@link org.w3c.dom.Element})
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>jaxbElement</tt> (or any
* object reachable from <tt>jaxbElement</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
*/
public void marshal( Object jaxbElement, org.w3c.dom.Node node )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into a
* {@link javax.xml.stream.XMLStreamWriter}.
*
* @param jaxbElement
* The content tree to be marshalled.
* @param writer
* XML will be sent to this writer.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
* @since JAXB 2.0
*/
public void marshal( Object jaxbElement, javax.xml.stream.XMLStreamWriter writer )
throws JAXBException;
/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into a
* {@link javax.xml.stream.XMLEventWriter}.
*
* @param jaxbElement
* The content tree rooted at jaxbElement to be marshalled.
* @param writer
* XML will be sent to this writer.
*
* @throws JAXBException
* If any unexpected problem occurs during the marshalling.
* @throws MarshalException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Marshaller</tt> is unable to marshal <tt>obj</tt> (or any
* object reachable from <tt>obj</tt>). See <a href="#elementMarshalling">
* Marshalling a JAXB element</a>.
* @throws IllegalArgumentException
* If any of the method parameters are null
* @since JAXB 2.0
*/
public void marshal( Object jaxbElement, javax.xml.stream.XMLEventWriter writer )
throws JAXBException;
/**
* Get a DOM tree view of the content tree(Optional).
*
* If the returned DOM tree is updated, these changes are also
* visible in the content tree.
* Use {@link #marshal(Object, org.w3c.dom.Node)} to force
* a deep copy of the content tree to a DOM representation.
*
* @param contentTree - JAXB Java representation of XML content
*
* @return the DOM tree view of the contentTree
*
* @throws UnsupportedOperationException
* If the JAXB provider implementation does not support a
* DOM view of the content tree
*
* @throws IllegalArgumentException
* If any of the method parameters are null
*
* @throws JAXBException
* If any unexpected problem occurs
*
*/
public org.w3c.dom.Node getNode( java.lang.Object contentTree )
throws JAXBException;
/**
* Set the particular property in the underlying implementation of
* <tt>Marshaller</tt>. This method can only be used to set one of
* the standard JAXB defined properties above or a provider specific
* property. Attempting to set an undefined property will result in
* a PropertyException being thrown. See <a href="#supportedProps">
* Supported Properties</a>.
*
* @param name the name of the property to be set. This value can either
* be specified using one of the constant fields or a user
* supplied string.
* @param value the value of the property to be set
*
* @throws PropertyException when there is an error processing the given
* property or value
* @throws IllegalArgumentException
* If the name parameter is null
*/
public void setProperty( String name, Object value )
throws PropertyException;
/**
* Get the particular property in the underlying implementation of
* <tt>Marshaller</tt>. This method can only be used to get one of
* the standard JAXB defined properties above or a provider specific
* property. Attempting to get an undefined property will result in
* a PropertyException being thrown. See <a href="#supportedProps">
* Supported Properties</a>.
*
* @param name the name of the property to retrieve
* @return the value of the requested property
*
* @throws PropertyException
* when there is an error retrieving the given property or value
* property name
* @throws IllegalArgumentException
* If the name parameter is null
*/
public Object getProperty( String name ) throws PropertyException;
/**
* Allow an application to register a validation event handler.
* <p>
* The validation event handler will be called by the JAXB Provider if any
* validation errors are encountered during calls to any of the marshal
* API's. If the client application does not register a validation event
* handler before invoking one of the marshal methods, then validation
* events will be handled by the default event handler which will terminate
* the marshal operation after the first error or fatal error is encountered.
* <p>
* Calling this method with a null parameter will cause the Marshaller
* to revert back to the default default event handler.
*
* @param handler the validation event handler
* @throws JAXBException if an error was encountered while setting the
* event handler
*/
public void setEventHandler( ValidationEventHandler handler )
throws JAXBException;
/**
* Return the current event handler or the default event handler if one
* hasn't been set.
*
* @return the current ValidationEventHandler or the default event handler
* if it hasn't been set
* @throws JAXBException if an error was encountered while getting the
* current event handler
*/
public ValidationEventHandler getEventHandler()
throws JAXBException;
/**
* Associates a configured instance of {@link XmlAdapter} with this marshaller.
*
* <p>
* This is a convenience method that invokes <code>setAdapter(adapter.getClass(),adapter);</code>.
*
* @see #setAdapter(Class,XmlAdapter)
* @throws IllegalArgumentException
* if the adapter parameter is null.
* @throws UnsupportedOperationException
* if invoked agains a JAXB 1.0 implementation.
* @since JAXB 2.0
*/
public void setAdapter( XmlAdapter adapter );
/**
* Associates a configured instance of {@link XmlAdapter} with this marshaller.
*
* <p>
* Every marshaller internally maintains a
* {@link java.util.Map}&lt;{@link Class},{@link XmlAdapter}>,
* which it uses for marshalling classes whose fields/methods are annotated
* with {@link javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter}.
*
* <p>
* This method allows applications to use a configured instance of {@link XmlAdapter}.
* When an instance of an adapter is not given, a marshaller will create
* one by invoking its default constructor.
*
* @param type
* The type of the adapter. The specified instance will be used when
* {@link javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter#value()}
* refers to this type.
* @param adapter
* The instance of the adapter to be used. If null, it will un-register
* the current adapter set for this type.
* @throws IllegalArgumentException
* if the type parameter is null.
* @throws UnsupportedOperationException
* if invoked agains a JAXB 1.0 implementation.
* @since JAXB 2.0
*/
public <A extends XmlAdapter> void setAdapter( Class<A> type, A adapter );
/**
* Gets the adapter associated with the specified type.
*
* This is the reverse operation of the {@link #setAdapter} method.
*
* @throws IllegalArgumentException
* if the type parameter is null.
* @throws UnsupportedOperationException
* if invoked agains a JAXB 1.0 implementation.
* @since JAXB 2.0
*/
public <A extends XmlAdapter> A getAdapter( Class<A> type );
/**
* <p>Associate a context that enables binary data within an XML document
* to be transmitted as XML-binary optimized attachment.
* The attachment is referenced from the XML document content model
* by content-id URIs(cid) references stored within the xml document.
*
* @throws IllegalStateException if attempt to concurrently call this
* method during a marshal operation.
*/
void setAttachmentMarshaller(AttachmentMarshaller am);
AttachmentMarshaller getAttachmentMarshaller();
/**
* Specify the JAXP 1.3 {@link javax.xml.validation.Schema Schema}
* object that should be used to validate subsequent marshal operations
* against. Passing null into this method will disable validation.
*
* <p>
* This method allows the caller to validate the marshalled XML as it's marshalled.
*
* <p>
* Initially this property is set to <tt>null</tt>.
*
* @param schema Schema object to validate marshal operations against or null to disable validation
* @throws UnsupportedOperationException could be thrown if this method is
* invoked on an Marshaller created from a JAXBContext referencing
* JAXB 1.0 mapped classes
* @since JAXB2.0
*/
public void setSchema( Schema schema );
/**
* Get the JAXP 1.3 {@link javax.xml.validation.Schema Schema} object
* being used to perform marshal-time validation. If there is no
* Schema set on the marshaller, then this method will return null
* indicating that marshal-time validation will not be performed.
*
* @return the Schema object being used to perform marshal-time
* validation or null if not present.
* @throws UnsupportedOperationException could be thrown if this method is
* invoked on an Marshaller created from a JAXBContext referencing
* JAXB 1.0 mapped classes
* @since JAXB2.0
*/
public Schema getSchema();
/**
* <p/>
* Register an instance of an implementation of this class with a {@link Marshaller} to externally listen
* for marshal events.
* <p/>
* <p/>
* This class enables pre and post processing of each marshalled object.
* The event callbacks are called when marshalling from an instance that maps to an xml element or
* complex type definition. The event callbacks are not called when marshalling from an instance of a
* Java datatype that represents a simple type definition.
* <p/>
* <p/>
* External listener is one of two different mechanisms for defining marshal event callbacks.
* See <a href="Marshaller.html#marshalEventCallback">Marshal Event Callbacks</a> for an overview.
*
* @see Marshaller#setListener(Listener)
* @see Marshaller#getListener()
* @since JAXB2.0
*/
public static abstract class Listener {
/**
* <p/>
* Callback method invoked before marshalling from <tt>source</tt> to XML.
* <p/>
* <p/>
* This method is invoked just before marshalling process starts to marshal <tt>source</tt>.
* Note that if the class of <tt>source</tt> defines its own <tt>beforeMarshal</tt> method,
* the class specific callback method is invoked just before this method is invoked.
*
* @param source instance of JAXB mapped class prior to marshalling from it.
*/
public void beforeMarshal(Object source) {
}
/**
* <p/>
* Callback method invoked after marshalling <tt>source</tt> to XML.
* <p/>
* <p/>
* This method is invoked after <tt>source</tt> and all its descendants have been marshalled.
* Note that if the class of <tt>source</tt> defines its own <tt>afterMarshal</tt> method,
* the class specific callback method is invoked just before this method is invoked.
*
* @param source instance of JAXB mapped class after marshalling it.
*/
public void afterMarshal(Object source) {
}
}
/**
* <p>
* Register marshal event callback {@link Listener} with this {@link Marshaller}.
*
* <p>
* There is only one Listener per Marshaller. Setting a Listener replaces the previous set Listener.
* One can unregister current Listener by setting listener to <tt>null</tt>.
*
* @param listener an instance of a class that implements {@link Listener}
* @since JAXB2.0
*/
public void setListener(Listener listener);
/**
* <p>Return {@link Listener} registered with this {@link Marshaller}.
*
* @return registered {@link Listener} or <code>null</code> if no Listener is registered with this Marshaller.
* @since JAXB2.0
*/
public Listener getListener();
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*/
class Messages
{
static String format( String property ) {
return format( property, null );
}
static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
static String format( String property, Object arg1, Object arg2, Object arg3 ) {
return format( property, new Object[]{arg1,arg2,arg3} );
}
// add more if necessary.
/** Loads a string resource and formats it with specified arguments. */
static String format( String property, Object[] args ) {
String text = ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
static final String PROVIDER_NOT_FOUND = // 1 arg
"ContextFinder.ProviderNotFound";
static final String COULD_NOT_INSTANTIATE = // 2 args
"ContextFinder.CouldNotInstantiate";
static final String CANT_FIND_PROPERTIES_FILE = // 1 arg
"ContextFinder.CantFindPropertiesFile";
static final String CANT_MIX_PROVIDERS = // 0 args
"ContextFinder.CantMixProviders";
static final String MISSING_PROPERTY = // 2 args
"ContextFinder.MissingProperty";
static final String NO_PACKAGE_IN_CONTEXTPATH = // 0 args
"ContextFinder.NoPackageInContextPath";
static final String NAME_VALUE = // 2 args
"PropertyException.NameValue";
static final String CONVERTER_MUST_NOT_BE_NULL = // 0 args
"DatatypeConverter.ConverterMustNotBeNull";
static final String ILLEGAL_CAST = // 2 args
"JAXBContext.IllegalCast";
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This event indicates that a problem was encountered resolving an ID/IDREF.
*
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see Validator
* @see ValidationEventHandler
* @since JAXB1.0
*/
public interface NotIdentifiableEvent extends ValidationEvent {
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This event indicates that a problem was encountered while converting a
* string from the XML data into a value of the target Java data type.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see ValidationEvent
* @see ValidationEventHandler
* @see Unmarshaller
* @since JAXB1.0
*/
public interface ParseConversionEvent extends ValidationEvent {
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This event indicates that a problem was encountered while converting data
* from the Java content tree into its lexical representation.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see ValidationEvent
* @see ValidationEventHandler
* @see Marshaller
* @since JAXB1.0
*/
public interface PrintConversionEvent extends ValidationEvent {
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This exception indicates that an error was encountered while getting or
* setting a property.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see JAXBContext
* @see Validator
* @see Unmarshaller
* @since JAXB1.0
*/
public class PropertyException extends JAXBException {
/**
* Construct a PropertyException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public PropertyException(String message) {
super(message);
}
/**
* Construct a PropertyException with the specified detail message and
* vendor specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public PropertyException(String message, String errorCode) {
super(message, errorCode);
}
/**
* Construct a PropertyException with a linkedException. The detail
* message and vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public PropertyException(Throwable exception) {
super(exception);
}
/**
* Construct a PropertyException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public PropertyException(String message, Throwable exception) {
super(message, exception);
}
/**
* Construct a PropertyException with the specified detail message, vendor
* specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public PropertyException(
String message,
String errorCode,
Throwable exception) {
super(message, errorCode, exception);
}
/**
* Construct a PropertyException whose message field is set based on the
* name of the property and value.toString().
*
* @param name the name of the property related to this exception
* @param value the value of the property related to this exception
*/
public PropertyException(String name, Object value) {
super( Messages.format( Messages.NAME_VALUE,
name,
value.toString() ) );
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import javax.xml.transform.Result;
import java.io.IOException;
/**
* Controls where a JAXB implementation puts the generates
* schema files.
*
* <p>
* An implementation of this abstract class has to be provided by the calling
* application to generate schemas.
*
* <p>
* This is a class, not an interface so as to allow future versions to evolve
* without breaking the compatibility.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public abstract class SchemaOutputResolver {
/**
* Decides where the schema file (of the given namespace URI)
* will be written, and return it as a {@link Result} object.
*
* <p>
* This method is called only once for any given namespace.
* IOW, all the components in one namespace is always written
* into the same schema document.
*
* @param namespaceUri
* The namespace URI that the schema declares.
* Can be the empty string, but never be null.
* @param suggestedFileName
* A JAXB implementation generates an unique file name (like "schema1.xsd")
* for the convenience of the callee. This name can be
* used for the file name of the schema, or the callee can just
* ignore this name and come up with its own name.
* This is just a hint.
*
* @return
* a {@link Result} object that encapsulates the actual destination
* of the schema.
*
* If the {@link Result} object has a system ID, it must be an
* absolute system ID. Those system IDs are relativized by the caller and used
* for &lt;xs:import> statements.
*
* If the {@link Result} object does not have a system ID, a schema
* for the namespace URI is generated but it won't be explicitly
* &lt;xs:import>ed from other schemas.
*
* If {@code null} is returned, the schema generation for this
* namespace URI will be skipped.
*/
public abstract Result createOutput( String namespaceUri, String suggestedFileName ) throws IOException;
}

View File

@@ -0,0 +1,184 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This exception indicates that a violation of a dynamically checked type
* constraint was detected.
*
* <p>
* This exception can be thrown by the generated setter methods of the schema
* derived Java content classes. However, since fail-fast validation is
* an optional feature for JAXB Providers to support, not all setter methods
* will throw this exception when a type constraint is violated.
*
* <p>
* If this exception is throw while invoking a fail-fast setter, the value of
* the property is guaranteed to remain unchanged, as if the setter were never
* called.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see ValidationEvent
* @since JAXB1.0
*/
public class TypeConstraintException extends java.lang.RuntimeException {
/**
* Vendor specific error code
*
*/
private String errorCode;
/**
* Exception reference
*
*/
private volatile Throwable linkedException;
static final long serialVersionUID = -3059799699420143848L;
/**
* Construct a TypeConstraintException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public TypeConstraintException(String message) {
this( message, null, null );
}
/**
* Construct a TypeConstraintException with the specified detail message and vendor
* specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public TypeConstraintException(String message, String errorCode) {
this( message, errorCode, null );
}
/**
* Construct a TypeConstraintException with a linkedException. The detail message and
* vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public TypeConstraintException(Throwable exception) {
this( null, null, exception );
}
/**
* Construct a TypeConstraintException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public TypeConstraintException(String message, Throwable exception) {
this( message, null, exception );
}
/**
* Construct a TypeConstraintException with the specified detail message,
* vendor specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public TypeConstraintException(String message, String errorCode, Throwable exception) {
super( message );
this.errorCode = errorCode;
this.linkedException = exception;
}
/**
* Get the vendor specific error code
*
* @return a string specifying the vendor specific error code
*/
public String getErrorCode() {
return this.errorCode;
}
/**
* Get the linked exception
*
* @return the linked Exception, null if none exists
*/
public Throwable getLinkedException() {
return linkedException;
}
/**
* Add a linked Exception.
*
* @param exception the linked Exception (A null value is permitted and
* indicates that the linked exception does not exist or
* is unknown).
*/
public void setLinkedException( Throwable exception ) {
this.linkedException = exception;
}
/**
* Returns a short description of this TypeConstraintException.
*
*/
public String toString() {
return linkedException == null ?
super.toString() :
super.toString() + "\n - with linked exception:\n[" +
linkedException.toString()+ "]";
}
/**
* Prints this TypeConstraintException and its stack trace (including the stack trace
* of the linkedException if it is non-null) to the PrintStream.
*
* @param s PrintStream to use for output
*/
public void printStackTrace( java.io.PrintStream s ) {
if( linkedException != null ) {
linkedException.printStackTrace(s);
s.println("--------------- linked to ------------------");
}
super.printStackTrace(s);
}
/**
* Prints this TypeConstraintException and its stack trace (including the stack trace
* of the linkedException if it is non-null) to <tt>System.err</tt>.
*
*/
public void printStackTrace() {
printStackTrace(System.err);
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This exception indicates that an error has occurred while performing
* an unmarshal operation that prevents the JAXB Provider from completing
* the operation.
*
* <p>
* The <tt>ValidationEventHandler</tt> can cause this exception to be thrown
* during the unmarshal operations. See
* {@link ValidationEventHandler#handleEvent(ValidationEvent)
* ValidationEventHandler.handleEvent(ValidationEvent)}.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see JAXBException
* @see Unmarshaller
* @see ValidationEventHandler
* @since JAXB1.0
*/
public class UnmarshalException extends JAXBException {
/**
* Construct an UnmarshalException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public UnmarshalException( String message ) {
this( message, null, null );
}
/**
* Construct an UnmarshalException with the specified detail message and vendor
* specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public UnmarshalException( String message, String errorCode ) {
this( message, errorCode, null );
}
/**
* Construct an UnmarshalException with a linkedException. The detail message and
* vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public UnmarshalException( Throwable exception ) {
this( null, null, exception );
}
/**
* Construct an UnmarshalException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public UnmarshalException( String message, Throwable exception ) {
this( message, null, exception );
}
/**
* Construct an UnmarshalException with the specified detail message, vendor
* specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public UnmarshalException( String message, String errorCode, Throwable exception ) {
super( message, errorCode, exception );
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
import org.xml.sax.ContentHandler;
/**
* Unmarshaller implemented as SAX ContentHandler.
*
* <p>
* Applications can use this interface to use their JAXB provider as a component
* in an XML pipeline. For example:
*
* <pre>
* JAXBContext context = JAXBContext.newInstance( "org.acme.foo" );
*
* Unmarshaller unmarshaller = context.createUnmarshaller();
*
* UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
*
* SAXParserFactory spf = SAXParserFactory.newInstance();
* spf.setNamespaceAware( true );
*
* XMLReader xmlReader = spf.newSAXParser().getXMLReader();
* xmlReader.setContentHandler( unmarshallerHandler );
* xmlReader.parse(new InputSource( new FileInputStream( XML_FILE ) ) );
*
* MyObject myObject= (MyObject)unmarshallerHandler.getResult();
* </pre>
*
* <p>
* This interface is reusable: even if the user fails to unmarshal
* an object, s/he can still start a new round of unmarshalling.
*
* @author <ul><li>Kohsuke KAWAGUCHI, Sun Microsystems, Inc.</li></ul>
* @see Unmarshaller#getUnmarshallerHandler()
* @since JAXB1.0
*/
public interface UnmarshallerHandler extends ContentHandler
{
/**
* Obtains the unmarshalled result.
*
* This method can be called only after this handler
* receives the endDocument SAX event.
*
* @exception IllegalStateException
* if this method is called before this handler
* receives the endDocument event.
*
* @exception JAXBException
* if there is any unmarshalling error.
* Note that the implementation is allowed to throw SAXException
* during the parsing when it finds an error.
*
* @return
* always return a non-null valid object which was unmarshalled.
*/
Object getResult() throws JAXBException, IllegalStateException;
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This event indicates that a problem was encountered while validating the
* incoming XML data during an unmarshal operation, while performing
* on-demand validation of the Java content tree, or while marshalling the
* Java content tree back to XML data.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see Validator
* @see ValidationEventHandler
* @since JAXB1.0
*/
public interface ValidationEvent {
/**
* Conditions that are not errors or fatal errors as defined by the
* XML 1.0 recommendation
*/
public static final int WARNING = 0;
/**
* Conditions that correspond to the definition of "error" in section
* 1.2 of the W3C XML 1.0 Recommendation
*/
public static final int ERROR = 1;
/**
* Conditions that correspond to the definition of "fatal error" in section
* 1.2 of the W3C XML 1.0 Recommendation
*/
public static final int FATAL_ERROR = 2;
/**
* Retrieve the severity code for this warning/error.
*
* <p>
* Must be one of <tt>ValidationError.WARNING</tt>,
* <tt>ValidationError.ERROR</tt>, or <tt>ValidationError.FATAL_ERROR</tt>.
*
* @return the severity code for this warning/error
*/
public int getSeverity();
/**
* Retrieve the text message for this warning/error.
*
* @return the text message for this warning/error or null if one wasn't set
*/
public String getMessage();
/**
* Retrieve the linked exception for this warning/error.
*
* @return the linked exception for this warning/error or null if one
* wasn't set
*/
public Throwable getLinkedException();
/**
* Retrieve the locator for this warning/error.
*
* @return the locator that indicates where the warning/error occurred
*/
public ValidationEventLocator getLocator();
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* A basic event handler interface for validation errors.
*
* <p>
* If an application needs to implement customized event handling, it must
* implement this interface and then register it with either the
* {@link Unmarshaller#setEventHandler(ValidationEventHandler) Unmarshaller},
* the {@link Validator#setEventHandler(ValidationEventHandler) Validator}, or
* the {@link Marshaller#setEventHandler(ValidationEventHandler) Marshaller}.
* The JAXB Provider will then report validation errors and warnings encountered
* during the unmarshal, marshal, and validate operations to these event
* handlers.
*
* <p>
* If the <tt>handleEvent</tt> method throws an unchecked runtime exception,
* the JAXB Provider must treat that as if the method returned false, effectively
* terminating whatever operation was in progress at the time (unmarshal,
* validate, or marshal).
*
* <p>
* Modifying the Java content tree within your event handler is undefined
* by the specification and may result in unexpected behaviour.
*
* <p>
* Failing to return false from the <tt>handleEvent</tt> method after
* encountering a fatal error is undefined by the specification and may result
* in unexpected behavior.
*
* <p>
* <b>Default Event Handler</b>
* <blockquote>
* See: <a href="Validator.html#defaulthandler">Validator javadocs</a>
* </blockquote>
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see Unmarshaller
* @see Validator
* @see Marshaller
* @see ValidationEvent
* @see javax.xml.bind.util.ValidationEventCollector
* @since JAXB1.0
*/
public interface ValidationEventHandler {
/**
* Receive notification of a validation warning or error.
*
* The ValidationEvent will have a
* {@link ValidationEventLocator ValidationEventLocator} embedded in it that
* indicates where the error or warning occurred.
*
* <p>
* If an unchecked runtime exception is thrown from this method, the JAXB
* provider will treat it as if the method returned false and interrupt
* the current unmarshal, validate, or marshal operation.
*
* @param event the encapsulated validation event information. It is a
* provider error if this parameter is null.
* @return true if the JAXB Provider should attempt to continue the current
* unmarshal, validate, or marshal operation after handling this
* warning/error, false if the provider should terminate the current
* operation with the appropriate <tt>UnmarshalException</tt>,
* <tt>ValidationException</tt>, or <tt>MarshalException</tt>.
* @throws IllegalArgumentException if the event object is null.
*/
public boolean handleEvent( ValidationEvent event );
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* Encapsulate the location of a ValidationEvent.
*
* <p>
* The <tt>ValidationEventLocator</tt> indicates where the <tt>ValidationEvent
* </tt> occurred. Different fields will be set depending on the type of
* validation that was being performed when the error or warning was detected.
* For example, on-demand validation would produce locators that contained
* references to objects in the Java content tree while unmarshal-time
* validation would produce locators containing information appropriate to the
* source of the XML data (file, url, Node, etc).
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see Validator
* @see ValidationEvent
* @since JAXB1.0
*/
public interface ValidationEventLocator {
/**
* Return the name of the XML source as a URL if available
*
* @return the name of the XML source as a URL or null if unavailable
*/
public java.net.URL getURL();
/**
* Return the byte offset if available
*
* @return the byte offset into the input source or -1 if unavailable
*/
public int getOffset();
/**
* Return the line number if available
*
* @return the line number or -1 if unavailable
*/
public int getLineNumber();
/**
* Return the column number if available
*
* @return the column number or -1 if unavailable
*/
public int getColumnNumber();
/**
* Return a reference to the object in the Java content tree if available
*
* @return a reference to the object in the Java content tree or null if
* unavailable
*/
public java.lang.Object getObject();
/**
* Return a reference to the DOM Node if available
*
* @return a reference to the DOM Node or null if unavailable
*/
public org.w3c.dom.Node getNode();
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* This exception indicates that an error has occurred while performing
* a validate operation.
*
* <p>
* The <tt>ValidationEventHandler</tt> can cause this exception to be thrown
* during the validate operations. See
* {@link ValidationEventHandler#handleEvent(ValidationEvent)
* ValidationEventHandler.handleEvent(ValidationEvent)}.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see JAXBException
* @see Validator
* @since JAXB1.0
*/
public class ValidationException extends JAXBException {
/**
* Construct an ValidationException with the specified detail message. The
* errorCode and linkedException will default to null.
*
* @param message a description of the exception
*/
public ValidationException(String message) {
this( message, null, null );
}
/**
* Construct an ValidationException with the specified detail message and vendor
* specific errorCode. The linkedException will default to null.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
*/
public ValidationException(String message, String errorCode) {
this( message, errorCode, null );
}
/**
* Construct an ValidationException with a linkedException. The detail message and
* vendor specific errorCode will default to null.
*
* @param exception the linked exception
*/
public ValidationException(Throwable exception) {
this( null, null, exception );
}
/**
* Construct an ValidationException with the specified detail message and
* linkedException. The errorCode will default to null.
*
* @param message a description of the exception
* @param exception the linked exception
*/
public ValidationException(String message, Throwable exception) {
this( message, null, exception );
}
/**
* Construct an ValidationException with the specified detail message, vendor
* specific errorCode, and linkedException.
*
* @param message a description of the exception
* @param errorCode a string specifying the vendor specific error code
* @param exception the linked exception
*/
public ValidationException(String message, String errorCode, Throwable exception) {
super( message, errorCode, exception );
}
}

View File

@@ -0,0 +1,285 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* As of JAXB 2.0, this class is deprecated and optional.
* <p>
* The <tt>Validator</tt> class is responsible for controlling the validation
* of content trees during runtime.
*
* <p>
* <a name="validationtypes"></a>
* <b>Three Forms of Validation</b><br>
* <blockquote>
* <dl>
* <dt><b>Unmarshal-Time Validation</b></dt>
* <dd>This form of validation enables a client application to receive
* information about validation errors and warnings detected while
* unmarshalling XML data into a Java content tree and is completely
* orthogonal to the other types of validation. To enable or disable
* it, see the javadoc for
* {@link Unmarshaller#setValidating(boolean) Unmarshaller.setValidating}.
* All JAXB 1.0 Providers are required to support this operation.
* </dd>
*
* <dt><b>On-Demand Validation</b></dt>
* <dd> This form of validation enables a client application to receive
* information about validation errors and warnings detected in the
* Java content tree. At any point, client applications can call
* the {@link Validator#validate(Object) Validator.validate} method
* on the Java content tree (or any sub-tree of it). All JAXB 1.0
* Providers are required to support this operation.
* </dd>
*
* <dt><b>Fail-Fast Validation</b></dt>
* <dd> This form of validation enables a client application to receive
* immediate feedback about modifications to the Java content tree
* that violate type constraints on Java Properties as defined in
* the specification. JAXB Providers are not required support
* this type of validation. Of the JAXB Providers that do support
* this type of validation, some may require you to decide at schema
* compile time whether or not a client application will be allowed
* to request fail-fast validation at runtime.
* </dd>
* </dl>
* </blockquote>
*
* <p>
* The <tt>Validator</tt> class is responsible for managing On-Demand Validation.
* The <tt>Unmarshaller</tt> class is responsible for managing Unmarshal-Time
* Validation during the unmarshal operations. Although there is no formal
* method of enabling validation during the marshal operations, the
* <tt>Marshaller</tt> may detect errors, which will be reported to the
* <tt>ValidationEventHandler</tt> registered on it.
*
* <p>
* <a name="defaulthandler"></a>
* <b>Using the Default EventHandler</b><br>
* <blockquote>
* If the client application does not set an event handler on their
* <tt>Validator</tt>, <tt>Unmarshaller</tt>, or <tt>Marshaller</tt> prior to
* calling the validate, unmarshal, or marshal methods, then a default event
* handler will receive notification of any errors or warnings encountered.
* The default event handler will cause the current operation to halt after
* encountering the first error or fatal error (but will attempt to continue
* after receiving warnings).
* </blockquote>
*
* <p>
* <a name="handlingevents"></a>
* <b>Handling Validation Events</b><br>
* <blockquote>
* There are three ways to handle events encountered during the unmarshal,
* validate, and marshal operations:
* <dl>
* <dt>Use the default event handler</dt>
* <dd>The default event handler will be used if you do not specify one
* via the <tt>setEventHandler</tt> API's on <tt>Validator</tt>,
* <tt>Unmarshaller</tt>, or <tt>Marshaller</tt>.
* </dd>
*
* <dt>Implement and register a custom event handler</dt>
* <dd>Client applications that require sophisticated event processing
* can implement the <tt>ValidationEventHandler</tt> interface and
* register it with the <tt>Unmarshaller</tt> and/or
* <tt>Validator</tt>.
* </dd>
*
* <dt>Use the {@link javax.xml.bind.util.ValidationEventCollector ValidationEventCollector}
* utility</dt>
* <dd>For convenience, a specialized event handler is provided that
* simply collects any <tt>ValidationEvent</tt> objects created
* during the unmarshal, validate, and marshal operations and
* returns them to the client application as a
* <tt>java.util.Collection</tt>.
* </dd>
* </dl>
* </blockquote>
*
* <p>
* <b>Validation and Well-Formedness</b><br>
* <blockquote>
* <p>
* Validation events are handled differently depending on how the client
* application is configured to process them as described in the previous
* section. However, there are certain cases where a JAXB Provider indicates
* that it is no longer able to reliably detect and report errors. In these
* cases, the JAXB Provider will set the severity of the ValidationEvent to
* FATAL_ERROR to indicate that the unmarshal, validate, or marshal operations
* should be terminated. The default event handler and
* <tt>ValidationEventCollector</tt> utility class must terminate processing
* after being notified of a fatal error. Client applications that supply their
* own <tt>ValidationEventHandler</tt> should also terminate processing after
* being notified of a fatal error. If not, unexpected behaviour may occur.
* </blockquote>
*
* <p>
* <a name="supportedProps"></a>
* <b>Supported Properties</b><br>
* <blockquote>
* <p>
* There currently are not any properties required to be supported by all
* JAXB Providers on Validator. However, some providers may support
* their own set of provider specific properties.
* </blockquote>
*
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see JAXBContext
* @see Unmarshaller
* @see ValidationEventHandler
* @see ValidationEvent
* @see javax.xml.bind.util.ValidationEventCollector
* @since JAXB1.0
* @deprecated since JAXB 2.0
*/
public interface Validator {
/**
* Allow an application to register a validation event handler.
* <p>
* The validation event handler will be called by the JAXB Provider if any
* validation errors are encountered during calls to
* {@link #validate(Object) validate}. If the client application does not
* register a validation event handler before invoking the validate method,
* then validation events will be handled by the default event handler which
* will terminate the validate operation after the first error or fatal error
* is encountered.
* <p>
* Calling this method with a null parameter will cause the Validator
* to revert back to the default default event handler.
*
* @param handler the validation event handler
* @throws JAXBException if an error was encountered while setting the
* event handler
* @deprecated since JAXB2.0
*/
public void setEventHandler( ValidationEventHandler handler )
throws JAXBException;
/**
* Return the current event handler or the default event handler if one
* hasn't been set.
*
* @return the current ValidationEventHandler or the default event handler
* if it hasn't been set
* @throws JAXBException if an error was encountered while getting the
* current event handler
* @deprecated since JAXB2.0
*/
public ValidationEventHandler getEventHandler()
throws JAXBException;
/**
* Validate the Java content tree starting at <tt>subrootObj</tt>.
* <p>
* Client applications can use this method to validate Java content trees
* on-demand at runtime. This method can be used to validate any arbitrary
* subtree of the Java content tree. Global constraint checking <b>will not
* </b> be performed as part of this operation (i.e. ID/IDREF constraints).
*
* @param subrootObj the obj to begin validation at
* @throws JAXBException if any unexpected problem occurs during validation
* @throws ValidationException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Validator</tt> is unable to validate the content tree rooted
* at <tt>subrootObj</tt>
* @throws IllegalArgumentException
* If the subrootObj parameter is null
* @return true if the subtree rooted at <tt>subrootObj</tt> is valid, false
* otherwise
* @deprecated since JAXB2.0
*/
public boolean validate( Object subrootObj ) throws JAXBException;
/**
* Validate the Java content tree rooted at <tt>rootObj</tt>.
* <p>
* Client applications can use this method to validate Java content trees
* on-demand at runtime. This method is used to validate an entire Java
* content tree. Global constraint checking <b>will</b> be performed as
* part of this operation (i.e. ID/IDREF constraints).
*
* @param rootObj the root obj to begin validation at
* @throws JAXBException if any unexpected problem occurs during validation
* @throws ValidationException
* If the {@link ValidationEventHandler ValidationEventHandler}
* returns false from its <tt>handleEvent</tt> method or the
* <tt>Validator</tt> is unable to validate the content tree rooted
* at <tt>rootObj</tt>
* @throws IllegalArgumentException
* If the rootObj parameter is null
* @return true if the tree rooted at <tt>rootObj</tt> is valid, false
* otherwise
* @deprecated since JAXB2.0
*/
public boolean validateRoot( Object rootObj ) throws JAXBException;
/**
* Set the particular property in the underlying implementation of
* <tt>Validator</tt>. This method can only be used to set one of
* the standard JAXB defined properties above or a provider specific
* property. Attempting to set an undefined property will result in
* a PropertyException being thrown. See <a href="#supportedProps">
* Supported Properties</a>.
*
* @param name the name of the property to be set. This value can either
* be specified using one of the constant fields or a user
* supplied string.
* @param value the value of the property to be set
*
* @throws PropertyException when there is an error processing the given
* property or value
* @throws IllegalArgumentException
* If the name parameter is null
* @deprecated since JAXB2.0
*/
public void setProperty( String name, Object value )
throws PropertyException;
/**
* Get the particular property in the underlying implementation of
* <tt>Validator</tt>. This method can only be used to get one of
* the standard JAXB defined properties above or a provider specific
* property. Attempting to get an undefined property will result in
* a PropertyException being thrown. See <a href="#supportedProps">
* Supported Properties</a>.
*
* @param name the name of the property to retrieve
* @return the value of the requested property
*
* @throws PropertyException
* when there is an error retrieving the given property or value
* property name
* @throws IllegalArgumentException
* If the name parameter is null
* @deprecated since JAXB2.0
*/
public Object getProperty( String name ) throws PropertyException;
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind;
/**
* Processes white space normalization.
*
* @since 1.0
*/
abstract class WhiteSpaceProcessor {
// benchmarking (see test/src/ReplaceTest.java in the CVS Attic)
// showed that this code is slower than the current code.
//
// public static String replace(String text) {
// final int len = text.length();
// StringBuffer result = new StringBuffer(len);
//
// for (int i = 0; i < len; i++) {
// char ch = text.charAt(i);
// if (isWhiteSpace(ch))
// result.append(' ');
// else
// result.append(ch);
// }
//
// return result.toString();
// }
public static String replace(String text) {
return replace( (CharSequence)text ).toString();
}
/**
* @since 2.0
*/
public static CharSequence replace(CharSequence text) {
int i=text.length()-1;
// look for the first whitespace char.
while( i>=0 && !isWhiteSpaceExceptSpace(text.charAt(i)) )
i--;
if( i<0 )
// no such whitespace. replace(text)==text.
return text;
// we now know that we need to modify the text.
// allocate a char array to do it.
StringBuilder buf = new StringBuilder(text);
buf.setCharAt(i--,' ');
for( ; i>=0; i-- )
if( isWhiteSpaceExceptSpace(buf.charAt(i)))
buf.setCharAt(i,' ');
return new String(buf);
}
/**
* Equivalent of {@link String#trim()}.
* @since 2.0
*/
public static CharSequence trim(CharSequence text) {
int len = text.length();
int start = 0;
while( start<len && isWhiteSpace(text.charAt(start)) )
start++;
int end = len-1;
while( end>start && isWhiteSpace(text.charAt(end)) )
end--;
if(start==0 && end==len-1)
return text; // no change
else
return text.subSequence(start,end+1);
}
public static String collapse(String text) {
return collapse( (CharSequence)text ).toString();
}
/**
* This is usually the biggest processing bottleneck.
*
* @since 2.0
*/
public static CharSequence collapse(CharSequence text) {
int len = text.length();
// most of the texts are already in the collapsed form.
// so look for the first whitespace in the hope that we will
// never see it.
int s=0;
while(s<len) {
if(isWhiteSpace(text.charAt(s)))
break;
s++;
}
if(s==len)
// the input happens to be already collapsed.
return text;
// we now know that the input contains spaces.
// let's sit down and do the collapsing normally.
StringBuilder result = new StringBuilder(len /*allocate enough size to avoid re-allocation*/ );
if(s!=0) {
for( int i=0; i<s; i++ )
result.append(text.charAt(i));
result.append(' ');
}
boolean inStripMode = true;
for (int i = s+1; i < len; i++) {
char ch = text.charAt(i);
boolean b = isWhiteSpace(ch);
if (inStripMode && b)
continue; // skip this character
inStripMode = b;
if (inStripMode)
result.append(' ');
else
result.append(ch);
}
// remove trailing whitespaces
len = result.length();
if (len > 0 && result.charAt(len - 1) == ' ')
result.setLength(len - 1);
// whitespaces are already collapsed,
// so all we have to do is to remove the last one character
// if it's a whitespace.
return result;
}
/**
* Returns true if the specified string is all whitespace.
*/
public static final boolean isWhiteSpace(CharSequence s) {
for( int i=s.length()-1; i>=0; i-- )
if(!isWhiteSpace(s.charAt(i)))
return false;
return true;
}
/** returns true if the specified char is a white space character. */
public static final boolean isWhiteSpace(char ch) {
// most of the characters are non-control characters.
// so check that first to quickly return false for most of the cases.
if( ch>0x20 ) return false;
// other than we have to do four comparisons.
return ch == 0x9 || ch == 0xA || ch == 0xD || ch == 0x20;
}
/**
* Returns true if the specified char is a white space character
* but not 0x20.
*/
protected static final boolean isWhiteSpaceExceptSpace(char ch) {
// most of the characters are non-control characters.
// so check that first to quickly return false for most of the cases.
if( ch>=0x20 ) return false;
// other than we have to do four comparisons.
return ch == 0x9 || ch == 0xA || ch == 0xD;
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
/**
* Converts an element (and its descendants)
* from/to DOM (or similar) representation.
*
* <p>
* Implementations of this interface will be used in conjunction with
* {@link XmlAnyElement} annotation to map an element of XML into a representation
* of infoset such as W3C DOM.
*
* <p>
* Implementations hide how a portion of XML is converted into/from such
* DOM-like representation, allowing JAXB providers to work with arbitrary
* such library.
*
* <P>
* This interface is intended to be implemented by library writers
* and consumed by JAXB providers. None of those methods are intended to
* be called from applications.
*
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
public interface DomHandler<ElementT,ResultT extends Result> {
/**
* When a JAXB provider needs to unmarshal a part of a document into an
* infoset representation, it first calls this method to create a
* {@link Result} object.
*
* <p>
* A JAXB provider will then send a portion of the XML
* into the given result. Such a portion always form a subtree
* of the whole XML document rooted at an element.
*
* @param errorHandler
* if any error happens between the invocation of this method
* and the invocation of {@link #getElement(Result)}, they
* must be reported to this handler.
*
* The caller must provide a non-null error handler.
*
* The {@link Result} object created from this method
* may hold a reference to this error handler.
*
* @return
* null if the operation fails. The error must have been reported
* to the error handler.
*/
ResultT createUnmarshaller( ValidationEventHandler errorHandler );
/**
* Once the portion is sent to the {@link Result}. This method is called
* by a JAXB provider to obtain the unmarshalled element representation.
*
* <p>
* Multiple invocations of this method may return different objects.
* This method can be invoked only when the whole sub-tree are fed
* to the {@link Result} object.
*
* @param rt
* The {@link Result} object created by {@link #createUnmarshaller(ValidationEventHandler)}.
*
* @return
* null if the operation fails. The error must have been reported
* to the error handler.
*/
ElementT getElement(ResultT rt);
/**
* This method is called when a JAXB provider needs to marshal an element
* to XML.
*
* <p>
* If non-null, the returned {@link Source} must contain a whole document
* rooted at one element, which will then be weaved into a bigger document
* that the JAXB provider is marshalling.
*
* @param errorHandler
* Receives any errors happened during the process of converting
* an element into a {@link Source}.
*
* The caller must provide a non-null error handler.
*
* @return
* null if there was an error. The error should have been reported
* to the handler.
*/
Source marshal( ElementT n, ValidationEventHandler errorHandler );
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
/**
* {@link DomHandler} implementation for W3C DOM (<code>org.w3c.dom</code> package.)
*
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
public class W3CDomHandler implements DomHandler<Element,DOMResult> {
private DocumentBuilder builder;
/**
* Default constructor.
*
* It is up to a JAXB provider to decide which DOM implementation
* to use or how that is configured.
*/
public W3CDomHandler() {
this.builder = null;
}
/**
* Constructor that allows applications to specify which DOM implementation
* to be used.
*
* @param builder
* must not be null. JAXB uses this {@link DocumentBuilder} to create
* a new element.
*/
public W3CDomHandler(DocumentBuilder builder) {
if(builder==null)
throw new IllegalArgumentException();
this.builder = builder;
}
public DocumentBuilder getBuilder() {
return builder;
}
public void setBuilder(DocumentBuilder builder) {
this.builder = builder;
}
public DOMResult createUnmarshaller(ValidationEventHandler errorHandler) {
if(builder==null)
return new DOMResult();
else
return new DOMResult(builder.newDocument());
}
public Element getElement(DOMResult r) {
// JAXP spec is ambiguous about what really happens in this case,
// so work defensively
Node n = r.getNode();
if( n instanceof Document ) {
return ((Document)n).getDocumentElement();
}
if( n instanceof Element )
return (Element)n;
if( n instanceof DocumentFragment )
return (Element)n.getChildNodes().item(0);
// if the result object contains something strange,
// it is not a user problem, but it is a JAXB provider's problem.
// That's why we throw a runtime exception.
throw new IllegalStateException(n.toString());
}
public Source marshal(Element element, ValidationEventHandler errorHandler) {
return new DOMSource(element);
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
/**
* Used by XmlAccessorOrder to control the ordering of properties and
* fields in a JAXB bound class.
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
* @see XmlAccessorOrder
*/
public enum XmlAccessOrder {
/**
* The ordering of fields and properties in a class is undefined.
*/
UNDEFINED,
/**
* The ordering of fields and properties in a class is in
* alphabetical order as determined by the
* method java.lang.String.compareTo(String anotherString).
*/
ALPHABETICAL
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
/**
* Used by XmlAccessorType to control serialization of fields or
* properties.
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
* @see XmlAccessorType
*/
public enum XmlAccessType {
/**
* Every getter/setter pair in a JAXB-bound class will be automatically
* bound to XML, unless annotated by {@link XmlTransient}.
*
* Fields are bound to XML only when they are explicitly annotated
* by some of the JAXB annotations.
*/
PROPERTY,
/**
* Every non static, non transient field in a JAXB-bound class will be automatically
* bound to XML, unless annotated by {@link XmlTransient}.
*
* Getter/setter pairs are bound to XML only when they are explicitly annotated
* by some of the JAXB annotations.
*/
FIELD,
/**
* Every public getter/setter pair and every public field will be
* automatically bound to XML, unless annotated by {@link XmlTransient}.
*
* Fields or getter/setter pairs that are private, protected, or
* defaulted to package-only access are bound to XML only when they are
* explicitly annotated by the appropriate JAXB annotations.
*/
PUBLIC_MEMBER,
/**
* None of the fields or properties is bound to XML unless they
* are specifically annotated with some of the JAXB annotations.
*/
NONE
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.Inherited;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p> Controls the ordering of fields and properties in a class. </p>
*
* <h3>Usage </h3>
*
* <p> <tt> @XmlAccessorOrder </tt> annotation can be used with the following
* program elements:</p>
*
* <ul>
* <li> package</li>
* <li> a top level class </li>
* </ul>
*
* <p> See "Package Specification" in <tt>javax.xml.bind</tt> package javadoc for
* additional common information.</p>
*
* <p>The effective {@link XmlAccessOrder} on a class is determined
* as follows:
*
* <ul>
* <li> If there is a <tt>@XmlAccessorOrder</tt> on a class, then
* it is used. </li>
* <li> Otherwise, if a <tt>@XmlAccessorOrder </tt> exists on one of
* its super classes, then it is inherited (by the virtue of
* {@link Inherited})
* <li> Otherwise, the <tt>@XmlAccessorOrder</tt> on the package
* of the class is used, if it's there.
* <li> Otherwise {@link XmlAccessOrder#UNDEFINED}.
* </ul>
*
* <p>This annotation can be used with the following annotations:
* {@link XmlType}, {@link XmlRootElement}, {@link XmlAccessorType},
* {@link XmlSchema}, {@link XmlSchemaType}, {@link XmlSchemaTypes},
* , {@link XmlJavaTypeAdapter}. It can also be used with the
* following annotations at the package level: {@link XmlJavaTypeAdapter}.
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
* @see XmlAccessOrder
*/
@Inherited @Retention(RUNTIME) @Target({PACKAGE, TYPE})
public @interface XmlAccessorOrder {
XmlAccessOrder value() default XmlAccessOrder.UNDEFINED;
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.Inherited;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p> Controls whether fields or Javabean properties are serialized by default. </p>
*
* <p> <b> Usage </b> </p>
*
* <p> <tt>@XmlAccessorType</tt> annotation can be used with the following program elements:</p>
*
* <ul>
* <li> package</li>
* <li> a top level class </li>
* </ul>
*
* <p> See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p>This annotation provides control over the default serialization
* of properties and fields in a class.
*
* <p>The annotation <tt> @XmlAccessorType </tt> on a package applies to
* all classes in the package. The following inheritance
* semantics apply:
*
* <ul>
* <li> If there is a <tt>@XmlAccessorType</tt> on a class, then it
* is used. </li>
* <li> Otherwise, if a <tt>@XmlAccessorType</tt> exists on one of
* its super classes, then it is inherited.
* <li> Otherwise, the <tt>@XmlAccessorType </tt> on a package is
* inherited.
* </ul>
* <p> <b> Defaulting Rules: </b> </p>
*
* <p>By default, if <tt>@XmlAccessorType </tt> on a package is absent,
* then the following package level annotation is assumed.</p>
* <pre>
* &#64;XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
* </pre>
* <p> By default, if <tt>@XmlAccessorType</tt> on a class is absent,
* and none of its super classes is annotated with
* <tt>@XmlAccessorType</tt>, then the following default on the class
* is assumed: </p>
* <pre>
* &#64;XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
* </pre>
* <p>This annotation can be used with the following annotations:
* {@link XmlType}, {@link XmlRootElement}, {@link XmlAccessorOrder},
* {@link XmlSchema}, {@link XmlSchemaType}, {@link XmlSchemaTypes},
* , {@link XmlJavaTypeAdapter}. It can also be used with the
* following annotations at the package level: {@link XmlJavaTypeAdapter}.
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
* @see XmlAccessType
*/
@Inherited @Retention(RUNTIME) @Target({PACKAGE, TYPE})
public @interface XmlAccessorType {
/**
* Specifies whether fields or properties are serialized.
*
* @see XmlAccessType
*/
XmlAccessType value() default XmlAccessType.PUBLIC_MEMBER;
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.namespace.QName;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Map;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
/**
* <p>
* Maps a JavaBean property to a map of wildcard attributes.
*
* <p> <b>Usage</b> </p>
* <p>
* The <tt>&#64;XmlAnyAttribute</tt> annotation can be used with the
* following program elements:
* <ul>
* <li> JavaBean property </li>
* <li> non static, non transient field </li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* The usage is subject to the following constraints:
* <ul>
* <li> At most one field or property in a class can be annotated
* with <tt>&#64;XmlAnyAttribute</tt>. </li>
* <li> The type of the property or the field must <tt>java.util.Map</tt> </li>
* </ul>
*
* <p>
* While processing attributes to be unmarshalled into a value class,
* each attribute that is not statically associated with another
* JavaBean property, via {@link XmlAttribute}, is entered into the
* wildcard attribute map represented by
* {@link Map}&lt;{@link QName},{@link Object}>. The attribute QName is the
* map's key. The key's value is the String value of the attribute.
*
* @author Kohsuke Kawaguchi, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlAnyAttribute {
}

View File

@@ -0,0 +1,288 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.List;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Maps a JavaBean property to XML infoset representation and/or JAXB element.
*
* <p>
* This annotation serves as a "catch-all" property while unmarshalling
* xml content into a instance of a JAXB annotated class. It typically
* annotates a multi-valued JavaBean property, but it can occur on
* single value JavaBean property. During unmarshalling, each xml element
* that does not match a static &#64;XmlElement or &#64;XmlElementRef
* annotation for the other JavaBean properties on the class, is added to this
* "catch-all" property.
*
* <p>
* <h2>Usages:</h2>
* <pre>
* &#64;XmlAnyElement
* public {@link Element}[] others;
*
* // Collection of {@link Element} or JAXB elements.
* &#64;XmlAnyElement(lax="true")
* public {@link Object}[] others;
*
* &#64;XmlAnyElement
* private List&lt;{@link Element}> nodes;
*
* &#64;XmlAnyElement
* private {@link Element} node;
* </pre>
*
* <h2>Restriction usage constraints</h2>
* <p>
* This annotation is mutually exclusive with
* {@link XmlElement}, {@link XmlAttribute}, {@link XmlValue},
* {@link XmlElements}, {@link XmlID}, and {@link XmlIDREF}.
*
* <p>
* There can be only one {@link XmlAnyElement} annotated JavaBean property
* in a class and its super classes.
*
* <h2>Relationship to other annotations</h2>
* <p>
* This annotation can be used with {@link XmlJavaTypeAdapter}, so that users
* can map their own data structure to DOM, which in turn can be composed
* into XML.
*
* <p>
* This annotation can be used with {@link XmlMixed} like this:
* <pre>
* // List of java.lang.String or DOM nodes.
* &#64;XmlAnyElement &#64;XmlMixed
* List&lt;Object> others;
* </pre>
*
*
* <h2>Schema To Java example</h2>
*
* The following schema would produce the following Java class:
* <pre>
* &lt;xs:complexType name="foo">
* &lt;xs:sequence>
* &lt;xs:element name="a" type="xs:int" />
* &lt;xs:element name="b" type="xs:int" />
* &lt;xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" />
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <pre>
* class Foo {
* int a;
* int b;
* &#64;{@link XmlAnyElement}
* List&lt;Element> any;
* }
* </pre>
*
* It can unmarshal instances like
*
* <pre>
* &lt;foo xmlns:e="extra">
* &lt;a>1</a>
* &lt;e:other /> // this will be bound to DOM, because unmarshalling is orderless
* &lt;b>3</b>
* &lt;e:other />
* &lt;c>5</c> // this will be bound to DOM, because the annotation doesn't remember namespaces.
* &lt;/foo>
* </pre>
*
*
*
* The following schema would produce the following Java class:
* <pre>
* &lt;xs:complexType name="bar">
* &lt;xs:complexContent>
* &lt;xs:extension base="foo">
* &lt;xs:sequence>
* &lt;xs:element name="c" type="xs:int" />
* &lt;xs:any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded" />
* &lt;/xs:sequence>
* &lt;/xs:extension>
* &lt;/xs:complexType>
* </pre>
*
* <pre>
* class Bar extends Foo {
* int c;
* // Foo.getAny() also represents wildcard content for type definition bar.
* }
* </pre>
*
*
* It can unmarshal instances like
*
* <pre>
* &lt;bar xmlns:e="extra">
* &lt;a>1</a>
* &lt;e:other /> // this will be bound to DOM, because unmarshalling is orderless
* &lt;b>3</b>
* &lt;e:other />
* &lt;c>5</c> // this now goes to Bar.c
* &lt;e:other /> // this will go to Foo.any
* &lt;/bar>
* </pre>
*
*
*
*
* <h2>Using {@link XmlAnyElement} with {@link XmlElementRef}</h2>
* <p>
* The {@link XmlAnyElement} annotation can be used with {@link XmlElementRef}s to
* designate additional elements that can participate in the content tree.
*
* <p>
* The following schema would produce the following Java class:
* <pre>
* &lt;xs:complexType name="foo">
* &lt;xs:choice maxOccurs="unbounded" minOccurs="0">
* &lt;xs:element name="a" type="xs:int" />
* &lt;xs:element name="b" type="xs:int" />
* &lt;xs:any namespace="##other" processContents="lax" />
* &lt;/xs:choice>
* &lt;/xs:complexType>
* </pre>
*
* <pre>
* class Foo {
* &#64;{@link XmlAnyElement}(lax="true")
* &#64;{@link XmlElementRefs}({
* &#64;{@link XmlElementRef}(name="a", type="JAXBElement.class")
* &#64;{@link XmlElementRef}(name="b", type="JAXBElement.class")
* })
* {@link List}&lt;{@link Object}> others;
* }
*
* &#64;XmlRegistry
* class ObjectFactory {
* ...
* &#64;XmlElementDecl(name = "a", namespace = "", scope = Foo.class)
* {@link JAXBElement}&lt;Integer> createFooA( Integer i ) { ... }
*
* &#64;XmlElementDecl(name = "b", namespace = "", scope = Foo.class)
* {@link JAXBElement}&lt;Integer> createFooB( Integer i ) { ... }
* </pre>
*
* It can unmarshal instances like
*
* <pre>
* &lt;foo xmlns:e="extra">
* &lt;a>1</a> // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
* &lt;e:other /> // this will unmarshal to a DOM {@link Element}.
* &lt;b>3</b> // this will unmarshal to a {@link JAXBElement} instance whose value is 1.
* &lt;/foo>
* </pre>
*
*
*
*
* <h2>W3C XML Schema "lax" wildcard emulation</h2>
* The lax element of the annotation enables the emulation of the "lax" wildcard semantics.
* For example, when the Java source code is annotated like this:
* <pre>
* &#64;{@link XmlRootElement}
* class Foo {
* &#64;XmlAnyElement(lax=true)
* public {@link Object}[] others;
* }
* </pre>
* then the following document will unmarshal like this:
* <pre>
* &lt;foo>
* &lt;unknown />
* &lt;foo />
* &lt;/foo>
*
* Foo foo = unmarshal();
* // 1 for 'unknown', another for 'foo'
* assert foo.others.length==2;
* // 'unknown' unmarshals to a DOM element
* assert foo.others[0] instanceof Element;
* // because of lax=true, the 'foo' element eagerly
* // unmarshals to a Foo object.
* assert foo.others[1] instanceof Foo;
* </pre>
*
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlAnyElement {
/**
* Controls the unmarshaller behavior when it sees elements
* known to the current {@link JAXBContext}.
*
* <h3>When false</h3>
* <p>
* If false, all the elements that match the property will be unmarshalled
* to DOM, and the property will only contain DOM elements.
*
* <h3>When true</h3>
* <p>
* If true, when an element matches a property marked with {@link XmlAnyElement}
* is known to {@link JAXBContext} (for example, there's a class with
* {@link XmlRootElement} that has the same tag name, or there's
* {@link XmlElementDecl} that has the same tag name),
* the unmarshaller will eagerly unmarshal this element to the JAXB object,
* instead of unmarshalling it to DOM. Additionally, if the element is
* unknown but it has a known xsi:type, the unmarshaller eagerly unmarshals
* the element to a {@link JAXBElement}, with the unknown element name and
* the JAXBElement value is set to an instance of the JAXB mapping of the
* known xsi:type.
*
* <p>
* As a result, after the unmarshalling, the property can become heterogeneous;
* it can have both DOM nodes and some JAXB objects at the same time.
*
* <p>
* This can be used to emulate the "lax" wildcard semantics of the W3C XML Schema.
*/
boolean lax() default false;
/**
* Specifies the {@link DomHandler} which is responsible for actually
* converting XML from/to a DOM-like data structure.
*/
Class<? extends DomHandler> value() default W3CDomHandler.class;
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.activation.DataHandler;
import static java.lang.annotation.ElementType.*;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* Marks a field/property that its XML form is a uri reference to mime content.
* The mime content is optimally stored out-of-line as an attachment.
*
* A field/property must always map to the {@link DataHandler} class.
*
* <h2>Usage</h2>
* <pre>
* &#64;{@link XmlRootElement}
* class Foo {
* &#64;{@link XmlAttachmentRef}
* &#64;{@link XmlAttribute}
* {@link DataHandler} data;
*
* &#64;{@link XmlAttachmentRef}
* &#64;{@link XmlElement}
* {@link DataHandler} body;
* }
* </pre>
* The above code maps to the following XML:
* <pre>
* &lt;xs:element name="foo" xmlns:ref="http://ws-i.org/profiles/basic/1.1/xsd">
* &lt;xs:complexType>
* &lt;xs:sequence>
* &lt;xs:element name="body" type="ref:swaRef" minOccurs="0" />
* &lt;/xs:sequence>
* &lt;xs:attribute name="data" type="ref:swaRef" use="optional" />
* &lt;/xs:complexType>
* &lt;/xs:element>
* </pre>
*
* <p>
* The above binding supports WS-I AP 1.0 <a href="http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html#Referencing_Attachments_from_the_SOAP_Envelope">WS-I Attachments Profile Version 1.0.</a>
*
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD,PARAMETER})
public @interface XmlAttachmentRef {
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p>
* Maps a JavaBean property to a XML attribute.
*
* <p> <b>Usage</b> </p>
* <p>
* The <tt>@XmlAttribute</tt> annotation can be used with the
* following program elements:
* <ul>
* <li> JavaBean property </li>
* <li> field </li>
* </ul>
*
* <p> A static final field is mapped to a XML fixed attribute.
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* The usage is subject to the following constraints:
* <ul>
* <li> If type of the field or the property is a collection
* type, then the collection item type must be mapped to schema
* simple type.
* <pre>
* // Examples
* &#64;XmlAttribute List&lt;Integer> items; //legal
* &#64;XmlAttribute List&lt;Bar> foo; // illegal if Bar does not map to a schema simple type
* </pre>
* </li>
* <li> If the type of the field or the property is a non
* collection type, then the type of the property or field
* must map to a simple schema type.
* <pre>
* // Examples
* &#64;XmlAttribute int foo; // legal
* &#64;XmlAttribute Foo foo; // illegal if Foo does not map to a schema simple type
* </pre>
* </li>
* <li> This annotation can be used with the following annotations:
* {@link XmlID},
* {@link XmlIDREF},
* {@link XmlList},
* {@link XmlSchemaType},
* {@link XmlValue},
* {@link XmlAttachmentRef},
* {@link XmlMimeType},
* {@link XmlInlineBinaryData},
* {@link javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter}.</li>
* </ul>
* </p>
*
* <p> <b>Example 1: </b>Map a JavaBean property to an XML attribute.</p>
* <pre>
* //Example: Code fragment
* public class USPrice {
* &#64;XmlAttribute
* public java.math.BigDecimal getPrice() {...} ;
* public void setPrice(java.math.BigDecimal ) {...};
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="USPrice">
* &lt;xs:sequence>
* &lt;/xs:sequence>
* &lt;xs:attribute name="price" type="xs:decimal"/>
* &lt;/xs:complexType>
* </pre>
*
* <p> <b>Example 2: </b>Map a JavaBean property to an XML attribute with anonymous type.</p>
* See Example 7 in @{@link XmlType}.
*
* <p> <b>Example 3: </b>Map a JavaBean collection property to an XML attribute.</p>
* <pre>
* // Example: Code fragment
* class Foo {
* ...
* &#64;XmlAttribute List&lt;Integer> items;
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="foo">
* ...
* &lt;xs:attribute name="items">
* &lt;xs:simpleType>
* &lt;xs:list itemType="xs:int"/>
* &lt;/xs:simpleType>
* &lt;/xs:complexType>
*
* </pre>
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @see XmlType
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlAttribute {
/**
* Name of the XML Schema attribute. By default, the XML Schema
* attribute name is derived from the JavaBean property name.
*
*/
String name() default "##default";
/**
* Specifies if the XML Schema attribute is optional or
* required. If true, then the JavaBean property is mapped to a
* XML Schema attribute that is required. Otherwise it is mapped
* to a XML Schema attribute that is optional.
*
*/
boolean required() default false;
/**
* Specifies the XML target namespace of the XML Schema
* attribute.
*
*/
String namespace() default "##default" ;
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.*;
/**
* Maps a JavaBean property to a XML element derived from property name.
*
* <p> <b>Usage</b> </p>
* <p>
* <tt>@XmlElement</tt> annotation can be used with the following program
* elements:
* <ul>
* <li> a JavaBean property </li>
* <li> non static, non transient field </li>
* <li> within {@link XmlElements}
* <p>
*
* </ul>
*
* The usage is subject to the following constraints:
* <ul>
* <li> This annotation can be used with following annotations:
* {@link XmlID},
* {@link XmlIDREF},
* {@link XmlList},
* {@link XmlSchemaType},
* {@link XmlValue},
* {@link XmlAttachmentRef},
* {@link XmlMimeType},
* {@link XmlInlineBinaryData},
* {@link XmlElementWrapper},
* {@link XmlJavaTypeAdapter}</li>
* <li> if the type of JavaBean property is a collection type of
* array, an indexed property, or a parameterized list, and
* this annotation is used with {@link XmlElements} then,
* <tt>@XmlElement.type()</tt> must be DEFAULT.class since the
* collection item type is already known. </li>
* </ul>
*
* <p>
* A JavaBean property, when annotated with @XmlElement annotation
* is mapped to a local element in the XML Schema complex type to
* which the containing class is mapped.
*
* <p>
* <b>Example 1: </b> Map a public non static non final field to local
* element
* <pre>
* //Example: Code fragment
* public class USPrice {
* &#64;XmlElement(name="itemprice")
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example: Local XML Schema element -->
* &lt;xs:complexType name="USPrice"/>
* &lt;xs:sequence>
* &lt;xs:element name="itemprice" type="xs:decimal" minOccurs="0"/>
* &lt;/sequence>
* &lt;/xs:complexType>
* </pre>
* <p>
*
* <b> Example 2: </b> Map a field to a nillable element.
* <pre>
*
* //Example: Code fragment
* public class USPrice {
* &#64;XmlElement(nillable=true)
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example: Local XML Schema element -->
* &lt;xs:complexType name="USPrice">
* &lt;xs:sequence>
* &lt;xs:element name="price" type="xs:decimal" nillable="true" minOccurs="0"/>
* &lt;/sequence>
* &lt;/xs:complexType>
* </pre>
* <p>
* <b> Example 3: </b> Map a field to a nillable, required element.
* <pre>
*
* //Example: Code fragment
* public class USPrice {
* &#64;XmlElement(nillable=true, required=true)
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example: Local XML Schema element -->
* &lt;xs:complexType name="USPrice">
* &lt;xs:sequence>
* &lt;xs:element name="price" type="xs:decimal" nillable="true" minOccurs="1"/>
* &lt;/sequence>
* &lt;/xs:complexType>
* </pre>
* <p>
*
* <p> <b>Example 4: </b>Map a JavaBean property to an XML element
* with anonymous type.</p>
* <p>
* See Example 6 in @{@link XmlType}.
*
* <p>
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD, PARAMETER})
public @interface XmlElement {
/**
* Name of the XML Schema element.
* <p> If the value is "##default", then element name is derived from the
* JavaBean property name.
*/
String name() default "##default";
/**
* Customize the element declaration to be nillable.
* <p>If nillable() is true, then the JavaBean property is
* mapped to a XML Schema nillable element declaration.
*/
boolean nillable() default false;
/**
* Customize the element declaration to be required.
* <p>If required() is true, then Javabean property is mapped to
* an XML schema element declaration with minOccurs="1".
* maxOccurs is "1" for a single valued property and "unbounded"
* for a multivalued property.
* <p>If required() is false, then the Javabean property is mapped
* to XML Schema element declaration with minOccurs="0".
* maxOccurs is "1" for a single valued property and "unbounded"
* for a multivalued property.
*/
boolean required() default false;
/**
* XML target namespace of the XML Schema element.
* <p>
* If the value is "##default", then the namespace is determined
* as follows:
* <ol>
* <li>
* If the enclosing package has {@link XmlSchema} annotation,
* and its {@link XmlSchema#elementFormDefault() elementFormDefault}
* is {@link XmlNsForm#QUALIFIED QUALIFIED}, then the namespace of
* the enclosing class.
*
* <li>
* Otherwise &#39;&#39; (which produces unqualified element in the default
* namespace.
* </ol>
*/
String namespace() default "##default";
/**
* Default value of this element.
*
* <p>
* The <pre>'\u0000'</pre> value specified as a default of this annotation element
* is used as a poor-man's substitute for null to allow implementations
* to recognize the 'no default value' state.
*/
String defaultValue() default "\u0000";
/**
* The Java class being referenced.
*/
Class type() default DEFAULT.class;
/**
* Used in {@link XmlElement#type()} to
* signal that the type be inferred from the signature
* of the property.
*/
static final class DEFAULT {}
}

View File

@@ -0,0 +1,216 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.METHOD;
/**
* Maps a factory method to a XML element.
*
* <p> <b>Usage</b> </p>
*
* The annotation creates a mapping between an XML schema element
* declaration and a <i> element factory method </i> that returns a
* JAXBElement instance representing the element
* declaration. Typically, the element factory method is generated
* (and annotated) from a schema into the ObjectFactory class in a
* Java package that represents the binding of the element
* declaration's target namespace. Thus, while the annotation syntax
* allows &#64;XmlElementDecl to be used on any method, semantically
* its use is restricted to annotation of element factory method.
*
* The usage is subject to the following constraints:
*
* <ul>
* <li> The class containing the element factory method annotated
* with &#64;XmlElementDecl must be marked with {@link
* XmlRegistry}. </li>
* <li> The element factory method must take one parameter
* assignable to {@link Object}.</li>
* </ul>
*
* <p><b>Example 1: </b>Annotation on a factory method
* <pre>
* // Example: code fragment
* &#64;XmlRegistry
* class ObjectFactory {
* &#64;XmlElementDecl(name="foo")
* JAXBElement&lt;String> createFoo(String s) { ... }
* }
* </pre>
* <pre>
* &lt;!-- XML input -->
* &lt;foo>string</foo>
*
* // Example: code fragment corresponding to XML input
* JAXBElement<String> o =
* (JAXBElement<String>)unmarshaller.unmarshal(aboveDocument);
* // print JAXBElement instance to show values
* System.out.println(o.getName()); // prints "{}foo"
* System.out.println(o.getValue()); // prints "string"
* System.out.println(o.getValue().getClass()); // prints "java.lang.String"
*
* &lt;!-- Example: XML schema definition -->
* &lt;xs:element name="foo" type="xs:string"/>
* </pre>
*
* <p><b>Example 2: </b> Element declaration with non local scope
* <p>
* The following example illustrates the use of scope annotation
* parameter in binding of element declaration in schema derived
* code.
* <p>
* The following example may be replaced in a future revision of
* this javadoc.
*
* <pre>
* &lt;!-- Example: XML schema definition -->
* &lt;xs:schema>
* &lt;xs:complexType name="pea">
* &lt;xs:choice maxOccurs="unbounded">
* &lt;xs:element name="foo" type="xs:string"/>
* &lt;xs:element name="bar" type="xs:string"/>
* &lt;/xs:choice>
* &lt;/xs:complexType>
* &lt;xs:element name="foo" type="xs:int"/>
* &lt;/xs:schema>
* </pre>
* <pre>
* // Example: expected default binding
* class Pea {
* &#64;XmlElementRefs({
* &#64;XmlElementRef(name="foo",type=JAXBElement.class)
* &#64;XmlElementRef(name="bar",type=JAXBElement.class)
* })
* List&lt;JAXBElement&lt;String>> fooOrBar;
* }
*
* &#64;XmlRegistry
* class ObjectFactory {
* &#64;XmlElementDecl(scope=Pea.class,name="foo")
* JAXBElement<String> createPeaFoo(String s);
*
* &#64;XmlElementDecl(scope=Pea.class,name="bar")
* JAXBElement<String> createPeaBar(String s);
*
* &#64;XmlElementDecl(name="foo")
* JAXBElement<Integer> createFoo(Integer i);
* }
*
* </pre>
* Without scope createFoo and createPeaFoo would become ambiguous
* since both of them map to a XML schema element with the same local
* name "foo".
*
* @see XmlRegistry
* @since JAXB 2.0
*/
@Retention(RUNTIME)
@Target({METHOD})
public @interface XmlElementDecl {
/**
* scope of the mapping.
*
* <p>
* If this is not {@link XmlElementDecl.GLOBAL}, then this element
* declaration mapping is only active within the specified class.
*/
Class scope() default GLOBAL.class;
/**
* namespace name of the XML element.
* <p>
* If the value is "##default", then the value is the namespace
* name for the package of the class containing this factory method.
*
* @see #name()
*/
String namespace() default "##default";
/**
* local name of the XML element.
*
* <p>
* <b> Note to reviewers: </b> There is no default name; since
* the annotation is on a factory method, it is not clear that the
* method name can be derived from the factory method name.
* @see #namespace()
*/
String name();
/**
* namespace name of a substitution group's head XML element.
* <p>
* This specifies the namespace name of the XML element whose local
* name is specified by <tt>substitutionHeadName()</tt>.
* <p>
* If <tt>susbtitutionHeadName()</tt> is "", then this
* value can only be "##default". But the value is ignored since
* since this element is not part of susbtitution group when the
* value of <tt>susbstitutionHeadName()</tt> is "".
* <p>
* If <tt>susbtitutionHeadName()</tt> is not "" and the value is
* "##default", then the namespace name is the namespace name to
* which the package of the containing class, marked with {@link
* XmlRegistry }, is mapped.
* <p>
* If <tt>susbtitutionHeadName()</tt> is not "" and the value is
* not "##default", then the value is the namespace name.
*
* @see #substitutionHeadName()
*/
String substitutionHeadNamespace() default "##default";
/**
* XML local name of a substitution group's head element.
* <p>
* If the value is "", then this element is not part of any
* substitution group.
*
* @see #substitutionHeadNamespace()
*/
String substitutionHeadName() default "";
/**
* Default value of this element.
*
* <p>
* The <pre>'\u0000'</pre> value specified as a default of this annotation element
* is used as a poor-man's substitute for null to allow implementations
* to recognize the 'no default value' state.
*/
String defaultValue() default "\u0000";
/**
* Used in {@link XmlElementDecl#scope()} to
* signal that the declaration is in the global scope.
*/
public final class GLOBAL {}
}

View File

@@ -0,0 +1,290 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
/**
* <p>
* Maps a JavaBean property to a XML element derived from property's type.
* <p>
* <b>Usage</b>
* <p>
* <tt>&#64;XmlElementRef</tt> annotation can be used with a
* JavaBean property or from within {@link XmlElementRefs}
* <p>
* This annotation dynamically associates an XML element name with the JavaBean
* property. When a JavaBean property is annotated with {@link
* XmlElement}, the XML element name is statically derived from the
* JavaBean property name. However, when this annotation is used, the
* XML element name is derived from the instance of the type of the
* JavaBean property at runtime.
*
* <h3> XML Schema substitution group support </h3>
* XML Schema allows a XML document author to use XML element names
* that were not statically specified in the content model of a
* schema using substitution groups. Schema derived code provides
* support for substitution groups using an <i>element property</i>,
* (section 5.5.5, "Element Property" of JAXB 2.0 specification). An
* element property method signature is of the form:
* <pre>
* public void setTerm(JAXBElement<? extends Operator>);
* public JAXBElement<? extends Operator> getTerm();
* </pre>
* <p>
* An element factory method annotated with {@link XmlElementDecl} is
* used to create a <tt>JAXBElement</tt> instance, containing an XML
* element name. The presence of &#64;XmlElementRef annotation on an
* element property indicates that the element name from <tt>JAXBElement</tt>
* instance be used instead of deriving an XML element name from the
* JavaBean property name.
*
* <p>
* The usage is subject to the following constraints:
* <ul>
* <li> If the collection item type (for collection property) or
* property type (for single valued property) is
* {@link javax.xml.bind.JAXBElement}, then
* <tt>&#64;XmlElementRef}.name()</tt> and <tt>&#64;XmlElementRef.namespace()</tt> must
* point an element factory method with an @XmlElementDecl
* annotation in a class annotated with @XmlRegistry (usually
* ObjectFactory class generated by the schema compiler) :
* <ul>
* <li> @XmlElementDecl.name() must equal @XmlElementRef.name() </li>
* <li> @XmlElementDecl.namespace() must equal @XmlElementRef.namespace(). </li>
* </ul>
* </li>
* <li> If the collection item type (for collection property) or
* property type (for single valued property) is not
* {@link javax.xml.bind.JAXBElement}, then the type referenced by the
* property or field must be annotated with {@link XmlRootElement}. </li>
* <li> This annotation can be used with the following annotations:
* {@link XmlElementWrapper}, {@link XmlJavaTypeAdapter}.
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p><b>Example 1: Ant Task Example</b></p>
* The following Java class hierarchy models an Ant build
* script. An Ant task corresponds to a class in the class
* hierarchy. The XML element name of an Ant task is indicated by the
* &#64;XmlRootElement annotation on its corresponding class.
* <pre>
* &#64;XmlRootElement(name="target")
* class Target {
* // The presence of &#64;XmlElementRef indicates that the XML
* // element name will be derived from the &#64;XmlRootElement
* // annotation on the type (for e.g. "jar" for JarTask).
* &#64;XmlElementRef
* List&lt;Task> tasks;
* }
*
* abstract class Task {
* }
*
* &#64;XmlRootElement(name="jar")
* class JarTask extends Task {
* ...
* }
*
* &#64;XmlRootElement(name="javac")
* class JavacTask extends Task {
* ...
* }
*
* &lt;!-- XML Schema fragment -->
* &lt;xs:element name="target" type="Target">
* &lt;xs:complexType name="Target">
* &lt;xs:sequence>
* &lt;xs:choice maxOccurs="unbounded">
* &lt;xs:element ref="jar">
* &lt;xs:element ref="javac">
* &lt;/xs:choice>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
*
* </pre>
* <p>
* Thus the following code fragment:
* <pre>
* Target target = new Target();
* target.tasks.add(new JarTask());
* target.tasks.add(new JavacTask());
* marshal(target);
* </pre>
* will produce the following XML output:
* <pre>
* &lt;target>
* &lt;jar>
* ....
* &lt;/jar>
* &lt;javac>
* ....
* &lt;/javac>
* &lt;/target>
* </pre>
* <p>
* It is not an error to have a class that extends <tt>Task</tt>
* that doesn't have {@link XmlRootElement}. But they can't show up in an
* XML instance (because they don't have XML element names).
*
* <p><b>Example 2: XML Schema Susbstitution group support</b>
* <p> The following example shows the annotations for XML Schema
* substitution groups. The annotations and the ObjectFactory are
* derived from the schema.
*
* <pre>
* &#64;XmlElement
* class Math {
* // The value of {@link #type()}is
* // JAXBElement.class , which indicates the XML
* // element name ObjectFactory - in general a class marked
* // with &#64;XmlRegistry. (See ObjectFactory below)
* //
* // The {@link #name()} is "operator", a pointer to a
* // factory method annotated with a
* // {@link XmlElementDecl} with the name "operator". Since
* // "operator" is the head of a substitution group that
* // contains elements "add" and "sub" elements, "operator"
* // element can be substituted in an instance document by
* // elements "add" or "sub". At runtime, JAXBElement
* // instance contains the element name that has been
* // substituted in the XML document.
* //
* &#64;XmlElementRef(type=JAXBElement.class,name="operator")
* JAXBElement&lt;? extends Operator> term;
* }
*
* &#64;XmlRegistry
* class ObjectFactory {
* &#64;XmlElementDecl(name="operator")
* JAXBElement&lt;Operator> createOperator(Operator o) {...}
* &#64;XmlElementDecl(name="add",substitutionHeadName="operator")
* JAXBElement&lt;Operator> createAdd(Operator o) {...}
* &#64;XmlElementDecl(name="sub",substitutionHeadName="operator")
* JAXBElement&lt;Operator> createSub(Operator o) {...}
* }
*
* class Operator {
* ...
* }
* </pre>
* <p>
* Thus, the following code fragment
* <pre>
* Math m = new Math();
* m.term = new ObjectFactory().createAdd(new Operator());
* marshal(m);
* </pre>
* will produce the following XML output:
* <pre>
* &lt;math>
* &lt;add>...&lt;/add>
* &lt;/math>
* </pre>
*
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems,Inc. </li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @see XmlElementRefs
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlElementRef {
/**
* The Java type being referenced.
* <p>
* If the value is DEFAULT.class, the type is inferred from the
* the type of the JavaBean property.
*/
Class type() default DEFAULT.class;
/**
* This parameter and {@link #name()} are used to determine the
* XML element for the JavaBean property.
*
* <p> If <tt>type()</tt> is <tt>JAXBElement.class</tt> , then
* <tt>namespace()</tt> and <tt>name()</tt>
* point to a factory method with {@link XmlElementDecl}. The XML
* element name is the element name from the factory method's
* {@link XmlElementDecl} annotation or if an element from its
* substitution group (of which it is a head element) has been
* substituted in the XML document, then the element name is from the
* {@link XmlElementDecl} on the substituted element.
*
* <p> If {@link #type()} is not <tt>JAXBElement.class</tt>, then
* the XML element name is the XML element name statically
* associated with the type using the annotation {@link
* XmlRootElement} on the type. If the type is not annotated with
* an {@link XmlElementDecl}, then it is an error.
*
* <p> If <tt>type()</tt> is not <tt>JAXBElement.class</tt>, then
* this value must be "".
*
*/
String namespace() default "";
/**
*
* @see #namespace()
*/
String name() default "##default";
/**
* Used in {@link XmlElementRef#type()} to
* signal that the type be inferred from the signature
* of the property.
*/
static final class DEFAULT {}
/**
* Customize the element declaration to be required.
* <p>
* If required() is true, then Javabean property is mapped to
* an XML schema element declaration with minOccurs="1".
* maxOccurs is "1" for a single valued property and "unbounded"
* for a multivalued property.
*
* <p>
* If required() is false, then the Javabean property is mapped
* to XML Schema element declaration with minOccurs="0".
* maxOccurs is "1" for a single valued property and "unbounded"
* for a multivalued property.
*
* <p>
* For compatibility with JAXB 2.1, this property defaults to <tt>true</tt>,
* despite the fact that {@link XmlElement#required()} defaults to false.
*
* @since 2.2
*/
boolean required() default true;
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marks a property that refers to classes with {@link XmlElement}
* or JAXBElement.
*
* <p>
* Compared to an element property (property with {@link XmlElement}
* annotation), a reference property has a different substitution semantics.
* When a sub-class is assigned to a property, an element property produces
* the same tag name with @xsi:type, whereas a reference property produces
* a different tag name (the tag name that's on the the sub-class.)
*
* <p> This annotation can be used with the following annotations:
* {@link XmlJavaTypeAdapter}, {@link XmlElementWrapper}.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
*
* @see XmlElementWrapper
* @see XmlElementRef
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlElementRefs {
XmlElementRef[] value();
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Generates a wrapper element around XML representation.
*
* This is primarily intended to be used to produce a wrapper
* XML element around collections. The annotation therefore supports
* two forms of serialization shown below.
*
* <pre>
* //Example: code fragment
* int[] names;
*
* // XML Serialization Form 1 (Unwrapped collection)
* &lt;names> ... &lt;/names>
* &lt;names> ... &lt;/names>
*
* // XML Serialization Form 2 ( Wrapped collection )
* &lt;wrapperElement>
* &lt;names> value-of-item &lt;/names>
* &lt;names> value-of-item &lt;/names>
* ....
* &lt;/wrapperElement>
* </pre>
*
* <p> The two serialized XML forms allow a null collection to be
* represented either by absence or presence of an element with a
* nillable attribute.
*
* <p> <b>Usage</b> </p>
* <p>
* The <tt>@XmlElementWrapper</tt> annotation can be used with the
* following program elements:
* <ul>
* <li> JavaBean property </li>
* <li> non static, non transient field </li>
* </ul>
*
* <p>The usage is subject to the following constraints:
* <ul>
* <li> The property must be a collection property </li>
* <li> This annotation can be used with the following annotations:
* {@link XmlElement},
* {@link XmlElements},
* {@link XmlElementRef},
* {@link XmlElementRefs},
* {@link XmlJavaTypeAdapter}.</li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @see XmlElement
* @see XmlElements
* @see XmlElementRef
* @see XmlElementRefs
* @since JAXB2.0
*
*/
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlElementWrapper {
/**
* Name of the XML wrapper element. By default, the XML wrapper
* element name is derived from the JavaBean property name.
*/
String name() default "##default";
/**
* XML target namespace of the XML wrapper element.
* <p>
* If the value is "##default", then the namespace is determined
* as follows:
* <ol>
* <li>
* If the enclosing package has {@link XmlSchema} annotation,
* and its {@link XmlSchema#elementFormDefault() elementFormDefault}
* is {@link XmlNsForm#QUALIFIED QUALIFIED}, then the namespace of
* the enclosing class.
*
* <li>
* Otherwise "" (which produces unqualified element in the default
* namespace.
* </ol>
*/
String namespace() default "##default";
/**
* If true, the absence of the collection is represented by
* using <tt>xsi:nil='true'</tt>. Otherwise, it is represented by
* the absence of the element.
*/
boolean nillable() default false;
/**
* Customize the wrapper element declaration to be required.
*
* <p>
* If required() is true, then the corresponding generated
* XML schema element declaration will have <tt>minOccurs="1"</tt>,
* to indicate that the wrapper element is always expected.
*
* <p>
* Note that this only affects the schema generation, and
* not the unmarshalling or marshalling capability. This is
* simply a mechanism to let users express their application constraints
* better.
*
* @since JAXB 2.1
*/
boolean required() default false;
}

View File

@@ -0,0 +1,177 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* <p>
* A container for multiple @{@link XmlElement} annotations.
*
* Multiple annotations of the same type are not allowed on a program
* element. This annotation therefore serves as a container annotation
* for multiple &#64;XmlElements as follows:
*
* <pre>
* &#64;XmlElements({ @XmlElement(...),@XmlElement(...) })
* </pre>
*
* <p>The <tt>@XmlElements</tt> annnotation can be used with the
* following program elements: </p>
* <ul>
* <li> a JavaBean property </li>
* <li> non static, non transient field </li>
* </ul>
*
* This annotation is intended for annotation a JavaBean collection
* property (e.g. List).
*
* <p><b>Usage</b></p>
*
* <p>The usage is subject to the following constraints:
* <ul>
* <li> This annotation can be used with the following
* annotations: @{@link XmlIDREF}, @{@link XmlElementWrapper}. </li>
* <li> If @XmlIDREF is also specified on the JavaBean property,
* then each &#64;XmlElement.type() must contain a JavaBean
* property annotated with <tt>&#64;XmlID</tt>.</li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <hr>
*
* <p><b>Example 1:</b> Map to a list of elements</p>
* <pre>
*
* // Mapped code fragment
* public class Foo {
* &#64;XmlElements(
* &#64;XmlElement(name="A", type=Integer.class),
* &#64;XmlElement(name="B", type=Float.class)
* }
* public List items;
* }
*
* &lt;!-- XML Representation for a List of {1,2.5}
* XML output is not wrapped using another element -->
* ...
* &lt;A> 1 &lt;/A>
* &lt;B> 2.5 &lt;/B>
* ...
*
* &lt;!-- XML Schema fragment -->
* &lt;xs:complexType name="Foo">
* &lt;xs:sequence>
* &lt;xs:choice minOccurs="0" maxOccurs="unbounded">
* &lt;xs:element name="A" type="xs:int"/>
* &lt;xs:element name="B" type="xs:float"/>
* &lt;xs:choice>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
*
* </pre>
*
* <p><b>Example 2:</b> Map to a list of elements wrapped with another element
* </p>
* <pre>
*
* // Mapped code fragment
* public class Foo {
* &#64;XmlElementWrapper(name="bar")
* &#64;XmlElements(
* &#64;XmlElement(name="A", type=Integer.class),
* &#64;XmlElement(name="B", type=Float.class)
* }
* public List items;
* }
*
* &lt;!-- XML Schema fragment -->
* &lt;xs:complexType name="Foo">
* &lt;xs:sequence>
* &lt;xs:element name="bar">
* &lt;xs:complexType>
* &lt;xs:choice minOccurs="0" maxOccurs="unbounded">
* &lt;xs:element name="A" type="xs:int"/>
* &lt;xs:element name="B" type="xs:float"/>
* &lt;/xs:choice>
* &lt;/xs:complexType>
* &lt;/xs:element>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p><b>Example 3:</b> Change element name based on type using an adapter.
* </p>
* <pre>
* class Foo {
* &#64;XmlJavaTypeAdapter(QtoPAdapter.class)
* &#64;XmlElements({
* &#64;XmlElement(name="A",type=PX.class),
* &#64;XmlElement(name="B",type=PY.class)
* })
* Q bar;
* }
*
* &#64;XmlType abstract class P {...}
* &#64;XmlType(name="PX") class PX extends P {...}
* &#64;XmlType(name="PY") class PY extends P {...}
*
* &lt;!-- XML Schema fragment -->
* &lt;xs:complexType name="Foo">
* &lt;xs:sequence>
* &lt;xs:element name="bar">
* &lt;xs:complexType>
* &lt;xs:choice minOccurs="0" maxOccurs="unbounded">
* &lt;xs:element name="A" type="PX"/>
* &lt;xs:element name="B" type="PY"/>
* &lt;/xs:choice>
* &lt;/xs:complexType>
* &lt;/xs:element>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @see XmlElement
* @see XmlElementRef
* @see XmlElementRefs
* @see XmlJavaTypeAdapter
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD,METHOD})
public @interface XmlElements {
/**
* Collection of @{@link XmlElement} annotations
*/
XmlElement[] value();
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* <p>
* Maps an enum type {@link Enum} to XML representation.
*
* <p>This annotation, together with {@link XmlEnumValue} provides a
* mapping of enum type to XML representation.
*
* <p> <b>Usage</b> </p>
* <p>
* The <tt>@XmlEnum</tt> annotation can be used with the
* following program elements:
* <ul>
* <li>enum type</li>
* </ul>
*
* <p> The usage is subject to the following constraints:
* <ul>
* <li> This annotation can be used the following other annotations:
* {@link XmlType},
* {@link XmlRootElement} </li>
* </ul>
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information </p>
*
* <p>An enum type is mapped to a schema simple type with enumeration
* facets. The schema type is derived from the Java type to which
* <tt>@XmlEnum.value()</tt>. Each enum constant <tt>@XmlEnumValue</tt>
* must have a valid lexical representation for the type
* <tt>@XmlEnum.value()</tt> .
*
* <p><b>Examples:</b> See examples in {@link XmlEnumValue}
*
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({TYPE})
public @interface XmlEnum {
/**
* Java type that is mapped to a XML simple type.
*
*/
Class<?> value() default String.class;
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
/**
* Maps an enum constant in {@link Enum} type to XML representation.
*
* <p> <b>Usage</b> </p>
*
* <p> The <tt>@XmlEnumValue</tt> annotation can be used with the
* following program elements:
* <ul>
* <li>enum constant</li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p>This annotation, together with {@link XmlEnum} provides a
* mapping of enum type to XML representation.
*
* <p>An enum type is mapped to a schema simple type with enumeration
* facets. The schema type is derived from the Java type specified in
* <tt>@XmlEnum.value()</tt>. Each enum constant <tt>@XmlEnumValue</tt>
* must have a valid lexical representation for the type
* <tt>@XmlEnum.value()</tt>
*
* <p> In the absence of this annotation, {@link Enum#name()} is used
* as the XML representation.
*
* <p> <b>Example 1: </b>Map enum constant name -> enumeration facet</p>
* <pre>
* //Example: Code fragment
* &#64;XmlEnum(String.class)
* public enum Card { CLUBS, DIAMONDS, HEARTS, SPADES }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:simpleType name="Card">
* &lt;xs:restriction base="xs:string"/>
* &lt;xs:enumeration value="CLUBS"/>
* &lt;xs:enumeration value="DIAMONDS"/>
* &lt;xs:enumeration value="HEARTS"/>
* &lt;xs:enumeration value="SPADES"/>
* &lt;/xs:simpleType>
* </pre>
*
* <p><b>Example 2: </b>Map enum constant name(value) -> enumeration facet </p>
* <pre>
* //Example: code fragment
* &#64;XmlType
* &#64;XmlEnum(Integer.class)
* public enum Coin {
* &#64;XmlEnumValue("1") PENNY(1),
* &#64;XmlEnumValue("5") NICKEL(5),
* &#64;XmlEnumValue("10") DIME(10),
* &#64;XmlEnumValue("25") QUARTER(25) }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:simpleType name="Coin">
* &lt;xs:restriction base="xs:int">
* &lt;xs:enumeration value="1"/>
* &lt;xs:enumeration value="5"/>
* &lt;xs:enumeration value="10"/>
* &lt;xs:enumeration value="25"/>
* &lt;/xs:restriction>
* &lt;/xs:simpleType>
* </pre>
*
* <p><b>Example 3: </b>Map enum constant name -> enumeration facet </p>
*
* <pre>
* //Code fragment
* &#64;XmlType
* &#64;XmlEnum(Integer.class)
* public enum Code {
* &#64;XmlEnumValue("1") ONE,
* &#64;XmlEnumValue("2") TWO;
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:simpleType name="Code">
* &lt;xs:restriction base="xs:int">
* &lt;xs:enumeration value="1"/>
* &lt;xs:enumeration value="2"/>
* &lt;/xs:restriction>
* &lt;/xs:simpleType>
* </pre>
*
* @since JAXB 2.0
*/
@Retention(RUNTIME)
@Target({FIELD})
public @interface XmlEnumValue {
String value();
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p>
* Maps a JavaBean property to XML ID.
*
* <p>
* To preserve referential integrity of an object graph across XML
* serialization followed by a XML deserialization, requires an object
* reference to be marshalled by reference or containment
* appropriately. Annotations <tt>&#64;XmlID</tt> and <tt>&#64;XmlIDREF</tt>
* together allow a customized mapping of a JavaBean property's
* type by containment or reference.
*
* <p><b>Usage</b> </p>
* The <tt>&#64;XmlID</tt> annotation can be used with the following
* program elements:
* <ul>
* <li> a JavaBean property </li>
* <li> non static, non transient field </li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* The usage is subject to the following constraints:
* <ul>
* <li> At most one field or property in a class can be annotated
* with <tt>&#64;XmlID</tt>. </li>
* <li> The JavaBean property's type must be <tt>java.lang.String</tt>.</li>
* <li> The only other mapping annotations that can be used
* with <tt>&#64;XmlID</tt>
* are:<tt>&#64;XmlElement</tt> and <tt>&#64;XmlAttribute</tt>.</li>
* </ul>
*
* <p><b>Example</b>: Map a JavaBean property's type to <tt>xs:ID</tt></p>
* <pre>
* // Example: code fragment
* public class Customer {
* &#64;XmlAttribute
* &#64;XmlID
* public String getCustomerID();
* public void setCustomerID(String id);
* .... other properties not shown
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="Customer">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* ....
* &lt;/xs:sequence>
* &lt;xs:attribute name="customerID" type="xs:ID"/>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
* </pre>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @see XmlIDREF
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlID { }

View File

@@ -0,0 +1,250 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p>
* Maps a JavaBean property to XML IDREF.
*
* <p>
* To preserve referential integrity of an object graph across XML
* serialization followed by a XML deserialization, requires an object
* reference to be marshalled by reference or containment
* appropriately. Annotations <tt>&#64;XmlID</tt> and <tt>&#64;XmlIDREF</tt>
* together allow a customized mapping of a JavaBean property's
* type by containment or reference.
*
* <p><b>Usage</b> </p>
* The <tt>&#64;XmlIDREF</tt> annotation can be used with the following
* program elements:
* <ul>
* <li> a JavaBean property </li>
* <li> non static, non transient field </li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p> The usage is subject to the following constraints:
* <ul>
*
* <li> If the type of the field or property is a collection type,
* then the collection item type must contain a property or
* field annotated with <tt>&#64;XmlID</tt>. </li>
* <li> If the field or property is single valued, then the type of
* the property or field must contain a property or field
* annotated with <tt>&#64;XmlID</tt>.
* <p>Note: If the collection item type or the type of the
* property (for non collection type) is java.lang.Object, then
* the instance must contain a property/field annotated with
* <tt>&#64;XmlID</tt> attribute.
* </li>
* <li> This annotation can be used with the following annotations:
* {@link XmlElement}, {@link XmlAttribute}, {@link XmlList},
* and {@link XmlElements}.</li>
*
* </ul>
* <p><b>Example:</b> Map a JavaBean property to <tt>xs:IDREF</tt>
* (i.e. by reference rather than by containment)</p>
* <pre>
*
* //EXAMPLE: Code fragment
* public class Shipping {
* &#64;XmlIDREF public Customer getCustomer();
* public void setCustomer(Customer customer);
* ....
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="Shipping">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* &lt;xs:element name="customer" type="xs:IDREF"/>
* ....
* &lt;/xs:sequence>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
*
* </pre>
*
*
* <p><b>Example 2: </b> The following is a complete example of
* containment versus reference.
*
* <pre>
* // By default, Customer maps to complex type <tt>xs:Customer</tt>
* public class Customer {
*
* // map JavaBean property type to <tt>xs:ID</tt>
* &#64;XmlID public String getCustomerID();
* public void setCustomerID(String id);
*
* // .... other properties not shown
* }
*
*
* // By default, Invoice maps to a complex type <tt>xs:Invoice</tt>
* public class Invoice {
*
* // map by reference
* &#64;XmlIDREF public Customer getCustomer();
* public void setCustomer(Customer customer);
*
* // .... other properties not shown here
* }
*
* // By default, Shipping maps to complex type <tt>xs:Shipping</tt>
* public class Shipping {
*
* // map by reference
* &#64;XmlIDREF public Customer getCustomer();
* public void setCustomer(Customer customer);
* }
*
* // at least one class must reference Customer by containment;
* // Customer instances won't be marshalled.
* &#64;XmlElement(name="CustomerData")
* public class CustomerData {
* // map reference to Customer by containment by default.
* public Customer getCustomer();
*
* // maps reference to Shipping by containment by default.
* public Shipping getShipping();
*
* // maps reference to Invoice by containment by default.
* public Invoice getInvoice();
* }
*
* &lt;!-- XML Schema mapping for above code frament -->
*
* &lt;xs:complexType name="Invoice">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* &lt;xs:element name="customer" type="xs:IDREF"/>
* ....
* &lt;/xs:sequence>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
*
* &lt;xs:complexType name="Shipping">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* &lt;xs:element name="customer" type="xs:IDREF"/>
* ....
* &lt;/xs:sequence>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
*
* &lt;xs:complexType name="Customer">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* ....
* &lt;/xs:sequence>
* &lt;xs:attribute name="CustomerID" type="xs:ID"/>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
*
* &lt;xs:complexType name="CustomerData">
* &lt;xs:complexContent>
* &lt;xs:sequence>
* &lt;xs:element name="customer" type="xs:Customer"/>
* &lt;xs:element name="shipping" type="xs:Shipping"/>
* &lt;xs:element name="invoice" type="xs:Invoice"/>
* &lt;/xs:sequence>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
*
* &lt;xs:element name"customerData" type="xs:CustomerData"/>
*
* &lt;!-- Instance document conforming to the above XML Schema -->
* &lt;customerData>
* &lt;customer customerID="Alice">
* ....
* &lt;/customer>
*
* &lt;shipping customer="Alice">
* ....
* &lt;/shipping>
*
* &lt;invoice customer="Alice">
* ....
* &lt;/invoice>
* &lt;/customerData>
*
* </pre>
*
* <p><b>Example 3: </b> Mapping List to repeating element of type IDREF
* <pre>
* // Code fragment
* public class Shipping {
* &#64;XmlIDREF
* &#64;XmlElement(name="Alice")
* public List customers;
* }
*
* &lt;!-- XML schema fragment -->
* &lt;xs:complexType name="Shipping">
* &lt;xs:sequence>
* &lt;xs:choice minOccurs="0" maxOccurs="unbounded">
* &lt;xs:element name="Alice" type="xs:IDREF"/>
* &lt;/xs:choice>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p><b>Example 4: </b> Mapping a List to a list of elements of type IDREF.
* <pre>
* //Code fragment
* public class Shipping {
* &#64;XmlIDREF
* &#64;XmlElements(
* &#64;XmlElement(name="Alice", type="Customer.class")
* &#64;XmlElement(name="John", type="InternationalCustomer.class")
* public List customers;
* }
*
* &lt;!-- XML Schema fragment -->
* &lt;xs:complexType name="Shipping">
* &lt;xs:sequence>
* &lt;xs:choice minOccurs="0" maxOccurs="unbounded">
* &lt;xs:element name="Alice" type="xs:IDREF"/>
* &lt;xs:element name="John" type="xs:IDREF"/>
* &lt;/xs:choice>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @see XmlID
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlIDREF {}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import javax.xml.transform.Source;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.activation.DataHandler;
/**
* Disable consideration of XOP encoding for datatypes that are bound to
* base64-encoded binary data in XML.
*
* <p>
* When XOP encoding is enabled as described in {@link AttachmentMarshaller#isXOPPackage()}, this annotation disables datatypes such as {@link java.awt.Image} or {@link Source} or <tt>byte[]</tt> that are bound to base64-encoded binary from being considered for
* XOP encoding. If a JAXB property is annotated with this annotation or if
* the JAXB property's base type is annotated with this annotation,
* neither
* {@link AttachmentMarshaller#addMtomAttachment(DataHandler, String, String)}
* nor
* {@link AttachmentMarshaller#addMtomAttachment(byte[], int, int, String, String, String)} is
* ever called for the property. The binary data will always be inlined.
*
* @author Joseph Fialli
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD,TYPE})
public @interface XmlInlineBinaryData {
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
/**
* Used to map a property to a list simple type.
*
* <p><b>Usage</b> </p>
* <p>
* The <tt>@XmlList</tt> annotation can be used with the
* following program elements:
* <ul>
* <li> JavaBean property </li>
* <li> field </li>
* </ul>
*
* <p>
* When a collection property is annotated just with @XmlElement,
* each item in the collection will be wrapped by an element.
* For example,
*
* <pre>
* &#64;XmlRootElement
* class Foo {
* &#64;XmlElement
* List&lt;String> data;
* }
* </pre>
*
* would produce XML like this:
*
* <pre>
* &lt;foo>
* &lt;data>abc</data>
* &lt;data>def</data>
* &lt;/foo>
* </pre>
*
* &#64;XmlList annotation, on the other hand, allows multiple values to be
* represented as whitespace-separated tokens in a single element. For example,
*
* <pre>
* &#64;XmlRootElement
* class Foo {
* &#64;XmlElement
* &#64;XmlList
* List&lt;String> data;
* }
* </pre>
*
* the above code will produce XML like this:
*
* <pre>
* &lt;foo>
* &lt;data>abc def</data>
* &lt;/foo>
* </pre>
*
* <p>This annotation can be used with the following annotations:
* {@link XmlElement},
* {@link XmlAttribute},
* {@link XmlValue},
* {@link XmlIDREF}.
* <ul>
* <li> The use of <tt>@XmlList</tt> with {@link XmlValue} while
* allowed, is redundant since {@link XmlList} maps a
* collection type to a simple schema type that derives by
* list just as {@link XmlValue} would. </li>
*
* <li> The use of <tt>@XmlList</tt> with {@link XmlAttribute} while
* allowed, is redundant since {@link XmlList} maps a
* collection type to a simple schema type that derives by
* list just as {@link XmlAttribute} would. </li>
* </ul>
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD,METHOD,PARAMETER})
public @interface XmlList {
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import javax.xml.transform.Source;
/**
* Associates the MIME type that controls the XML representation of the property.
*
* <p>
* This annotation is used in conjunction with datatypes such as
* {@link java.awt.Image} or {@link Source} that are bound to base64-encoded binary in XML.
*
* <p>
* If a property that has this annotation has a sibling property bound to
* the xmime:contentType attribute, and if in the instance the property has a value,
* the value of the attribute takes precedence and that will control the marshalling.
*
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD,PARAMETER})
public @interface XmlMimeType {
/**
* The textual representation of the MIME type,
* such as "image/jpeg" "image/*", "text/xml; charset=iso-8859-1" and so on.
*/
String value();
}

View File

@@ -0,0 +1,132 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBElement;
/**
* <p>
* Annotate a JavaBean multi-valued property to support mixed content.
*
* <p>
* The usage is subject to the following constraints:
* <ul>
* <li> can be used with &#64;XmlElementRef, &#64;XmlElementRefs or &#64;XmlAnyElement</li>
* </ul>
* <p>
* The following can be inserted into &#64;XmlMixed annotated multi-valued property
* <ul>
* <li>XML text information items are added as values of java.lang.String.</li>
* <li>Children element information items are added as instances of
* {@link JAXBElement} or instances with a class that is annotated with
* &#64;XmlRootElement.</li>
* <li>Unknown content that is not be bound to a JAXB mapped class is inserted
* as {@link Element}. (Assumes property annotated with &#64;XmlAnyElement)</li>
* </ul>
*
* Below is an example of binding and creation of mixed content.
* <pre>
* &lt;!-- schema fragment having mixed content -->
* &lt;xs:complexType name="letterBody" mixed="true">
* &lt;xs:sequence>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;xs:element name="quantity" type="xs:positiveInteger"/>
* &lt;xs:element name="productName" type="xs:string"/>
* &lt;!-- etc. -->
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* &lt;xs:element name="letterBody" type="letterBody"/>
*
* // Schema-derived Java code:
* // (Only annotations relevant to mixed content are shown below,
* // others are ommitted.)
* import java.math.BigInteger;
* public class ObjectFactory {
* // element instance factories
* JAXBElement&lt;LetterBody> createLetterBody(LetterBody value);
* JAXBElement&lt;String> createLetterBodyName(String value);
* JAXBElement&lt;BigInteger> createLetterBodyQuantity(BigInteger value);
* JAXBElement&lt;String> createLetterBodyProductName(String value);
* // type instance factory
* LetterBody> createLetterBody();
* }
* </pre>
* <pre>
* public class LetterBody {
* // Mixed content can contain instances of Element classes
* // Name, Quantity and ProductName. Text data is represented as
* // java.util.String for text.
* &#64;XmlMixed
* &#64;XmlElementRefs({
* &#64;XmlElementRef(name="productName", type=JAXBElement.class),
* &#64;XmlElementRef(name="quantity", type=JAXBElement.class),
* &#64;XmlElementRef(name="name", type=JAXBElement.class)})
* List getContent(){...}
* }
* </pre>
* The following is an XML instance document with mixed content
* <pre>
* &lt;letterBody>
* Dear Mr.&lt;name>Robert Smith&lt;/name>
* Your order of &lt;quantity>1&lt;/quantity> &lt;productName>Baby
* Monitor&lt;/productName> shipped from our warehouse. ....
* &lt;/letterBody>
* </pre>
* that can be constructed using following JAXB API calls.
* <pre>
* LetterBody lb = ObjectFactory.createLetterBody();
* JAXBElement&lt;LetterBody> lbe = ObjectFactory.createLetterBody(lb);
* List gcl = lb.getContent(); //add mixed content to general content property.
* gcl.add("Dear Mr."); // add text information item as a String.
*
* // add child element information item
* gcl.add(ObjectFactory.createLetterBodyName("Robert Smith"));
* gcl.add("Your order of "); // add text information item as a String
*
* // add children element information items
* gcl.add(ObjectFactory.
* createLetterBodyQuantity(new BigInteger("1")));
* gcl.add(ObjectFactory.createLetterBodyProductName("Baby Monitor"));
* gcl.add("shipped from our warehouse"); // add text information item
* </pre>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
* @author Kohsuke Kawaguchi
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlMixed {
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* <p>
* Associates a namespace prefix with a XML namespace URI.
*
* <p><b>Usage</b></p>
* <p><tt>@XmlNs</tt> annotation is intended for use from other
* program annotations.
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p><b>Example:</b>See <tt>XmlSchema</tt> annotation type for an example.
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({})
public @interface XmlNs {
/**
* Namespace prefix
*/
String prefix();
/**
* Namespace URI
*/
String namespaceURI();
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
/**
* Enumeration of XML Schema namespace qualifications.
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p><b>Usage</b>
* <p>
* The namespace qualification values are used in the annotations
* defined in this packge. The enumeration values are mapped as follows:
*
* <p>
* <table border="1" cellpadding="4" cellspacing="3">
* <tbody>
* <tr>
* <td><b>Enum Value</b></td>
* <td><b>XML Schema Value</b></td>
* </tr>
*
* <tr valign="top">
* <td>UNQUALIFIED</td>
* <td>unqualified</td>
* </tr>
* <tr valign="top">
* <td>QUALIFIED</td>
* <td>qualified</td>
* </tr>
* <tr valign="top">
* <td>UNSET</td>
* <td>namespace qualification attribute is absent from the
* XML Schema fragment</td>
* </tr>
* </tbody>
* </table>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
public enum XmlNsForm {UNQUALIFIED, QUALIFIED, UNSET}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marks a class that has {@link XmlElementDecl}s.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @since JAXB 2.0
* @see XmlElementDecl
*/
@Retention(RUNTIME)
@Target({TYPE})
public @interface XmlRegistry {
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.TYPE;
/**
* Maps a class or an enum type to an XML element.
*
* <p> <b>Usage</b> </p>
* <p>
* The &#64;XmlRootElement annotation can be used with the following program
* elements:
* <ul>
* <li> a top level class </li>
* <li> an enum type </li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p>
* When a top level class or an enum type is annotated with the
* &#64;XmlRootElement annotation, then its value is represented
* as XML element in an XML document.
*
* <p> This annotation can be used with the following annotations:
* {@link XmlType}, {@link XmlEnum}, {@link XmlAccessorType},
* {@link XmlAccessorOrder}.
* <p>
* <p>
* <b>Example 1: </b> Associate an element with XML Schema type
* <pre>
* // Example: Code fragment
* &#64;XmlRootElement
* class Point {
* int x;
* int y;
* Point(int _x,int _y) {x=_x;y=_y;}
* }
* </pre>
*
* <pre>
* //Example: Code fragment corresponding to XML output
* marshal( new Point(3,5), System.out);
* </pre>
*
* <pre>
* &lt;!-- Example: XML output -->
* &lt;point>
* &lt;x> 3 </x>
* &lt;y> 5 </y>
* &lt;/point>
* </pre>
*
* The annotation causes an global element declaration to be produced
* in the schema. The global element declaration is associated with
* the XML schema type to which the class is mapped.
*
* <pre>
* &lt;!-- Example: XML schema definition -->
* &lt;xs:element name="point" type="point"/>
* &lt;xs:complexType name="point">
* &lt;xs:sequence>
* &lt;xs:element name="x" type="xs:int"/>
* &lt;xs:element name="y" type="xs:int"/>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p>
*
* <b>Example 2: Orthogonality to type inheritance </b>
*
* <p>
* An element declaration annotated on a type is not inherited by its
* derived types. The following example shows this.
* <pre>
* // Example: Code fragment
* &#64;XmlRootElement
* class Point3D extends Point {
* int z;
* Point3D(int _x,int _y,int _z) {super(_x,_y);z=_z;}
* }
*
* //Example: Code fragment corresponding to XML output *
* marshal( new Point3D(3,5,0), System.out );
*
* &lt;!-- Example: XML output -->
* &lt;!-- The element name is point3D not point -->
* &lt;point3D>
* &lt;x>3&lt;/x>
* &lt;y>5&lt;/y>
* &lt;z>0&lt;/z>
* &lt;/point3D>
*
* &lt;!-- Example: XML schema definition -->
* &lt;xs:element name="point3D" type="point3D"/>
* &lt;xs:complexType name="point3D">
* &lt;xs:complexContent>
* &lt;xs:extension base="point">
* &lt;xs:sequence>
* &lt;xs:element name="z" type="xs:int"/>
* &lt;/xs:sequence>
* &lt;/xs:extension>
* &lt;/xs:complexContent>
* &lt;/xs:complexType>
* </pre>
*
* <b>Example 3: </b> Associate a global element with XML Schema type
* to which the class is mapped.
* <pre>
* //Example: Code fragment
* &#64;XmlRootElement(name="PriceElement")
* public class USPrice {
* &#64;XmlElement
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example: XML schema definition -->
* &lt;xs:element name="PriceElement" type="USPrice"/>
* &lt;xs:complexType name="USPrice">
* &lt;xs:sequence>
* &lt;xs:element name="price" type="xs:decimal"/>
* &lt;/sequence>
* &lt;/xs:complexType>
* </pre>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME)
@Target({TYPE})
public @interface XmlRootElement {
/**
* namespace name of the XML element.
* <p>
* If the value is "##default", then the XML namespace name is derived
* from the package of the class ( {@link XmlSchema} ). If the
* package is unnamed, then the XML namespace is the default empty
* namespace.
*/
String namespace() default "##default";
/**
* local name of the XML element.
* <p>
* If the value is "##default", then the name is derived from the
* class name.
*
*/
String name() default "##default";
}

View File

@@ -0,0 +1,206 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p> Maps a package name to a XML namespace. </p>
*
* <h3>Usage</h3>
* <p>
* The XmlSchema annotation can be used with the following program
* elements:
* <ul>
* <li>package</li>
* </ul>
*
* <p>
* This is a package level annotation and follows the recommendations
* and restrictions contained in JSR 175, section III, "Annotations".
* Thus the usage is subject to the following constraints and
* recommendations.
* <ul>
* <li> There can only be one package declaration as noted in JSR
* 175, section III, "Annotations". </li>
* <li> JSR 175 recommends package-info.java for package level
* annotations. JAXB Providers that follow this recommendation
* will allow the package level annotations to be defined in
* package-info.java.
* </ul>
* <p>
*
* <p><b>Example 1:</b> Customize name of XML namespace to which
* package is mapped.</p>
*
* <pre>
* &#64;javax.xml.bind.annotation.XmlSchema (
* namespace = "http://www.example.com/MYPO1"
* )
*
* &lt;!-- XML Schema fragment -->
* &lt;schema
* xmlns=...
* xmlns:po=....
* targetNamespace="http://www.example.com/MYPO1"
* >
* &lt;!-- prefixes generated by default are implementation
* depedenent -->
* </pre>
*
* <p><b>Example 2:</b> Customize namespace prefix, namespace URI
* mapping</p>
*
* <pre>
* // Package level annotation
* &#64;javax.xml.bind.annotation.XmlSchema (
* xmlns = {
* &#64;javax.xml.bind.annotation.XmlNs(prefix = "po",
* namespaceURI="http://www.example.com/myPO1"),
*
* &#64;javax.xml.bind.annotation.XmlNs(prefix="xs",
* namespaceURI="http://www.w3.org/2001/XMLSchema")
* )
* )
*
* &lt;!-- XML Schema fragment -->
* &lt;schema
* xmlns:xs="http://www.w3.org/2001/XMLSchema"
* xmlns:po="http://www.example.com/PO1"
* targetNamespace="http://www.example.com/PO1">
*
* </pre>
*
* <p><b>Example 3:</b> Customize elementFormDefault</p>
* <pre>
* &#64;javax.xml.bind.annotation.XmlSchema (
* elementFormDefault=XmlNsForm.UNQUALIFIED
* ...
* )
*
* &lt;!-- XML Schema fragment -->
* &lt;schema
* xmlns="http://www.w3.org/2001/XMLSchema"
* xmlns:po="http://www.example.com/PO1"
* elementFormDefault="unqualified">
*
* </pre>
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target(PACKAGE)
public @interface XmlSchema {
/**
* Customize the namespace URI, prefix associations. By default,
* the namespace prefixes for a XML namespace are generated by a
* JAXB Provider in an implementation dependent way.
*/
XmlNs[] xmlns() default {};
/**
* Name of the XML namespace.
*/
String namespace() default "";
/**
* Namespace qualification for elements. By default, element
* default attribute will be absent from the XML Schema fragment.
*/
XmlNsForm elementFormDefault() default XmlNsForm.UNSET;
/**
* Namespace qualification for attributes. By default,
* attributesFormDefault will be absent from the XML Schema fragment.
*/
XmlNsForm attributeFormDefault() default XmlNsForm.UNSET;
/**
* Indicates that this namespace (specified by {@link #namespace()})
* has a schema already available exeternally, available at this location.
*
* <p>
* This instructs the JAXB schema generators to simply refer to
* the pointed schema, as opposed to generating components into the schema.
* This schema is assumed to match what would be otherwise produced
* by the schema generator (same element names, same type names...)
*
* <p>
* This feature is intended to be used when a set of the Java classes
* is originally generated from an existing schema, hand-written to
* match externally defined schema, or the generated schema is modified
* manually.
*
* <p>
* Value could be any absolute URI, like <tt>http://example.org/some.xsd</tt>.
* It is also possible to specify the empty string, to indicate
* that the schema is externally available but the location is
* unspecified (and thus it's the responsibility of the reader of the generate
* schema to locate it.) Finally, the default value of this property
* <tt>"##generate"</tt> indicates that the schema generator is going
* to generate components for this namespace (as it did in JAXB 2.0.)
*
* <p>
* Multiple {@link XmlSchema} annotations on multiple packages are allowed
* to govern the same {@link #namespace()}. In such case, all of them
* must have the same {@link #location()} values.
*
*
* <h3>Note to implementor</h3>
* <p>
* More precisely, the value must be either <tt>""</tt>, <tt>"##generate"</tt>, or
* <a href="http://www.w3.org/TR/xmlschema-2/#anyURI">
* a valid lexical representation of <tt>xs:anyURI</tt></a> that begins
* with <tt>&lt;scheme>:</tt>.
*
* <p>
* A schema generator is expected to generate a corresponding
* <tt>&lt;xs:import namespace="..." schemaLocation="..."/></tt> (or
* no <tt>schemaLocation</tt> attribute at all if the empty string is specified.)
* However, the schema generator is allowed to use a different value in
* the <tt>schemaLocation</tt> attribute (including not generating
* such attribute), for example so that the user can specify a local
* copy of the resource through the command line interface.
*
* @since JAXB2.1
*/
String location() default NO_LOCATION;
/**
* The default value of the {@link #location()} attribute,
* which indicates that the schema generator will generate
* components in this namespace.
*/
// the actual value is chosen because ## is not a valid
// sequence in xs:anyURI.
static final String NO_LOCATION = "##generate";
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Maps a Java type to a simple schema built-in type.
*
* <p> <b>Usage</b> </p>
* <p>
* <tt>@XmlSchemaType</tt> annotation can be used with the following program
* elements:
* <ul>
* <li> a JavaBean property </li>
* <li> field </li>
* <li> package</li>
* </ul>
*
* <p> <tt>@XmlSchemaType</tt> annotation defined for Java type
* applies to all references to the Java type from a property/field.
* A <tt>@XmlSchemaType</tt> annotation specified on the
* property/field overrides the <tt>@XmlSchemaType</tt> annotation
* specified at the package level.
*
* <p> This annotation can be used with the following annotations:
* {@link XmlElement}, {@link XmlAttribute}.
* <p>
* <b>Example 1: </b> Customize mapping of XMLGregorianCalendar on the
* field.
*
* <pre>
* //Example: Code fragment
* public class USPrice {
* &#64;XmlElement
* &#64;XmlSchemaType(name="date")
* public XMLGregorianCalendar date;
* }
*
* &lt;!-- Example: Local XML Schema element -->
* &lt;xs:complexType name="USPrice"/>
* &lt;xs:sequence>
* &lt;xs:element name="date" type="xs:date"/>
* &lt;/sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p> <b> Example 2: </b> Customize mapping of XMLGregorianCalendar at package
* level </p>
* <pre>
* package foo;
* &#64;javax.xml.bind.annotation.XmlSchemaType(
* name="date", type=javax.xml.datatype.XMLGregorianCalendar.class)
* }
* </pre>
*
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD,METHOD,PACKAGE})
public @interface XmlSchemaType {
String name();
String namespace() default "http://www.w3.org/2001/XMLSchema";
/**
* If this annotation is used at the package level, then value of
* the type() must be specified.
*/
Class type() default DEFAULT.class;
/**
* Used in {@link XmlSchemaType#type()} to
* signal that the type be inferred from the signature
* of the property.
*/
static final class DEFAULT {}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.PACKAGE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* <p>
* A container for multiple @{@link XmlSchemaType} annotations.
*
* <p> Multiple annotations of the same type are not allowed on a program
* element. This annotation therefore serves as a container annotation
* for multiple &#64;XmlSchemaType annotations as follows:
*
* <pre>
* &#64;XmlSchemaTypes({ @XmlSchemaType(...), @XmlSchemaType(...) })
* </pre>
* <p>The <tt>@XmlSchemaTypes</tt> annnotation can be used to
* define {@link XmlSchemaType} for different types at the
* package level.
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @see XmlSchemaType
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({PACKAGE})
public @interface XmlSchemaTypes {
/**
* Collection of @{@link XmlSchemaType} annotations
*/
XmlSchemaType[] value();
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import javax.xml.bind.JAXBContext;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* Instructs JAXB to also bind other classes when binding this class.
*
* <p>
* Java makes it impractical/impossible to list all sub-classes of
* a given class. This often gets in a way of JAXB users, as it JAXB
* cannot automatically list up the classes that need to be known
* to {@link JAXBContext}.
*
* <p>
* For example, with the following class definitions:
*
* <pre>
* class Animal {}
* class Dog extends Animal {}
* class Cat extends Animal {}
* </pre>
*
* <p>
* The user would be required to create {@link JAXBContext} as
* <tt>JAXBContext.newInstance(Dog.class,Cat.class)</tt>
* (<tt>Animal</tt> will be automatically picked up since <tt>Dog</tt>
* and <tt>Cat</tt> refers to it.)
*
* <p>
* {@link XmlSeeAlso} annotation would allow you to write:
* <pre>
* &#64;XmlSeeAlso({Dog.class,Cat.class})
* class Animal {}
* class Dog extends Animal {}
* class Cat extends Animal {}
* </pre>
*
* <p>
* This would allow you to do <tt>JAXBContext.newInstance(Animal.class)</tt>.
* By the help of this annotation, JAXB implementations will be able to
* correctly bind <tt>Dog</tt> and <tt>Cat</tt>.
*
* @author Kohsuke Kawaguchi
* @since JAXB2.1
*/
@Target({ElementType.TYPE})
@Retention(RUNTIME)
public @interface XmlSeeAlso {
Class[] value();
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p>
* Prevents the mapping of a JavaBean property/type to XML representation.
* <p>
* The <tt>@XmlTransient</tt> annotation is useful for resolving name
* collisions between a JavaBean property name and a field name or
* preventing the mapping of a field/property. A name collision can
* occur when the decapitalized JavaBean property name and a field
* name are the same. If the JavaBean property refers to the field,
* then the name collision can be resolved by preventing the
* mapping of either the field or the JavaBean property using the
* <tt>@XmlTransient</tt> annotation.
*
* <p>
* When placed on a class, it indicates that the class shouldn't be mapped
* to XML by itself. Properties on such class will be mapped to XML along
* with its derived classes, as if the class is inlined.
*
* <p><b>Usage</b></p>
* <p> The <tt>@XmlTransient</tt> annotation can be used with the following
* program elements:
* <ul>
* <li> a JavaBean property </li>
* <li> field </li>
* <li> class </li>
* </ul>
*
* <p><tt>@XmlTransient</tt>is mutually exclusive with all other
* JAXB defined annotations. </p>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <p><b>Example:</b> Resolve name collision between JavaBean property and
* field name </p>
*
* <pre>
* // Example: Code fragment
* public class USAddress {
*
* // The field name "name" collides with the property name
* // obtained by bean decapitalization of getName() below
* &#64;XmlTransient public String name;
*
* String getName() {..};
* String setName() {..};
* }
*
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="USAddress">
* &lt;xs:sequence>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD, TYPE})
public @interface XmlTransient {}

View File

@@ -0,0 +1,452 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* <p>
* Maps a class or an enum type to a XML Schema type.
*
* <p><b>Usage</b></p>
* <p> The <tt>@XmlType</tt> annnotation can be used with the following program
* elements:
* <ul>
* <li> a top level class </li>
* <li> an enum type </li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* <h3> Mapping a Class </h3>
* <p>
* A class maps to a XML Schema type. A class is a data container for
* values represented by properties and fields. A schema type is a
* data container for values represented by schema components within a
* schema type's content model (e.g. model groups, attributes etc).
* <p> To be mapped, a class must either have a public no-arg
* constructor or a static no-arg factory method. The static factory
* method can be specified in <tt>factoryMethod()</tt> and
* <tt>factoryClass()</tt> annotation elements. The static factory
* method or the no-arg constructor is used during unmarshalling to
* create an instance of this class. If both are present, the static
* factory method overrides the no-arg constructor.
* <p>
* A class maps to either a XML Schema complex type or a XML Schema simple
* type. The XML Schema type is derived based on the
* mapping of JavaBean properties and fields contained within the
* class. The schema type to which the class is mapped can either be
* named or anonymous. A class can be mapped to an anonymous schema
* type by annotating the class with <tt>&#64XmlType(name="")</tt>.
* <p>
* Either a global element, local element or a local attribute can be
* associated with an anonymous type as follows:
* <ul>
* <li><b>global element: </b> A global element of an anonymous
* type can be derived by annotating the class with @{@link
* XmlRootElement}. See Example 3 below. </li>
*
* <li><b>local element: </b> A JavaBean property that references
* a class annotated with @XmlType(name="") and is mapped to the
* element associated with the anonymous type. See Example 4
* below.</li>
*
* <li><b>attribute: </b> A JavaBean property that references
* a class annotated with @XmlType(name="") and is mapped to the
* attribute associated with the anonymous type. See Example 5 below. </li>
* </ul>
* <b> Mapping to XML Schema Complex Type </b>
* <ul>
* <li>If class is annotated with <tt>@XmlType(name="") </tt>, it
* is mapped to an anonymous type otherwise, the class name maps
* to a complex type name. The <tt>XmlName()</tt> annotation element
* can be used to customize the name.</li>
*
* <li> Properties and fields that are mapped to elements are mapped to a
* content model within a complex type. The annotation element
* <tt>propOrder()</tt> can be used to customize the content model to be
* <tt>xs:all</tt> or <tt>xs:sequence</tt>. It is used for specifying
* the order of XML elements in <tt>xs:sequence</tt>. </li>
*
* <li> Properties and fields can be mapped to attributes within the
* complex type. </li>
*
* <li> The targetnamespace of the XML Schema type can be customized
* using the annotation element <tt>namespace()</tt>. </li>
* </ul>
*
* <p>
* <b> Mapping class to XML Schema simple type </b>
* <p>
* A class can be mapped to a XML Schema simple type using the
* <tt>@XmlValue</tt> annotation. For additional details and examples,
* see @{@link XmlValue} annotation type.
* <p>
* The following table shows the mapping of the class to a XML Schema
* complex type or simple type. The notational symbols used in the table are:
* <ul>
* <li> -> : represents a mapping </li>
* <li> [x]+ : one or more occurances of x </li>
* <li> [ <tt>@XmlValue</tt> property ]: JavaBean property annotated with
* <tt>@XmlValue</tt></li>
* <li> X : don't care
* </ul>
* <blockquote>
* <table border="1" cellpadding="4" cellspacing="3">
* <tbody>
* <tr>
* <td><b>Target</b></td>
* <td><b>propOrder</b></td>
* <td><b>ClassBody</b></td>
* <td><b>ComplexType</b></td>
* <td><b>SimpleType</b></td>
* </tr>
*
* <tr valign="top">
* <td>Class</td>
* <td>{}</td>
* <td>[property]+ -> elements</td>
* <td>complexcontent<br>xs:all</td>
* <td> </td>
* </tr>
*
* <tr valign="top">
* <td>Class</td>
* <td>non empty</td>
* <td>[property]+ -> elements</td>
* <td>complexcontent<br>xs:sequence</td>
* <td> </td>
* </tr>
*
* <tr valign="top">
* <td>Class</td>
* <td>X</td>
* <td>no property -> element</td>
* <td>complexcontent<br>empty sequence</td>
* <td> </td>
* </tr>
*
* <tr valign="top">
* <td>Class</td>
* <td>X</td>
* <td>1 [ <tt>@XmlValue</tt> property] && <br> [property]+
* ->attributes</td>
* <td>simplecontent</td>
* <td> </td>
* </tr>
*
* <tr valign="top">
* <td>Class</td>
* <td>X</td>
* <td>1 [ <tt>@XmlValue</tt> property ]&& <br> no properties
* -> attribute</td>
* <td> </td>
* <td>simpletype</td>
* <td> </td>
* </tr>
* </tbody>
* </table>
* </blockquote>
*
* <h3> Mapping an enum type </h3>
*
* An enum type maps to a XML schema simple type with enumeration
* facets. The following annotation elements are ignored since they
* are not meaningful: <tt>propOrder()</tt> , <tt>factoryMethod()</tt> ,
* <tt>factoryClass()</tt> .
*
* <h3> Usage with other annotations </h3>
* <p> This annotation can be used with the following annotations:
* {@link XmlRootElement}, {@link XmlAccessorOrder}, {@link XmlAccessorType},
* {@link XmlEnum}. However, {@link
* XmlAccessorOrder} and {@link XmlAccessorType} are ignored when this
* annotation is used on an enum type.
*
* <p> <b> Example 1: </b> Map a class to a complex type with
* xs:sequence with a customized ordering of JavaBean properties.
* </p>
*
* <pre>
* &#64;XmlType(propOrder={"street", "city" , "state", "zip", "name" })
* public class USAddress {
* String getName() {..};
* void setName(String) {..};
*
* String getStreet() {..};
* void setStreet(String) {..};
*
* String getCity() {..};
* void setCity(String) {..};
*
* String getState() {..};
* void setState(String) {..};
*
* java.math.BigDecimal getZip() {..};
* void setZip(java.math.BigDecimal) {..};
* }
*
* &lt;!-- XML Schema mapping for USAddress -->
* &lt;xs:complexType name="USAddress">
* &lt;xs:sequence>
* &lt;xs:element name="street" type="xs:string"/>
* &lt;xs:element name="city" type="xs:string"/>
* &lt;xs:element name="state" type="xs:string"/>
* &lt;xs:element name="zip" type="xs:decimal"/>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;/xs:all>
* &lt;/xs:complexType>
* </pre>
* <p> <b> Example 2: </b> Map a class to a complex type with
* xs:all </p>
* <pre>
* &#64;XmlType(propOrder={})
* public class USAddress { ...}
*
* &lt;!-- XML Schema mapping for USAddress -->
* &lt;xs:complexType name="USAddress">
* &lt;xs:all>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;xs:element name="street" type="xs:string"/>
* &lt;xs:element name="city" type="xs:string"/>
* &lt;xs:element name="state" type="xs:string"/>
* &lt;xs:element name="zip" type="xs:decimal"/>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
*</pre>
* <p> <b> Example 3: </b> Map a class to a global element with an
* anonymous type.
* </p>
* <pre>
* &#64;XmlRootElement
* &#64;XmlType(name="")
* public class USAddress { ...}
*
* &lt;!-- XML Schema mapping for USAddress -->
* &lt;xs:element name="USAddress">
* &lt;xs:complexType>
* &lt;xs:sequence>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;xs:element name="street" type="xs:string"/>
* &lt;xs:element name="city" type="xs:string"/>
* &lt;xs:element name="state" type="xs:string"/>
* &lt;xs:element name="zip" type="xs:decimal"/>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* &lt;/xs:element>
* </pre>
*
* <p> <b> Example 4: </b> Map a property to a local element with
* anonmyous type.
* <pre>
* //Example: Code fragment
* public class Invoice {
* USAddress addr;
* ...
* }
*
* &#64;XmlType(name="")
* public class USAddress { ... }
* }
*
* &lt;!-- XML Schema mapping for USAddress -->
* &lt;xs:complexType name="Invoice">
* &lt;xs:sequence>
* &lt;xs:element name="addr">
* &lt;xs:complexType>
* &lt;xs:element name="name", type="xs:string"/>
* &lt;xs:element name="city", type="xs:string"/>
* &lt;xs:element name="city" type="xs:string"/>
* &lt;xs:element name="state" type="xs:string"/>
* &lt;xs:element name="zip" type="xs:decimal"/>
* &lt;/xs:complexType>
* ...
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p> <b> Example 5: </b> Map a property to an attribute with
* anonymous type.
*
* <pre>
*
* //Example: Code fragment
* public class Item {
* public String name;
* &#64;XmlAttribute
* public USPrice price;
* }
*
* // map class to anonymous simple type.
* &#64;XmlType(name="")
* public class USPrice {
* &#64;XmlValue
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example: XML Schema fragment -->
* &lt;xs:complexType name="Item">
* &lt;xs:sequence>
* &lt;xs:element name="name" type="xs:string"/>
* &lt;xs:attribute name="price">
* &lt;xs:simpleType>
* &lt;xs:restriction base="xs:decimal"/>
* &lt;/xs:simpleType>
* &lt;/xs:attribute>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* <p> <b> Example 6: </b> Define a factoryClass and factoryMethod
*
* <pre>
* &#64;XmlType(name="USAddressType", factoryClass=USAddressFactory.class,
* factoryMethod="getUSAddress")
* public class USAddress {
*
* private String city;
* private String name;
* private String state;
* private String street;
* private int zip;
*
* public USAddress(String name, String street, String city,
* String state, int zip) {
* this.name = name;
* this.street = street;
* this.city = city;
* this.state = state;
* this.zip = zip;
* }
* }
*
* public class USAddressFactory {
* public static USAddress getUSAddress(){
* return new USAddress("Mark Baker", "23 Elm St",
* "Dayton", "OH", 90952);
* }
*
* </pre>
*
* <p> <b> Example 7: </b> Define factoryMethod and use the default factoryClass
*
* <pre>
* &#64;XmlType(name="USAddressType", factoryMethod="getNewInstance")
* public class USAddress {
*
* private String city;
* private String name;
* private String state;
* private String street;
* private int zip;
*
* private USAddress() {}
*
* public static USAddress getNewInstance(){
* return new USAddress();
* }
* }
* </pre>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @see XmlElement
* @see XmlAttribute
* @see XmlValue
* @see XmlSchema
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({TYPE})
public @interface XmlType {
/**
* Name of the XML Schema type which the class is mapped.
*/
String name() default "##default" ;
/**
* Specifies the order for XML Schema elements when class is
* mapped to a XML Schema complex type.
*
* <p> Refer to the table for how the propOrder affects the
* mapping of class </p>
*
* <p> The propOrder is a list of names of JavaBean properties in
* the class. Each name in the list is the name of a Java
* identifier of the JavaBean property. The order in which
* JavaBean properties are listed is the order of XML Schema
* elements to which the JavaBean properties are mapped. </p>
* <p> All of the JavaBean properties being mapped to XML Schema elements
* must be listed.
* <p> A JavaBean property or field listed in propOrder must not
* be transient or annotated with <tt>@XmlTransient</tt>.
* <p> The default ordering of JavaBean properties is determined
* by @{@link XmlAccessorOrder}.
*/
String[] propOrder() default {""};
/**
* Name of the target namespace of the XML Schema type. By
* default, this is the target namespace to which the package
* containing the class is mapped.
*/
String namespace() default "##default" ;
/**
* Class containing a no-arg factory method for creating an
* instance of this class. The default is this class.
*
* <p>If <tt>factoryClass</tt> is DEFAULT.class and
* <tt>factoryMethod</tt> is "", then there is no static factory
* method.
*
* <p>If <tt>factoryClass</tt> is DEFAULT.class and
* <tt>factoryMethod</tt> is not "", then
* <tt>factoryMethod</tt> is the name of a static factory method
* in this class.
*
* <p>If <tt>factoryClass</tt> is not DEFAULT.class, then
* <tt>factoryMethod</tt> must not be "" and must be the name of
* a static factory method specified in <tt>factoryClass</tt>.
*/
Class factoryClass() default DEFAULT.class;
/**
* Used in {@link XmlType#factoryClass()} to
* signal that either factory mehod is not used or
* that it's in the class with this {@link XmlType} itself.
*/
static final class DEFAULT {}
/**
* Name of a no-arg factory method in the class specified in
* <tt>factoryClass</tt> factoryClass().
*
*/
String factoryMethod() default "";
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* <p>
* Enables mapping a class to a XML Schema complex type with a
* simpleContent or a XML Schema simple type.
* </p>
*
* <p>
* <b> Usage: </b>
* <p>
* The <tt>@XmlValue</tt> annotation can be used with the following program
* elements:
* <ul>
* <li> a JavaBean property.</li>
* <li> non static, non transient field.</li>
* </ul>
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* The usage is subject to the following usage constraints:
* <ul>
* <li>At most one field or property can be annotated with the
* <tt>@XmlValue</tt> annotation. </li>
*
* <li><tt>@XmlValue</tt> can be used with the following
* annotations: {@link XmlList}. However this is redundant since
* {@link XmlList} maps a type to a simple schema type that derives by
* list just as {@link XmlValue} would. </li>
*
* <li>If the type of the field or property is a collection type,
* then the collection item type must map to a simple schema
* type. </li>
*
* <li>If the type of the field or property is not a collection
* type, then the type must map to a XML Schema simple type. </li>
*
* </ul>
* </p>
* <p>
* If the annotated JavaBean property is the sole class member being
* mapped to XML Schema construct, then the class is mapped to a
* simple type.
*
* If there are additional JavaBean properties (other than the
* JavaBean property annotated with <tt>@XmlValue</tt> annotation)
* that are mapped to XML attributes, then the class is mapped to a
* complex type with simpleContent.
* </p>
*
* <p> <b> Example 1: </b> Map a class to XML Schema simpleType</p>
*
* <pre>
*
* // Example 1: Code fragment
* public class USPrice {
* &#64;XmlValue
* public java.math.BigDecimal price;
* }
*
* &lt;!-- Example 1: XML Schema fragment -->
* &lt;xs:simpleType name="USPrice">
* &lt;xs:restriction base="xs:decimal"/>
* &lt;/xs:simpleType>
*
* </pre>
*
* <p><b> Example 2: </b> Map a class to XML Schema complexType with
* with simpleContent.</p>
*
* <pre>
*
* // Example 2: Code fragment
* public class InternationalPrice {
* &#64;XmlValue
* public java.math.BigDecimal price;
*
* &#64;XmlAttribute
* public String currency;
* }
*
* &lt;!-- Example 2: XML Schema fragment -->
* &lt;xs:complexType name="InternationalPrice">
* &lt;xs:simpleContent>
* &lt;xs:extension base="xs:decimal">
* &lt;xs:attribute name="currency" type="xs:string"/>
* &lt;/xs:extension>
* &lt;/xs:simpleContent>
* &lt;/xs:complexType>
*
* </pre>
* </p>
*
* @author Sekhar Vajjhala, Sun Microsystems, Inc.
* @see XmlType
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlValue {}

View File

@@ -0,0 +1,119 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
/**
* Built-in {@link XmlAdapter} to handle <tt>xs:token</tt> and its derived types.
*
* <p>
* This adapter removes leading and trailing whitespaces, then truncate any
* sequnce of tab, CR, LF, and SP by a single whitespace character ' '.
*
* @author Kohsuke Kawaguchi
* @since JAXB 2.0
*/
public class CollapsedStringAdapter extends XmlAdapter<String,String> {
/**
* Removes leading and trailing whitespaces of the string
* given as the parameter, then truncate any
* sequnce of tab, CR, LF, and SP by a single whitespace character ' '.
*/
public String unmarshal(String text) {
if(text==null) return null; // be defensive
int len = text.length();
// most of the texts are already in the collapsed form.
// so look for the first whitespace in the hope that we will
// never see it.
int s=0;
while(s<len) {
if(isWhiteSpace(text.charAt(s)))
break;
s++;
}
if(s==len)
// the input happens to be already collapsed.
return text;
// we now know that the input contains spaces.
// let's sit down and do the collapsing normally.
StringBuilder result = new StringBuilder(len /*allocate enough size to avoid re-allocation*/ );
if(s!=0) {
for( int i=0; i<s; i++ )
result.append(text.charAt(i));
result.append(' ');
}
boolean inStripMode = true;
for (int i = s+1; i < len; i++) {
char ch = text.charAt(i);
boolean b = isWhiteSpace(ch);
if (inStripMode && b)
continue; // skip this character
inStripMode = b;
if (inStripMode)
result.append(' ');
else
result.append(ch);
}
// remove trailing whitespaces
len = result.length();
if (len > 0 && result.charAt(len - 1) == ' ')
result.setLength(len - 1);
// whitespaces are already collapsed,
// so all we have to do is to remove the last one character
// if it's a whitespace.
return result.toString();
}
/**
* No-op.
*
* Just return the same string given as the parameter.
*/
public String marshal(String s) {
return s;
}
/** returns true if the specified char is a white space character. */
protected static boolean isWhiteSpace(char ch) {
// most of the characters are non-control characters.
// so check that first to quickly return false for most of the cases.
if( ch>0x20 ) return false;
// other than we have to do four comparisons.
return ch == 0x9 || ch == 0xA || ch == 0xD || ch == 0x20;
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
import javax.xml.bind.DatatypeConverter;
/**
* {@link XmlAdapter} for <tt>xs:hexBinary</tt>.
*
* <p>
* This {@link XmlAdapter} binds <tt>byte[]</tt> to the hexBinary representation in XML.
*
* @author Kohsuke Kawaguchi
* @since JAXB 2.0
*/
public final class HexBinaryAdapter extends XmlAdapter<String,byte[]> {
public byte[] unmarshal(String s) {
if(s==null) return null;
return DatatypeConverter.parseHexBinary(s);
}
public String marshal(byte[] bytes) {
if(bytes==null) return null;
return DatatypeConverter.printHexBinary(bytes);
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
/**
* {@link XmlAdapter} to handle <tt>xs:normalizedString</tt>.
*
* <p>
* Replaces any tab, CR, and LF by a whitespace character ' ',
* as specified in <a href="http://www.w3.org/TR/xmlschema-2/#rf-whiteSpace">the whitespace facet 'replace'</a>
*
* @author Kohsuke Kawaguchi, Martin Grebac
* @since JAXB 2.0
*/
public final class NormalizedStringAdapter extends XmlAdapter<String,String> {
/**
* Replace any tab, CR, and LF by a whitespace character ' ',
* as specified in <a href="http://www.w3.org/TR/xmlschema-2/#rf-whiteSpace">the whitespace facet 'replace'</a>
*/
public String unmarshal(String text) {
if(text==null) return null; // be defensive
int i=text.length()-1;
// look for the first whitespace char.
while( i>=0 && !isWhiteSpaceExceptSpace(text.charAt(i)) )
i--;
if( i<0 )
// no such whitespace. replace(text)==text.
return text;
// we now know that we need to modify the text.
// allocate a char array to do it.
char[] buf = text.toCharArray();
buf[i--] = ' ';
for( ; i>=0; i-- )
if( isWhiteSpaceExceptSpace(buf[i]))
buf[i] = ' ';
return new String(buf);
}
/**
* No-op.
*
* Just return the same string given as the parameter.
*/
public String marshal(String s) {
return s;
}
/**
* Returns true if the specified char is a white space character
* but not 0x20.
*/
protected static boolean isWhiteSpaceExceptSpace(char ch) {
// most of the characters are non-control characters.
// so check that first to quickly return false for most of the cases.
if( ch>=0x20 ) return false;
// other than we have to do four comparisons.
return ch == 0x9 || ch == 0xA || ch == 0xD;
}
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
/**
* Adapts a Java type for custom marshaling.
*
* <p> <b> Usage: </b> </p>
*
* <p>
* Some Java types do not map naturally to a XML representation, for
* example <tt>HashMap</tt> or other non JavaBean classes. Conversely,
* a XML repsentation may map to a Java type but an application may
* choose to accesss the XML representation using another Java
* type. For example, the schema to Java binding rules bind
* xs:DateTime by default to XmlGregorianCalendar. But an application
* may desire to bind xs:DateTime to a custom type,
* MyXmlGregorianCalendar, for example. In both cases, there is a
* mismatch between <i> bound type </i>, used by an application to
* access XML content and the <i> value type</i>, that is mapped to an
* XML representation.
*
* <p>
* This abstract class defines methods for adapting a bound type to a value
* type or vice versa. The methods are invoked by the JAXB binding
* framework during marshaling and unmarshalling:
*
* <ul>
* <li> <b> XmlAdapter.marshal(...): </b> During marshalling, JAXB
* binding framework invokes XmlAdapter.marshal(..) to adapt a
* bound type to value type, which is then marshaled to XML
* representation. </li>
*
* <li> <b> XmlAdapter.unmarshal(...): </b> During unmarshalling,
* JAXB binding framework first unmarshals XML representation
* to a value type and then invokes XmlAdapter.unmarshal(..) to
* adapt the value type to a bound type. </li>
* </ul>
*
* Writing an adapter therefore involves the following steps:
*
* <ul>
* <li> Write an adapter that implements this abstract class. </li>
* <li> Install the adapter using the annotation {@link
* XmlJavaTypeAdapter} </li>
* </ul>
*
* <p><b>Example:</b> Customized mapping of <tt>HashMap</tt></p>
* <p> The following example illustrates the use of
* <tt>&#64;XmlAdapter</tt> and <tt>&#64;XmlJavaTypeAdapter</tt> to
* customize the mapping of a <tt>HashMap</tt>.
*
* <p> <b> Step 1: </b> Determine the desired XML representation for HashMap.
*
* <pre>
* &lt;hashmap>
* &lt;entry key="id123">this is a value&lt;/entry>
* &lt;entry key="id312">this is another value&lt;/entry>
* ...
* &lt;/hashmap>
* </pre>
*
* <p> <b> Step 2: </b> Determine the schema definition that the
* desired XML representation shown above should follow.
*
* <pre>
*
* &lt;xs:complexType name="myHashMapType">
* &lt;xs:sequence>
* &lt;xs:element name="entry" type="myHashMapEntryType"
* minOccurs = "0" maxOccurs="unbounded"/>
* &lt;/xs:sequence>
* &lt;/xs:complexType>
*
* &lt;xs:complexType name="myHashMapEntryType">
* &lt;xs:simpleContent>
* &lt;xs:extension base="xs:string">
* &lt;xs:attribute name="key" type="xs:int"/>
* &lt;/xs:extension>
* &lt;/xs:simpleContent>
* &lt;/xs:complexType>
*
* </pre>
*
* <p> <b> Step 3: </b> Write value types that can generate the above
* schema definition.
*
* <pre>
* public class MyHashMapType {
* List&lt;MyHashMapEntryType> entry;
* }
*
* public class MyHashMapEntryType {
* &#64;XmlAttribute
* public Integer key;
*
* &#64;XmlValue
* public String value;
* }
* </pre>
*
* <p> <b> Step 4: </b> Write the adapter that adapts the value type,
* MyHashMapType to a bound type, HashMap, used by the application.
*
* <pre>
* public final class MyHashMapAdapter extends
* XmlAdapter&lt;MyHashMapType,HashMap> { ... }
*
* </pre>
*
* <p> <b> Step 5: </b> Use the adapter.
*
* <pre>
* public class Foo {
* &#64;XmlJavaTypeAdapter(MyHashMapAdapter.class)
* HashMap hashmap;
* ...
* }
* </pre>
*
* The above code fragment will map to the following schema:
*
* <pre>
* &lt;xs:complexType name="Foo">
* &lt;xs:sequence>
* &lt;xs:element name="hashmap" type="myHashMapType"
* &lt;/xs:sequence>
* &lt;/xs:complexType>
* </pre>
*
* @param <BoundType>
* The type that JAXB doesn't know how to handle. An adapter is written
* to allow this type to be used as an in-memory representation through
* the <tt>ValueType</tt>.
* @param <ValueType>
* The type that JAXB knows how to handle out of the box.
*
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems Inc.</li> <li> Kohsuke Kawaguchi, Sun Microsystems Inc.</li></ul>
* @see XmlJavaTypeAdapter
* @since JAXB 2.0
*/
public abstract class XmlAdapter<ValueType,BoundType> {
/**
* Do-nothing constructor for the derived classes.
*/
protected XmlAdapter() {}
/**
* Convert a value type to a bound type.
*
* @param v
* The value to be converted. Can be null.
* @throws Exception
* if there's an error during the conversion. The caller is responsible for
* reporting the error to the user through {@link javax.xml.bind.ValidationEventHandler}.
*/
public abstract BoundType unmarshal(ValueType v) throws Exception;
/**
* Convert a bound type to a value type.
*
* @param v
* The value to be convereted. Can be null.
* @throws Exception
* if there's an error during the conversion. The caller is responsible for
* reporting the error to the user through {@link javax.xml.bind.ValidationEventHandler}.
*/
public abstract ValueType marshal(BoundType v) throws Exception;
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaTypes;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.PACKAGE;
/**
* Use an adapter that implements {@link XmlAdapter} for custom marshaling.
*
* <p> <b> Usage: </b> </p>
*
* <p> The <tt>@XmlJavaTypeAdapter</tt> annotation can be used with the
* following program elements:
* <ul>
* <li> a JavaBean property </li>
* <li> field </li>
* <li> parameter </li>
* <li> package </li>
* <li> from within {@link XmlJavaTypeAdapters} </li>
* </ul>
*
* <p> When <tt>@XmlJavaTypeAdapter</tt> annotation is defined on a
* class, it applies to all references to the class.
* <p> When <tt>@XmlJavaTypeAdapter</tt> annotation is defined at the
* package level it applies to all references from within the package
* to <tt>@XmlJavaTypeAdapter.type()</tt>.
* <p> When <tt>@XmlJavaTypeAdapter</tt> annotation is defined on the
* field, property or parameter, then the annotation applies to the
* field, property or the parameter only.
* <p> A <tt>@XmlJavaTypeAdapter</tt> annotation on a field, property
* or parameter overrides the <tt>@XmlJavaTypeAdapter</tt> annotation
* associated with the class being referenced by the field, property
* or parameter.
* <p> A <tt>@XmlJavaTypeAdapter</tt> annotation on a class overrides
* the <tt>@XmlJavaTypeAdapter</tt> annotation specified at the
* package level for that class.
*
* <p>This annotation can be used with the following other annotations:
* {@link XmlElement}, {@link XmlAttribute}, {@link XmlElementRef},
* {@link XmlElementRefs}, {@link XmlAnyElement}. This can also be
* used at the package level with the following annotations:
* {@link XmlAccessorType}, {@link XmlSchema}, {@link XmlSchemaType},
* {@link XmlSchemaTypes}.
*
* <p><b> Example: </b> See example in {@link XmlAdapter}
*
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems Inc.</li> <li> Kohsuke Kawaguchi, Sun Microsystems Inc.</li></ul>
* @since JAXB2.0
* @see XmlAdapter
*/
@Retention(RUNTIME) @Target({PACKAGE,FIELD,METHOD,TYPE,PARAMETER})
public @interface XmlJavaTypeAdapter {
/**
* Points to the class that converts a value type to a bound type or vice versa.
* See {@link XmlAdapter} for more details.
*/
Class<? extends XmlAdapter> value();
/**
* If this annotation is used at the package level, then value of
* the type() must be specified.
*/
Class type() default DEFAULT.class;
/**
* Used in {@link XmlJavaTypeAdapter#type()} to
* signal that the type be inferred from the signature
* of the field, property, parameter or the class.
*/
static final class DEFAULT {}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.annotation.adapters;
import static java.lang.annotation.ElementType.PACKAGE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* <p>
* A container for multiple @{@link XmlJavaTypeAdapter} annotations.
*
* <p> Multiple annotations of the same type are not allowed on a program
* element. This annotation therefore serves as a container annotation
* for multiple &#64;XmlJavaTypeAdapter as follows:
*
* <pre>
* &#64;XmlJavaTypeAdapters ({ @XmlJavaTypeAdapter(...),@XmlJavaTypeAdapter(...) })
* </pre>
*
* <p>The <tt>@XmlJavaTypeAdapters</tt> annnotation is useful for
* defining {@link XmlJavaTypeAdapter} annotations for different types
* at the package level.
*
* <p>See "Package Specification" in javax.xml.bind.package javadoc for
* additional common information.</p>
*
* @author <ul><li>Sekhar Vajjhala, Sun Microsystems, Inc.</li></ul>
* @see XmlJavaTypeAdapter
* @since JAXB2.0
*/
@Retention(RUNTIME) @Target({PACKAGE})
public @interface XmlJavaTypeAdapters {
/**
* Collection of @{@link XmlJavaTypeAdapter} annotations
*/
XmlJavaTypeAdapter[] value();
}

View File

@@ -0,0 +1,200 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.attachment;
import javax.activation.DataHandler;
import javax.xml.bind.Marshaller;
/**
* <p>Enable JAXB marshalling to optimize storage of binary data.</p>
*
* <p>This API enables an efficient cooperative creation of optimized
* binary data formats between a JAXB marshalling process and a MIME-based package
* processor. A JAXB implementation marshals the root body of a MIME-based package,
* delegating the creation of referenceable MIME parts to
* the MIME-based package processor that implements this abstraction.</p>
*
* <p>XOP processing is enabled when {@link #isXOPPackage()} is true.
* See {@link #addMtomAttachment(DataHandler, String, String)} for details.
* </p>
*
* <p>WS-I Attachment Profile 1.0 is supported by
* {@link #addSwaRefAttachment(DataHandler)} being called by the
* marshaller for each JAXB property related to
* {http://ws-i.org/profiles/basic/1.1/xsd}swaRef.</p>
*
*
* @author Marc Hadley
* @author Kohsuke Kawaguchi
* @author Joseph Fialli
* @since JAXB 2.0
*
* @see Marshaller#setAttachmentMarshaller(AttachmentMarshaller)
*
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @see <a href="http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html">WS-I Attachments Profile Version 1.0.</a>
*/
public abstract class AttachmentMarshaller {
/**
* <p>Consider MIME content <code>data</code> for optimized binary storage as an attachment.
*
* <p>
* This method is called by JAXB marshal process when {@link #isXOPPackage()} is
* <code>true</code>, for each element whose datatype is "base64Binary", as described in
* Step 3 in
* <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#creating_xop_packages">Creating XOP Packages</a>.
*
* <p>
* The method implementor determines whether <code>data</code> shall be attached separately
* or inlined as base64Binary data. If the implementation chooses to optimize the storage
* of the binary data as a MIME part, it is responsible for attaching <code>data</code> to the
* MIME-based package, and then assigning an unique content-id, cid, that identifies
* the MIME part within the MIME message. This method returns the cid,
* which enables the JAXB marshaller to marshal a XOP element that refers to that cid in place
* of marshalling the binary data. When the method returns null, the JAXB marshaller
* inlines <code>data</code> as base64binary data.
*
* <p>
* The caller of this method is required to meet the following constraint.
* If the element infoset item containing <code>data</code> has the attribute
* <code>xmime:contentType</code> or if the JAXB property/field representing
* <code>data</code>is annotated with a known MIME type,
* <code>data.getContentType()</code> should be set to that MIME type.
*
* <p>
* The <code>elementNamespace</code> and <code>elementLocalName</code>
* parameters provide the
* context that contains the binary data. This information could
* be used by the MIME-based package processor to determine if the
* binary data should be inlined or optimized as an attachment.
*
* @param data
* represents the data to be attached. Must be non-null.
* @param elementNamespace
* the namespace URI of the element that encloses the base64Binary data.
* Can be empty but never null.
* @param elementLocalName
* The local name of the element. Always a non-null valid string.
*
* @return
* a valid content-id URI (see <a href="http://www.w3.org/TR/xop10/#RFC2387">RFC 2387</a>) that identifies the attachment containing <code>data</code>.
* Otherwise, null if the attachment was not added and should instead be inlined in the message.
*
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @see <a href="http://www.w3.org/TR/xml-media-types/">Describing Media Content of Binary Data in XML</a>
*/
public abstract String addMtomAttachment(DataHandler data, String elementNamespace, String elementLocalName);
/**
* <p>Consider binary <code>data</code> for optimized binary storage as an attachment.
*
* <p>Since content type is not known, the attachment's MIME content type must be set to "application/octet-stream".</p>
*
* <p>
* The <code>elementNamespace</code> and <code>elementLocalName</code>
* parameters provide the
* context that contains the binary data. This information could
* be used by the MIME-based package processor to determine if the
* binary data should be inlined or optimized as an attachment.
*
* @param data
* represents the data to be attached. Must be non-null. The actual data region is
* specified by <tt>(data,offset,length)</tt> tuple.
*
* @param offset
* The offset within the array of the first byte to be read;
* must be non-negative and no larger than array.length
*
* @param length
* The number of bytes to be read from the given array;
* must be non-negative and no larger than array.length
*
* @param mimeType
* If the data has an associated MIME type known to JAXB, that is passed
* as this parameter. If none is known, "application/octet-stream".
* This parameter may never be null.
*
* @param elementNamespace
* the namespace URI of the element that encloses the base64Binary data.
* Can be empty but never null.
*
* @param elementLocalName
* The local name of the element. Always a non-null valid string.
*
* @return content-id URI, cid, to the attachment containing
* <code>data</code> or null if data should be inlined.
*
* @see #addMtomAttachment(DataHandler, String, String)
*/
public abstract String addMtomAttachment(byte[] data, int offset, int length, String mimeType, String elementNamespace, String elementLocalName);
/**
* <p>Read-only property that returns true if JAXB marshaller should enable XOP creation.</p>
*
* <p>This value must not change during the marshalling process. When this
* value is true, the <code>addMtomAttachment(...)</code> method
* is invoked when the appropriate binary datatypes are encountered by
* the marshal process.</p>
*
* <p>Marshaller.marshal() must throw IllegalStateException if this value is <code>true</code>
* and the XML content to be marshalled violates Step 1 in
* <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#creating_xop_packages">Creating XOP Pacakges</a>
* http://www.w3.org/TR/2005/REC-xop10-20050125/#creating_xop_packages.
* <i>"Ensure the Original XML Infoset contains no element information item with a
* [namespace name] of "http://www.w3.org/2004/08/xop/include" and a [local name] of Include"</i>
*
* <p>When this method returns true and during the marshal process
* at least one call to <code>addMtomAttachment(...)</code> returns
* a content-id, the MIME-based package processor must label the
* root part with the application/xop+xml media type as described in
* Step 5 of
* <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#creating_xop_packages">Creating XOP Pacakges</a>.<p>
*
* @return true when MIME context is a XOP Package.
*/
public boolean isXOPPackage() { return false; }
/**
* <p>Add MIME <code>data</code> as an attachment and return attachment's content-id, cid.</p>
*
* <p>
* This method is called by JAXB marshal process for each element/attribute typed as
* {http://ws-i.org/profiles/basic/1.1/xsd}swaRef. The MIME-based package processor
* implementing this method is responsible for attaching the specified data to a
* MIME attachment, and generating a content-id, cid, that uniquely identifies the attachment
* within the MIME-based package.
*
* <p>Caller inserts the returned content-id, cid, into the XML content being marshalled.</p>
*
* @param data
* represents the data to be attached. Must be non-null.
* @return
* must be a valid URI used as cid. Must satisfy Conformance Requirement R2928 from
* <a href="http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html#Referencing_Attachments_from_the_SOAP_Envelope">WS-I Attachments Profile Version 1.0.</a>
*/
public abstract String addSwaRefAttachment(DataHandler data);
}

View File

@@ -0,0 +1,139 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.attachment;
import javax.activation.DataHandler;
/**
* <p>Enables JAXB unmarshalling of a root document containing optimized binary data formats.</p>
*
* <p>This API enables an efficient cooperative processing of optimized
* binary data formats between a JAXB 2.0 implementation and MIME-based package
* processor (MTOM/XOP and WS-I AP 1.0). JAXB unmarshals the body of a package, delegating the
* understanding of the packaging format being used to a MIME-based
* package processor that implements this abstract class.</p>
*
* <p>This abstract class identifies if a package requires XOP processing, {@link #isXOPPackage()} and provides retrieval of binary content stored as attachments by content-id.</p>
*
* <h2>Identifying the content-id, cid, to pass to <code>getAttachment*(String cid)</code></h2>
* <ul>
* <li>
* For XOP processing, the infoset representation of the cid is described
* in step 2a in
* <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#interpreting_xop_packages">Section 3.2 Interpreting XOP Packages</a>
* </li>
* <li>
* For WS-I AP 1.0, the cid is identified as an element or attribute of
* type <code>ref:swaRef </code> specified in
* <a href="http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html#Referencing_Attachments_from_the_SOAP_Envelope">Section 4.4 Referencing Attachments from the SOAP Envelope</a>
* </li>
* </ul>
*
* @author Marc Hadley
* @author Kohsuke Kawaguchi
* @author Joseph Fialli
*
* @since JAXB 2.0
*
* @see javax.xml.bind.Unmarshaller#setAttachmentUnmarshaller(AttachmentUnmarshaller)
*
* @see <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/">XML-binary Optimized Packaging</a>
* @see <a href="http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html">WS-I Attachments Profile Version 1.0.</a>
* @see <a href="http://www.w3.org/TR/xml-media-types/">Describing Media Content of Binary Data in XML</a>
*/
public abstract class AttachmentUnmarshaller {
/**
* <p>Lookup MIME content by content-id, <code>cid</code>, and return as a {@link DataHandler}.</p>
*
* <p>The returned <code>DataHandler</code> instance must be configured
* to meet the following required mapping constaint.
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2">
* Required Mappings between MIME and Java Types
* </tr>
* <tr>
* <th>MIME Type</th>
* <th>Java Type</th>
* </tr>
* <tr>
* <th><code>DataHandler.getContentType()</code></th>
* <th><code>instanceof DataHandler.getContent()</code></th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>image/gif</td>
* <td>java.awt.Image</td>
* </tr>
* <tr>
* <td>image/jpeg</td>
* <td>java.awt.Image</td>
* </tr>
* <tr>
* <td>text/xml or application/xml</td>
* <td>javax.xml.transform.Source</td>
* </tr>
* </tbody>
* </table>
* Note that it is allowable to support additional mappings.</p>
*
* @param cid It is expected to be a valid lexical form of the XML Schema
* <code>xs:anyURI</code> datatype. If <code>{@link #isXOPPackage()}
* ==true</code>, it must be a valid URI per the <code>cid:</code> URI scheme (see <a href="http://www.ietf.org/rfc/rfc2387.txt">RFC 2387</a>)
*
* @return
* a {@link DataHandler} that represents the MIME attachment.
*
* @throws IllegalArgumentException if the attachment for the given cid is not found.
*/
public abstract DataHandler getAttachmentAsDataHandler(String cid);
/**
* <p>Retrieve the attachment identified by content-id, <code>cid</code>, as a <tt>byte[]</tt></p>.
*
* @param cid It is expected to be a valid lexical form of the XML Schema
* <code>xs:anyURI</code> datatype. If <code>{@link #isXOPPackage()}
* ==true</code>, it must be a valid URI per the <code>cid:</code> URI scheme (see <a href="http://www.ietf.org/rfc/rfc2387.txt">RFC 2387</a>)
*
* @return byte[] representation of attachment identified by cid.
*
* @throws IllegalArgumentException if the attachment for the given cid is not found.
*/
public abstract byte[] getAttachmentAsByteArray(String cid);
/**
* <p>Read-only property that returns true if JAXB unmarshaller needs to perform XOP processing.</p>
*
* <p>This method returns <code>true</code> when the constraints specified
* in <a href="http://www.w3.org/TR/2005/REC-xop10-20050125/#identifying_xop_documents">Identifying XOP Documents</a> are met.
* This value must not change during the unmarshalling process.</p>
*
* @return true when MIME context is a XOP Document.
*/
public boolean isXOPPackage() { return false; }
}

View File

@@ -0,0 +1,495 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import java.io.UnsupportedEncodingException;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
// J2SE1.4 feature
// import java.nio.charset.Charset;
// import java.nio.charset.UnsupportedCharsetException;
/**
* Partial default <tt>Marshaller</tt> implementation.
*
* <p>
* This class provides a partial default implementation for the
* {@link javax.xml.bind.Marshaller} interface.
*
* <p>
* The only methods that a JAXB Provider has to implement are
* {@link Marshaller#marshal(Object, javax.xml.transform.Result) marshal(Object, javax.xml.transform.Result)},
* {@link Marshaller#marshal(Object, javax.xml.transform.Result) marshal(Object, javax.xml.stream.XMLStreamWriter)}, and
* {@link Marshaller#marshal(Object, javax.xml.transform.Result) marshal(Object, javax.xml.stream.XMLEventWriter)}.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.Marshaller
* @since JAXB1.0
*/
public abstract class AbstractMarshallerImpl implements Marshaller
{
/** handler that will be used to process errors and warnings during marshal */
private ValidationEventHandler eventHandler =
new DefaultValidationEventHandler();
//J2SE1.4 feature
//private Charset encoding = null;
/** store the value of the encoding property. */
private String encoding = "UTF-8";
/** store the value of the schemaLocation property. */
private String schemaLocation = null;
/** store the value of the noNamespaceSchemaLocation property. */
private String noNSSchemaLocation = null;
/** store the value of the formattedOutput property. */
private boolean formattedOutput = false;
/** store the value of the fragment property. */
private boolean fragment = false;
public final void marshal( Object obj, java.io.OutputStream os )
throws JAXBException {
checkNotNull( obj, "obj", os, "os" );
marshal( obj, new StreamResult(os) );
}
public void marshal(Object jaxbElement, File output) throws JAXBException {
checkNotNull(jaxbElement, "jaxbElement", output, "output" );
try {
OutputStream os = new BufferedOutputStream(new FileOutputStream(output));
try {
marshal( jaxbElement, new StreamResult(os) );
} finally {
os.close();
}
} catch (IOException e) {
throw new JAXBException(e);
}
}
public final void marshal( Object obj, java.io.Writer w )
throws JAXBException {
checkNotNull( obj, "obj", w, "writer" );
marshal( obj, new StreamResult(w) );
}
public final void marshal( Object obj, org.xml.sax.ContentHandler handler )
throws JAXBException {
checkNotNull( obj, "obj", handler, "handler" );
marshal( obj, new SAXResult(handler) );
}
public final void marshal( Object obj, org.w3c.dom.Node node )
throws JAXBException {
checkNotNull( obj, "obj", node, "node" );
marshal( obj, new DOMResult(node) );
}
/**
* By default, the getNode method is unsupported and throw
* an {@link java.lang.UnsupportedOperationException}.
*
* Implementations that choose to support this method must
* override this method.
*/
public org.w3c.dom.Node getNode( Object obj ) throws JAXBException {
checkNotNull( obj, "obj", Boolean.TRUE, "foo" );
throw new UnsupportedOperationException();
}
/**
* Convenience method for getting the current output encoding.
*
* @return the current encoding or "UTF-8" if it hasn't been set.
*/
protected String getEncoding() {
return encoding;
}
/**
* Convenience method for setting the output encoding.
*
* @param encoding a valid encoding as specified in the Marshaller class
* documentation
*/
protected void setEncoding( String encoding ) {
this.encoding = encoding;
}
/**
* Convenience method for getting the current schemaLocation.
*
* @return the current schemaLocation or null if it hasn't been set
*/
protected String getSchemaLocation() {
return schemaLocation;
}
/**
* Convenience method for setting the schemaLocation.
*
* @param location the schemaLocation value
*/
protected void setSchemaLocation( String location ) {
schemaLocation = location;
}
/**
* Convenience method for getting the current noNamespaceSchemaLocation.
*
* @return the current noNamespaceSchemaLocation or null if it hasn't
* been set
*/
protected String getNoNSSchemaLocation() {
return noNSSchemaLocation;
}
/**
* Convenience method for setting the noNamespaceSchemaLocation.
*
* @param location the noNamespaceSchemaLocation value
*/
protected void setNoNSSchemaLocation( String location ) {
noNSSchemaLocation = location;
}
/**
* Convenience method for getting the formatted output flag.
*
* @return the current value of the formatted output flag or false if
* it hasn't been set.
*/
protected boolean isFormattedOutput() {
return formattedOutput;
}
/**
* Convenience method for setting the formatted output flag.
*
* @param v value of the formatted output flag.
*/
protected void setFormattedOutput( boolean v ) {
formattedOutput = v;
}
/**
* Convenience method for getting the fragment flag.
*
* @return the current value of the fragment flag or false if
* it hasn't been set.
*/
protected boolean isFragment() {
return fragment;
}
/**
* Convenience method for setting the fragment flag.
*
* @param v value of the fragment flag.
*/
protected void setFragment( boolean v ) {
fragment = v;
}
static String[] aliases = {
"UTF-8", "UTF8",
"UTF-16", "Unicode",
"UTF-16BE", "UnicodeBigUnmarked",
"UTF-16LE", "UnicodeLittleUnmarked",
"US-ASCII", "ASCII",
"TIS-620", "TIS620",
// taken from the project-X parser
"ISO-10646-UCS-2", "Unicode",
"EBCDIC-CP-US", "cp037",
"EBCDIC-CP-CA", "cp037",
"EBCDIC-CP-NL", "cp037",
"EBCDIC-CP-WT", "cp037",
"EBCDIC-CP-DK", "cp277",
"EBCDIC-CP-NO", "cp277",
"EBCDIC-CP-FI", "cp278",
"EBCDIC-CP-SE", "cp278",
"EBCDIC-CP-IT", "cp280",
"EBCDIC-CP-ES", "cp284",
"EBCDIC-CP-GB", "cp285",
"EBCDIC-CP-FR", "cp297",
"EBCDIC-CP-AR1", "cp420",
"EBCDIC-CP-HE", "cp424",
"EBCDIC-CP-BE", "cp500",
"EBCDIC-CP-CH", "cp500",
"EBCDIC-CP-ROECE", "cp870",
"EBCDIC-CP-YU", "cp870",
"EBCDIC-CP-IS", "cp871",
"EBCDIC-CP-AR2", "cp918",
// IANA also defines two that JDK 1.2 doesn't handle:
// EBCDIC-CP-GR --> CP423
// EBCDIC-CP-TR --> CP905
};
/**
* Gets the corresponding Java encoding name from an IANA name.
*
* This method is a helper method for the derived class to convert
* encoding names.
*
* @exception UnsupportedEncodingException
* If this implementation couldn't find the Java encoding name.
*/
protected String getJavaEncoding( String encoding ) throws UnsupportedEncodingException {
try {
"1".getBytes(encoding);
return encoding;
} catch( UnsupportedEncodingException e ) {
// try known alias
for( int i=0; i<aliases.length; i+=2 ) {
if(encoding.equals(aliases[i])) {
"1".getBytes(aliases[i+1]);
return aliases[i+1];
}
}
throw new UnsupportedEncodingException(encoding);
}
/* J2SE1.4 feature
try {
this.encoding = Charset.forName( _encoding );
} catch( UnsupportedCharsetException uce ) {
throw new JAXBException( uce );
}
*/
}
/**
* Default implementation of the setProperty method handles
* the four defined properties in Marshaller. If a provider
* needs to handle additional properties, it should override
* this method in a derived class.
*/
public void setProperty( String name, Object value )
throws PropertyException {
if( name == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
}
// recognize and handle four pre-defined properties.
if( JAXB_ENCODING.equals(name) ) {
checkString( name, value );
setEncoding( (String)value );
return;
}
if( JAXB_FORMATTED_OUTPUT.equals(name) ) {
checkBoolean( name, value );
setFormattedOutput((Boolean) value );
return;
}
if( JAXB_NO_NAMESPACE_SCHEMA_LOCATION.equals(name) ) {
checkString( name, value );
setNoNSSchemaLocation( (String)value );
return;
}
if( JAXB_SCHEMA_LOCATION.equals(name) ) {
checkString( name, value );
setSchemaLocation( (String)value );
return;
}
if( JAXB_FRAGMENT.equals(name) ) {
checkBoolean(name, value);
setFragment((Boolean) value );
return;
}
throw new PropertyException(name, value);
}
/**
* Default implementation of the getProperty method handles
* the four defined properties in Marshaller. If a provider
* needs to support additional provider specific properties,
* it should override this method in a derived class.
*/
public Object getProperty( String name )
throws PropertyException {
if( name == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
}
// recognize and handle four pre-defined properties.
if( JAXB_ENCODING.equals(name) )
return getEncoding();
if( JAXB_FORMATTED_OUTPUT.equals(name) )
return isFormattedOutput()?Boolean.TRUE:Boolean.FALSE;
if( JAXB_NO_NAMESPACE_SCHEMA_LOCATION.equals(name) )
return getNoNSSchemaLocation();
if( JAXB_SCHEMA_LOCATION.equals(name) )
return getSchemaLocation();
if( JAXB_FRAGMENT.equals(name) )
return isFragment()?Boolean.TRUE:Boolean.FALSE;
throw new PropertyException(name);
}
/**
* @see javax.xml.bind.Marshaller#getEventHandler()
*/
public ValidationEventHandler getEventHandler() throws JAXBException {
return eventHandler;
}
/**
* @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
/*
* assert that the given object is a Boolean
*/
private void checkBoolean( String name, Object value ) throws PropertyException {
if(!(value instanceof Boolean))
throw new PropertyException(
Messages.format( Messages.MUST_BE_BOOLEAN, name ) );
}
/*
* assert that the given object is a String
*/
private void checkString( String name, Object value ) throws PropertyException {
if(!(value instanceof String))
throw new PropertyException(
Messages.format( Messages.MUST_BE_STRING, name ) );
}
/*
* assert that the parameters are not null
*/
private void checkNotNull( Object o1, String o1Name,
Object o2, String o2Name ) {
if( o1 == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, o1Name ) );
}
if( o2 == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, o2Name ) );
}
}
public void marshal(Object obj, XMLEventWriter writer)
throws JAXBException {
throw new UnsupportedOperationException();
}
public void marshal(Object obj, XMLStreamWriter writer)
throws JAXBException {
throw new UnsupportedOperationException();
}
public void setSchema(Schema schema) {
throw new UnsupportedOperationException();
}
public Schema getSchema() {
throw new UnsupportedOperationException();
}
public void setAdapter(XmlAdapter adapter) {
if(adapter==null)
throw new IllegalArgumentException();
setAdapter((Class)adapter.getClass(),adapter);
}
public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) {
throw new UnsupportedOperationException();
}
public <A extends XmlAdapter> A getAdapter(Class<A> type) {
throw new UnsupportedOperationException();
}
public void setAttachmentMarshaller(AttachmentMarshaller am) {
throw new UnsupportedOperationException();
}
public AttachmentMarshaller getAttachmentMarshaller() {
throw new UnsupportedOperationException();
}
public void setListener(Listener listener) {
throw new UnsupportedOperationException();
}
public Listener getListener() {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,435 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.w3c.dom.Node;
import javax.xml.bind.JAXBException;
import javax.xml.bind.PropertyException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.attachment.AttachmentUnmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import java.io.File;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Partial default <tt>Unmarshaller</tt> implementation.
*
* <p>
* This class provides a partial default implementation for the
* {@link javax.xml.bind.Unmarshaller}interface.
*
* <p>
* A JAXB Provider has to implement five methods (getUnmarshallerHandler,
* unmarshal(Node), unmarshal(XMLReader,InputSource),
* unmarshal(XMLStreamReader), and unmarshal(XMLEventReader).
*
* @author <ul>
* <li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li>
* </ul>
* @see javax.xml.bind.Unmarshaller
* @since JAXB1.0
*/
public abstract class AbstractUnmarshallerImpl implements Unmarshaller
{
/** handler that will be used to process errors and warnings during unmarshal */
private ValidationEventHandler eventHandler =
new DefaultValidationEventHandler();
/** whether or not the unmarshaller will validate */
protected boolean validating = false;
/**
* XMLReader that will be used to parse a document.
*/
private XMLReader reader = null;
/**
* Obtains a configured XMLReader.
*
* This method is used when the client-specified
* {@link SAXSource} object doesn't have XMLReader.
*
* {@link Unmarshaller} is not re-entrant, so we will
* only use one instance of XMLReader.
*/
protected XMLReader getXMLReader() throws JAXBException {
if(reader==null) {
try {
SAXParserFactory parserFactory;
parserFactory = SAXParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
// there is no point in asking a validation because
// there is no guarantee that the document will come with
// a proper schemaLocation.
parserFactory.setValidating(false);
reader = parserFactory.newSAXParser().getXMLReader();
} catch( ParserConfigurationException e ) {
throw new JAXBException(e);
} catch( SAXException e ) {
throw new JAXBException(e);
}
}
return reader;
}
public Object unmarshal( Source source ) throws JAXBException {
if( source == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
}
if(source instanceof SAXSource)
return unmarshal( (SAXSource)source );
if(source instanceof StreamSource)
return unmarshal( streamSourceToInputSource((StreamSource)source));
if(source instanceof DOMSource)
return unmarshal( ((DOMSource)source).getNode() );
// we don't handle other types of Source
throw new IllegalArgumentException();
}
// use the client specified XMLReader contained in the SAXSource.
private Object unmarshal( SAXSource source ) throws JAXBException {
XMLReader r = source.getXMLReader();
if( r == null )
r = getXMLReader();
return unmarshal( r, source.getInputSource() );
}
/**
* Unmarshals an object by using the specified XMLReader and the InputSource.
*
* The callee should call the setErrorHandler method of the XMLReader
* so that errors are passed to the client-specified ValidationEventHandler.
*/
protected abstract Object unmarshal( XMLReader reader, InputSource source ) throws JAXBException;
public final Object unmarshal( InputSource source ) throws JAXBException {
if( source == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
}
return unmarshal( getXMLReader(), source );
}
private Object unmarshal( String url ) throws JAXBException {
return unmarshal( new InputSource(url) );
}
public final Object unmarshal( URL url ) throws JAXBException {
if( url == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "url" ) );
}
return unmarshal( url.toExternalForm() );
}
public final Object unmarshal( File f ) throws JAXBException {
if( f == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "file" ) );
}
try {
// copied from JAXP
String path = f.getAbsolutePath();
if (File.separatorChar != '/')
path = path.replace(File.separatorChar, '/');
if (!path.startsWith("/"))
path = "/" + path;
if (!path.endsWith("/") && f.isDirectory())
path = path + "/";
return unmarshal(new URL("file", "", path));
} catch( MalformedURLException e ) {
throw new IllegalArgumentException(e.getMessage());
}
}
public final Object unmarshal( java.io.InputStream is )
throws JAXBException {
if( is == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "is" ) );
}
InputSource isrc = new InputSource( is );
return unmarshal( isrc );
}
public final Object unmarshal( Reader reader ) throws JAXBException {
if( reader == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "reader" ) );
}
InputSource isrc = new InputSource( reader );
return unmarshal( isrc );
}
private static InputSource streamSourceToInputSource( StreamSource ss ) {
InputSource is = new InputSource();
is.setSystemId( ss.getSystemId() );
is.setByteStream( ss.getInputStream() );
is.setCharacterStream( ss.getReader() );
return is;
}
/**
* Indicates whether or not the Unmarshaller is configured to validate
* during unmarshal operations.
* <p>
* <i><b>Note:</b> I named this method isValidating() to stay in-line
* with JAXP, as opposed to naming it getValidating(). </i>
*
* @return true if the Unmarshaller is configured to validate during
* unmarshal operations, false otherwise
* @throws JAXBException if an error occurs while retrieving the validating
* flag
*/
public boolean isValidating() throws JAXBException {
return validating;
}
/**
* Allow an application to register a validation event handler.
* <p>
* The validation event handler will be called by the JAXB Provider if any
* validation errors are encountered during calls to any of the
* <tt>unmarshal</tt> methods. If the client application does not register
* a validation event handler before invoking the unmarshal methods, then
* all validation events will be silently ignored and may result in
* unexpected behaviour.
*
* @param handler the validation event handler
* @throws JAXBException if an error was encountered while setting the
* event handler
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
/**
* Specifies whether or not the Unmarshaller should validate during
* unmarshal operations. By default, the <tt>Unmarshaller</tt> does
* not validate.
* <p>
* This method may only be invoked before or after calling one of the
* unmarshal methods.
*
* @param validating true if the Unmarshaller should validate during
* unmarshal, false otherwise
* @throws JAXBException if an error occurred while enabling or disabling
* validation at unmarshal time
*/
public void setValidating(boolean validating) throws JAXBException {
this.validating = validating;
}
/**
* Return the current event handler or the default event handler if one
* hasn't been set.
*
* @return the current ValidationEventHandler or the default event handler
* if it hasn't been set
* @throws JAXBException if an error was encountered while getting the
* current event handler
*/
public ValidationEventHandler getEventHandler() throws JAXBException {
return eventHandler;
}
/**
* Creates an UnmarshalException from a SAXException.
*
* This is an utility method provided for the derived classes.
*
* <p>
* When a provider-implemented ContentHandler wants to throw a
* JAXBException, it needs to wrap the exception by a SAXException.
* If the unmarshaller implementation blindly wrap SAXException
* by JAXBException, such an exception will be a JAXBException
* wrapped by a SAXException wrapped by another JAXBException.
* This is silly.
*
* <p>
* This method checks the nested exception of SAXException
* and reduce those excessive wrapping.
*
* @return the resulting UnmarshalException
*/
protected UnmarshalException createUnmarshalException( SAXException e ) {
// check the nested exception to see if it's an UnmarshalException
Exception nested = e.getException();
if(nested instanceof UnmarshalException)
return (UnmarshalException)nested;
if(nested instanceof RuntimeException)
// typically this is an unexpected exception,
// just throw it rather than wrap it, so that the full stack
// trace can be displayed.
throw (RuntimeException)nested;
// otherwise simply wrap it
if(nested!=null)
return new UnmarshalException(nested);
else
return new UnmarshalException(e);
}
/**
* Default implementation of the setProperty method always
* throws PropertyException since there are no required
* properties. If a provider needs to handle additional
* properties, it should override this method in a derived class.
*/
public void setProperty( String name, Object value )
throws PropertyException {
if( name == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
}
throw new PropertyException(name, value);
}
/**
* Default implementation of the getProperty method always
* throws PropertyException since there are no required
* properties. If a provider needs to handle additional
* properties, it should override this method in a derived class.
*/
public Object getProperty( String name )
throws PropertyException {
if( name == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "name" ) );
}
throw new PropertyException(name);
}
public Object unmarshal(XMLEventReader reader) throws JAXBException {
throw new UnsupportedOperationException();
}
public Object unmarshal(XMLStreamReader reader) throws JAXBException {
throw new UnsupportedOperationException();
}
public <T> JAXBElement<T> unmarshal(Node node, Class<T> expectedType) throws JAXBException {
throw new UnsupportedOperationException();
}
public <T> JAXBElement<T> unmarshal(Source source, Class<T> expectedType) throws JAXBException {
throw new UnsupportedOperationException();
}
public <T> JAXBElement<T> unmarshal(XMLStreamReader reader, Class<T> expectedType) throws JAXBException {
throw new UnsupportedOperationException();
}
public <T> JAXBElement<T> unmarshal(XMLEventReader reader, Class<T> expectedType) throws JAXBException {
throw new UnsupportedOperationException();
}
public void setSchema(Schema schema) {
throw new UnsupportedOperationException();
}
public Schema getSchema() {
throw new UnsupportedOperationException();
}
public void setAdapter(XmlAdapter adapter) {
if(adapter==null)
throw new IllegalArgumentException();
setAdapter((Class)adapter.getClass(),adapter);
}
public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) {
throw new UnsupportedOperationException();
}
public <A extends XmlAdapter> A getAdapter(Class<A> type) {
throw new UnsupportedOperationException();
}
public void setAttachmentUnmarshaller(AttachmentUnmarshaller au) {
throw new UnsupportedOperationException();
}
public AttachmentUnmarshaller getAttachmentUnmarshaller() {
throw new UnsupportedOperationException();
}
public void setListener(Listener listener) {
throw new UnsupportedOperationException();
}
public Listener getListener() {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import org.w3c.dom.Node;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationEventLocator;
import java.net.URL;
/**
* <p>
* JAXB 1.0 only default validation event handler. This is the default
* handler for all objects created from a JAXBContext that is managing
* schema-derived code generated by a JAXB 1.0 binding compiler.
*
* <p>
* This handler causes the unmarshal and validate operations to fail on the first
* error or fatal error.
*
* <p>
* This handler is not the default handler for JAXB mapped classes following
* JAXB 2.0 or later versions. Default validation event handling has changed
* and is specified in {@link javax.xml.bind.Unmarshaller} and
* {@link javax.xml.bind.Marshaller}.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.Unmarshaller
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @since JAXB1.0
*/
public class DefaultValidationEventHandler implements ValidationEventHandler {
public boolean handleEvent( ValidationEvent event ) {
if( event == null ) {
throw new IllegalArgumentException();
}
// calculate the severity prefix and return value
String severity = null;
boolean retVal = false;
switch ( event.getSeverity() ) {
case ValidationEvent.WARNING:
severity = Messages.format( Messages.WARNING );
retVal = true; // continue after warnings
break;
case ValidationEvent.ERROR:
severity = Messages.format( Messages.ERROR );
retVal = false; // terminate after errors
break;
case ValidationEvent.FATAL_ERROR:
severity = Messages.format( Messages.FATAL_ERROR );
retVal = false; // terminate after fatal errors
break;
default:
assert false :
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() );
}
// calculate the location message
String location = getLocation( event );
System.out.println(
Messages.format( Messages.SEVERITY_MESSAGE,
severity,
event.getMessage(),
location ) );
// fail on the first error or fatal error
return retVal;
}
/**
* Calculate a location message for the event
*
*/
private String getLocation(ValidationEvent event) {
StringBuffer msg = new StringBuffer();
ValidationEventLocator locator = event.getLocator();
if( locator != null ) {
URL url = locator.getURL();
Object obj = locator.getObject();
Node node = locator.getNode();
int line = locator.getLineNumber();
if( url!=null || line!=-1 ) {
msg.append( "line " + line );
if( url!=null )
msg.append( " of " + url );
} else if( obj != null ) {
msg.append( " obj: " + obj.toString() );
} else if( node != null ) {
msg.append( " node: " + node.toString() );
}
} else {
msg.append( Messages.format( Messages.LOCATION_UNAVAILABLE ) );
}
return msg.toString();
}
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*/
class Messages
{
static String format( String property ) {
return format( property, null );
}
static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
static String format( String property, Object arg1, Object arg2, Object arg3 ) {
return format( property, new Object[]{arg1,arg2,arg3} );
}
// add more if necessary.
/** Loads a string resource and formats it with specified arguments. */
static String format( String property, Object[] args ) {
String text = ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
static final String INPUTSTREAM_NOT_NULL = // 0 args
"AbstractUnmarshallerImpl.ISNotNull";
static final String MUST_BE_BOOLEAN = // 1 arg
"AbstractMarshallerImpl.MustBeBoolean";
static final String MUST_BE_STRING = // 1 arg
"AbstractMarshallerImpl.MustBeString";
static final String SEVERITY_MESSAGE = // 3 args
"DefaultValidationEventHandler.SeverityMessage";
static final String LOCATION_UNAVAILABLE = // 0 args
"DefaultValidationEventHandler.LocationUnavailable";
static final String UNRECOGNIZED_SEVERITY = // 1 arg
"DefaultValidationEventHandler.UnrecognizedSeverity";
static final String WARNING = // 0 args
"DefaultValidationEventHandler.Warning";
static final String ERROR = // 0 args
"DefaultValidationEventHandler.Error";
static final String FATAL_ERROR = // 0 args
"DefaultValidationEventHandler.FatalError";
static final String ILLEGAL_SEVERITY = // 0 args
"ValidationEventImpl.IllegalSeverity";
static final String MUST_NOT_BE_NULL = // 1 arg
"Shared.MustNotBeNull";
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import javax.xml.bind.ValidationEventLocator;
/**
* Default implementation of the NotIdentifiableEvent interface.
*
* <p>
* JAXB providers are allowed to use whatever class that implements
* the ValidationEvent interface. This class is just provided for a
* convenience.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.NotIdentifiableEvent
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class NotIdentifiableEventImpl
extends ValidationEventImpl
implements javax.xml.bind.NotIdentifiableEvent {
/**
* Create a new NotIdentifiableEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public NotIdentifiableEventImpl( int _severity, String _message,
ValidationEventLocator _locator) {
super(_severity, _message, _locator);
}
/**
* Create a new NotIdentifiableEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @param _linkedException An optional linked exception that may provide
* additional information about the event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public NotIdentifiableEventImpl( int _severity, String _message,
ValidationEventLocator _locator,
Throwable _linkedException) {
super(_severity, _message, _locator, _linkedException);
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import javax.xml.bind.ParseConversionEvent;
import javax.xml.bind.ValidationEventLocator;
/**
* Default implementation of the ParseConversionEvent interface.
*
* <p>
* JAXB providers are allowed to use whatever class that implements
* the ValidationEvent interface. This class is just provided for a
* convenience.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.ParseConversionEvent
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class ParseConversionEventImpl
extends ValidationEventImpl
implements ParseConversionEvent {
/**
* Create a new ParseConversionEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public ParseConversionEventImpl( int _severity, String _message,
ValidationEventLocator _locator) {
super(_severity, _message, _locator);
}
/**
* Create a new ParseConversionEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @param _linkedException An optional linked exception that may provide
* additional information about the event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public ParseConversionEventImpl( int _severity, String _message,
ValidationEventLocator _locator,
Throwable _linkedException) {
super(_severity, _message, _locator, _linkedException);
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import javax.xml.bind.PrintConversionEvent;
import javax.xml.bind.ValidationEventLocator;
/**
* Default implementation of the PrintConversionEvent interface.
*
* <p>
* JAXB providers are allowed to use whatever class that implements
* the ValidationEvent interface. This class is just provided for a
* convenience.
*
* @author <ul><li>Ryan Shoemaker, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.PrintConversionEvent
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class PrintConversionEventImpl
extends ValidationEventImpl
implements PrintConversionEvent {
/**
* Create a new PrintConversionEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public PrintConversionEventImpl( int _severity, String _message,
ValidationEventLocator _locator) {
super(_severity, _message, _locator);
}
/**
* Create a new PrintConversionEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @param _linkedException An optional linked exception that may provide
* additional information about the event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public PrintConversionEventImpl( int _severity, String _message,
ValidationEventLocator _locator,
Throwable _linkedException) {
super(_severity, _message, _locator, _linkedException);
}
}

View File

@@ -0,0 +1,175 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import java.text.MessageFormat;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventLocator;
/**
* Default implementation of the ValidationEvent interface.
*
* <p>
* JAXB providers are allowed to use whatever class that implements
* the ValidationEvent interface. This class is just provided for a
* convenience.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class ValidationEventImpl implements ValidationEvent
{
/**
* Create a new ValidationEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public ValidationEventImpl( int _severity, String _message,
ValidationEventLocator _locator ) {
this(_severity,_message,_locator,null);
}
/**
* Create a new ValidationEventImpl.
*
* @param _severity The severity value for this event. Must be one of
* ValidationEvent.WARNING, ValidationEvent.ERROR, or
* ValidationEvent.FATAL_ERROR
* @param _message The text message for this event - may be null.
* @param _locator The locator object for this event - may be null.
* @param _linkedException An optional linked exception that may provide
* additional information about the event - may be null.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public ValidationEventImpl( int _severity, String _message,
ValidationEventLocator _locator,
Throwable _linkedException ) {
setSeverity( _severity );
this.message = _message;
this.locator = _locator;
this.linkedException = _linkedException;
}
private int severity;
private String message;
private Throwable linkedException;
private ValidationEventLocator locator;
public int getSeverity() {
return severity;
}
/**
* Set the severity field of this event.
*
* @param _severity Must be one of ValidationEvent.WARNING,
* ValidationEvent.ERROR, or ValidationEvent.FATAL_ERROR.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public void setSeverity( int _severity ) {
if( _severity != ValidationEvent.WARNING &&
_severity != ValidationEvent.ERROR &&
_severity != ValidationEvent.FATAL_ERROR ) {
throw new IllegalArgumentException(
Messages.format( Messages.ILLEGAL_SEVERITY ) );
}
this.severity = _severity;
}
public String getMessage() {
return message;
}
/**
* Set the message field of this event.
*
* @param _message String message - may be null.
*/
public void setMessage( String _message ) {
this.message = _message;
}
public Throwable getLinkedException() {
return linkedException;
}
/**
* Set the linked exception field of this event.
*
* @param _linkedException Optional linked exception - may be null.
*/
public void setLinkedException( Throwable _linkedException ) {
this.linkedException = _linkedException;
}
public ValidationEventLocator getLocator() {
return locator;
}
/**
* Set the locator object for this event.
*
* @param _locator The locator - may be null.
*/
public void setLocator( ValidationEventLocator _locator ) {
this.locator = _locator;
}
/**
* Returns a string representation of this object in a format
* helpful to debugging.
*
* @see Object#equals(Object)
*/
public String toString() {
String s;
switch(getSeverity()) {
case WARNING: s="WARNING";break;
case ERROR: s="ERROR";break;
case FATAL_ERROR: s="FATAL_ERROR";break;
default: s=String.valueOf(getSeverity());break;
}
return MessageFormat.format("[severity={0},message={1},locator={2}]",
new Object[]{
s,
getMessage(),
getLocator()
});
}
}

View File

@@ -0,0 +1,273 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.helpers;
import java.net.URL;
import java.net.MalformedURLException;
import java.text.MessageFormat;
import javax.xml.bind.ValidationEventLocator;
import org.w3c.dom.Node;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
/**
* Default implementation of the ValidationEventLocator interface.
*
* <p>
* JAXB providers are allowed to use whatever class that implements
* the ValidationEventLocator interface. This class is just provided for a
* convenience.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class ValidationEventLocatorImpl implements ValidationEventLocator
{
/**
* Creates an object with all fields unavailable.
*/
public ValidationEventLocatorImpl() {
}
/**
* Constructs an object from an org.xml.sax.Locator.
*
* The object's ColumnNumber, LineNumber, and URL become available from the
* values returned by the locator's getColumnNumber(), getLineNumber(), and
* getSystemId() methods respectively. Node, Object, and Offset are not
* available.
*
* @param loc the SAX Locator object that will be used to populate this
* event locator.
* @throws IllegalArgumentException if the Locator is null
*/
public ValidationEventLocatorImpl( Locator loc ) {
if( loc == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "loc" ) );
}
this.url = toURL(loc.getSystemId());
this.columnNumber = loc.getColumnNumber();
this.lineNumber = loc.getLineNumber();
}
/**
* Constructs an object from the location information of a SAXParseException.
*
* The object's ColumnNumber, LineNumber, and URL become available from the
* values returned by the locator's getColumnNumber(), getLineNumber(), and
* getSystemId() methods respectively. Node, Object, and Offset are not
* available.
*
* @param e the SAXParseException object that will be used to populate this
* event locator.
* @throws IllegalArgumentException if the SAXParseException is null
*/
public ValidationEventLocatorImpl( SAXParseException e ) {
if( e == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "e" ) );
}
this.url = toURL(e.getSystemId());
this.columnNumber = e.getColumnNumber();
this.lineNumber = e.getLineNumber();
}
/**
* Constructs an object that points to a DOM Node.
*
* The object's Node becomes available. ColumnNumber, LineNumber, Object,
* Offset, and URL are not available.
*
* @param _node the DOM Node object that will be used to populate this
* event locator.
* @throws IllegalArgumentException if the Node is null
*/
public ValidationEventLocatorImpl(Node _node) {
if( _node == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "_node" ) );
}
this.node = _node;
}
/**
* Constructs an object that points to a JAXB content object.
*
* The object's Object becomes available. ColumnNumber, LineNumber, Node,
* Offset, and URL are not available.
*
* @param _object the Object that will be used to populate this
* event locator.
* @throws IllegalArgumentException if the Object is null
*/
public ValidationEventLocatorImpl(Object _object) {
if( _object == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "_object" ) );
}
this.object = _object;
}
/** Converts a system ID to an URL object. */
private static URL toURL( String systemId ) {
try {
return new URL(systemId);
} catch( MalformedURLException e ) {
// TODO: how should we handle system id here?
return null; // for now
}
}
private URL url = null;
private int offset = -1;
private int lineNumber = -1;
private int columnNumber = -1;
private Object object = null;
private Node node = null;
/**
* @see javax.xml.bind.ValidationEventLocator#getURL()
*/
public URL getURL() {
return url;
}
/**
* Set the URL field on this event locator. Null values are allowed.
*
* @param _url the url
*/
public void setURL( URL _url ) {
this.url = _url;
}
/**
* @see javax.xml.bind.ValidationEventLocator#getOffset()
*/
public int getOffset() {
return offset;
}
/**
* Set the offset field on this event locator.
*
* @param _offset the offset
*/
public void setOffset( int _offset ) {
this.offset = _offset;
}
/**
* @see javax.xml.bind.ValidationEventLocator#getLineNumber()
*/
public int getLineNumber() {
return lineNumber;
}
/**
* Set the lineNumber field on this event locator.
*
* @param _lineNumber the line number
*/
public void setLineNumber( int _lineNumber ) {
this.lineNumber = _lineNumber;
}
/**
* @see javax.xml.bind.ValidationEventLocator#getColumnNumber()
*/
public int getColumnNumber() {
return columnNumber;
}
/**
* Set the columnNumber field on this event locator.
*
* @param _columnNumber the column number
*/
public void setColumnNumber( int _columnNumber ) {
this.columnNumber = _columnNumber;
}
/**
* @see javax.xml.bind.ValidationEventLocator#getObject()
*/
public Object getObject() {
return object;
}
/**
* Set the Object field on this event locator. Null values are allowed.
*
* @param _object the java content object
*/
public void setObject( Object _object ) {
this.object = _object;
}
/**
* @see javax.xml.bind.ValidationEventLocator#getNode()
*/
public Node getNode() {
return node;
}
/**
* Set the Node field on this event locator. Null values are allowed.
*
* @param _node the Node
*/
public void setNode( Node _node ) {
this.node = _node;
}
/**
* Returns a string representation of this object in a format
* helpful to debugging.
*
* @see Object#equals(Object)
*/
public String toString() {
return MessageFormat.format("[node={0},object={1},url={2},line={3},col={4},offset={5}]",
getNode(),
getObject(),
getURL(),
String.valueOf(getLineNumber()),
String.valueOf(getColumnNumber()),
String.valueOf(getOffset()));
}
}

View File

@@ -0,0 +1,150 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.util;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.UnmarshallerHandler;
import javax.xml.transform.sax.SAXResult;
/**
* JAXP {@link javax.xml.transform.Result} implementation
* that unmarshals a JAXB object.
*
* <p>
* This utility class is useful to combine JAXB with
* other Java/XML technologies.
*
* <p>
* The following example shows how to use JAXB to unmarshal a document
* resulting from an XSLT transformation.
*
* <blockquote>
* <pre>
* JAXBResult result = new JAXBResult(
* JAXBContext.newInstance("org.acme.foo") );
*
* // set up XSLT transformation
* TransformerFactory tf = TransformerFactory.newInstance();
* Transformer t = tf.newTransformer(new StreamSource("test.xsl"));
*
* // run transformation
* t.transform(new StreamSource("document.xml"),result);
*
* // obtain the unmarshalled content tree
* Object o = result.getResult();
* </pre>
* </blockquote>
*
* <p>
* The fact that JAXBResult derives from SAXResult is an implementation
* detail. Thus in general applications are strongly discouraged from
* accessing methods defined on SAXResult.
*
* <p>
* In particular it shall never attempt to call the setHandler,
* setLexicalHandler, and setSystemId methods.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class JAXBResult extends SAXResult {
/**
* Creates a new instance that uses the specified
* JAXBContext to unmarshal.
*
* @param context The JAXBContext that will be used to create the
* necessary Unmarshaller. This parameter must not be null.
* @exception JAXBException if an error is encountered while creating the
* JAXBResult or if the context parameter is null.
*/
public JAXBResult( JAXBContext context ) throws JAXBException {
this( ( context == null ) ? assertionFailed() : context.createUnmarshaller() );
}
/**
* Creates a new instance that uses the specified
* Unmarshaller to unmarshal an object.
*
* <p>
* This JAXBResult object will use the specified Unmarshaller
* instance. It is the caller's responsibility not to use the
* same Unmarshaller for other purposes while it is being
* used by this object.
*
* <p>
* The primary purpose of this method is to allow the client
* to configure Unmarshaller. Unless you know what you are doing,
* it's easier and safer to pass a JAXBContext.
*
* @param _unmarshaller the unmarshaller. This parameter must not be null.
* @throws JAXBException if an error is encountered while creating the
* JAXBResult or the Unmarshaller parameter is null.
*/
public JAXBResult( Unmarshaller _unmarshaller ) throws JAXBException {
if( _unmarshaller == null )
throw new JAXBException(
Messages.format( Messages.RESULT_NULL_UNMARSHALLER ) );
this.unmarshallerHandler = _unmarshaller.getUnmarshallerHandler();
super.setHandler(unmarshallerHandler);
}
/**
* Unmarshaller that will be used to unmarshal
* the input documents.
*/
private final UnmarshallerHandler unmarshallerHandler;
/**
* Gets the unmarshalled object created by the transformation.
*
* @return
* Always return a non-null object.
*
* @exception IllegalStateException
* if this method is called before an object is unmarshalled.
*
* @exception JAXBException
* if there is any unmarshalling error.
* Note that the implementation is allowed to throw SAXException
* during the parsing when it finds an error.
*/
public Object getResult() throws JAXBException {
return unmarshallerHandler.getResult();
}
/**
* Hook to throw exception from the middle of a contructor chained call
* to this
*/
private static Unmarshaller assertionFailed() throws JAXBException {
throw new JAXBException( Messages.format( Messages.RESULT_NULL_CONTEXT ) );
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.util;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.XMLFilterImpl;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.XMLFilter;
/**
* JAXP {@link javax.xml.transform.Source} implementation
* that marshals a JAXB-generated object.
*
* <p>
* This utility class is useful to combine JAXB with
* other Java/XML technologies.
*
* <p>
* The following example shows how to use JAXB to marshal a document
* for transformation by XSLT.
*
* <blockquote>
* <pre>
* MyObject o = // get JAXB content tree
*
* // jaxbContext is a JAXBContext object from which 'o' is created.
* JAXBSource source = new JAXBSource( jaxbContext, o );
*
* // set up XSLT transformation
* TransformerFactory tf = TransformerFactory.newInstance();
* Transformer t = tf.newTransformer(new StreamSource("test.xsl"));
*
* // run transformation
* t.transform(source,new StreamResult(System.out));
* </pre>
* </blockquote>
*
* <p>
* The fact that JAXBSource derives from SAXSource is an implementation
* detail. Thus in general applications are strongly discouraged from
* accessing methods defined on SAXSource. In particular,
* the setXMLReader and setInputSource methods shall never be called.
* The XMLReader object obtained by the getXMLReader method shall
* be used only for parsing the InputSource object returned by
* the getInputSource method.
*
* <p>
* Similarly the InputSource object obtained by the getInputSource
* method shall be used only for being parsed by the XMLReader object
* returned by the getXMLReader.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class JAXBSource extends SAXSource {
/**
* Creates a new {@link javax.xml.transform.Source} for the given content object.
*
* @param context
* JAXBContext that was used to create
* <code>contentObject</code>. This context is used
* to create a new instance of marshaller and must not be null.
* @param contentObject
* An instance of a JAXB-generated class, which will be
* used as a {@link javax.xml.transform.Source} (by marshalling it into XML). It must
* not be null.
* @throws JAXBException if an error is encountered while creating the
* JAXBSource or if either of the parameters are null.
*/
public JAXBSource( JAXBContext context, Object contentObject )
throws JAXBException {
this(
( context == null ) ?
assertionFailed( Messages.format( Messages.SOURCE_NULL_CONTEXT ) ) :
context.createMarshaller(),
( contentObject == null ) ?
assertionFailed( Messages.format( Messages.SOURCE_NULL_CONTENT ) ) :
contentObject);
}
/**
* Creates a new {@link javax.xml.transform.Source} for the given content object.
*
* @param marshaller
* A marshaller instance that will be used to marshal
* <code>contentObject</code> into XML. This must be
* created from a JAXBContext that was used to build
* <code>contentObject</code> and must not be null.
* @param contentObject
* An instance of a JAXB-generated class, which will be
* used as a {@link javax.xml.transform.Source} (by marshalling it into XML). It must
* not be null.
* @throws JAXBException if an error is encountered while creating the
* JAXBSource or if either of the parameters are null.
*/
public JAXBSource( Marshaller marshaller, Object contentObject )
throws JAXBException {
if( marshaller == null )
throw new JAXBException(
Messages.format( Messages.SOURCE_NULL_MARSHALLER ) );
if( contentObject == null )
throw new JAXBException(
Messages.format( Messages.SOURCE_NULL_CONTENT ) );
this.marshaller = marshaller;
this.contentObject = contentObject;
super.setXMLReader(pseudoParser);
// pass a dummy InputSource. We don't care
super.setInputSource(new InputSource());
}
private final Marshaller marshaller;
private final Object contentObject;
// this object will pretend as an XMLReader.
// no matter what parameter is specified to the parse method,
// it just parse the contentObject.
private final XMLReader pseudoParser = new XMLReader() {
public boolean getFeature(String name) throws SAXNotRecognizedException {
if(name.equals("http://xml.org/sax/features/namespaces"))
return true;
if(name.equals("http://xml.org/sax/features/namespace-prefixes"))
return false;
throw new SAXNotRecognizedException(name);
}
public void setFeature(String name, boolean value) throws SAXNotRecognizedException {
if(name.equals("http://xml.org/sax/features/namespaces") && value)
return;
if(name.equals("http://xml.org/sax/features/namespace-prefixes") && !value)
return;
throw new SAXNotRecognizedException(name);
}
public Object getProperty(String name) throws SAXNotRecognizedException {
if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) {
return lexicalHandler;
}
throw new SAXNotRecognizedException(name);
}
public void setProperty(String name, Object value) throws SAXNotRecognizedException {
if( "http://xml.org/sax/properties/lexical-handler".equals(name) ) {
this.lexicalHandler = (LexicalHandler)value;
return;
}
throw new SAXNotRecognizedException(name);
}
private LexicalHandler lexicalHandler;
// we will store this value but never use it by ourselves.
private EntityResolver entityResolver;
public void setEntityResolver(EntityResolver resolver) {
this.entityResolver = resolver;
}
public EntityResolver getEntityResolver() {
return entityResolver;
}
private DTDHandler dtdHandler;
public void setDTDHandler(DTDHandler handler) {
this.dtdHandler = handler;
}
public DTDHandler getDTDHandler() {
return dtdHandler;
}
// SAX allows ContentHandler to be changed during the parsing,
// but JAXB doesn't. So this repeater will sit between those
// two components.
private XMLFilter repeater = new XMLFilterImpl();
public void setContentHandler(ContentHandler handler) {
repeater.setContentHandler(handler);
}
public ContentHandler getContentHandler() {
return repeater.getContentHandler();
}
private ErrorHandler errorHandler;
public void setErrorHandler(ErrorHandler handler) {
this.errorHandler = handler;
}
public ErrorHandler getErrorHandler() {
return errorHandler;
}
public void parse(InputSource input) throws SAXException {
parse();
}
public void parse(String systemId) throws SAXException {
parse();
}
public void parse() throws SAXException {
// parses a content object by using the given marshaller
// SAX events will be sent to the repeater, and the repeater
// will further forward it to an appropriate component.
try {
marshaller.marshal( contentObject, (XMLFilterImpl)repeater );
} catch( JAXBException e ) {
// wrap it to a SAXException
SAXParseException se =
new SAXParseException( e.getMessage(),
null, null, -1, -1, e );
// if the consumer sets an error handler, it is our responsibility
// to notify it.
if(errorHandler!=null)
errorHandler.fatalError(se);
// this is a fatal error. Even if the error handler
// returns, we will abort anyway.
throw se;
}
}
};
/**
* Hook to throw exception from the middle of a contructor chained call
* to this
*/
private static Marshaller assertionFailed( String message )
throws JAXBException {
throw new JAXBException( message );
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.util;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*/
class Messages
{
static String format( String property ) {
return format( property, null );
}
static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
static String format( String property, Object arg1, Object arg2, Object arg3 ) {
return format( property, new Object[]{arg1,arg2,arg3} );
}
// add more if necessary.
/** Loads a string resource and formats it with specified arguments. */
static String format( String property, Object[] args ) {
String text = ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
static final String UNRECOGNIZED_SEVERITY = // 1 arg
"ValidationEventCollector.UnrecognizedSeverity";
static final String RESULT_NULL_CONTEXT = // 0 args
"JAXBResult.NullContext";
static final String RESULT_NULL_UNMARSHALLER = // 0 arg
"JAXBResult.NullUnmarshaller";
static final String SOURCE_NULL_CONTEXT = // 0 args
"JAXBSource.NullContext";
static final String SOURCE_NULL_CONTENT = // 0 arg
"JAXBSource.NullContent";
static final String SOURCE_NULL_MARSHALLER = // 0 arg
"JAXBSource.NullMarshaller";
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.bind.util;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import java.util.ArrayList;
import java.util.List;
/**
* {@link javax.xml.bind.ValidationEventHandler ValidationEventHandler}
* implementation that collects all events.
*
* <p>
* To use this class, create a new instance and pass it to the setEventHandler
* method of the Validator, Unmarshaller, Marshaller class. After the call to
* validate or unmarshal completes, call the getEvents method to retrieve all
* the reported errors and warnings.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li><li>Ryan Shoemaker, Sun Microsystems, Inc.</li><li>Joe Fialli, Sun Microsystems, Inc.</li></ul>
* @see javax.xml.bind.Validator
* @see javax.xml.bind.ValidationEventHandler
* @see javax.xml.bind.ValidationEvent
* @see javax.xml.bind.ValidationEventLocator
* @since JAXB1.0
*/
public class ValidationEventCollector implements ValidationEventHandler
{
private final List<ValidationEvent> events = new ArrayList<ValidationEvent>();
/**
* Return an array of ValidationEvent objects containing a copy of each of
* the collected errors and warnings.
*
* @return
* a copy of all the collected errors and warnings or an empty array
* if there weren't any
*/
public ValidationEvent[] getEvents() {
return events.toArray(new ValidationEvent[events.size()]);
}
/**
* Clear all collected errors and warnings.
*/
public void reset() {
events.clear();
}
/**
* Returns true if this event collector contains at least one
* ValidationEvent.
*
* @return true if this event collector contains at least one
* ValidationEvent, false otherwise
*/
public boolean hasEvents() {
return !events.isEmpty();
}
public boolean handleEvent( ValidationEvent event ) {
events.add(event);
boolean retVal = true;
switch( event.getSeverity() ) {
case ValidationEvent.WARNING:
retVal = true; // continue validation
break;
case ValidationEvent.ERROR:
retVal = true; // continue validation
break;
case ValidationEvent.FATAL_ERROR:
retVal = false; // halt validation
break;
default:
_assert( false,
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() ) );
break;
}
return retVal;
}
private static void _assert( boolean b, String msg ) {
if( !b ) {
throw new InternalError( msg );
}
}
}