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,63 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.xml.bind.JAXBException;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
/**
* A means to allow the user to provide customized Accessor
* to be used by JAXB.
*/
public interface AccessorFactory {
/**
* Access a field of the class.
*
* @param bean the class to be processed.
* @param f the field within the class to be accessed.
* @param readOnly the isStatic value of the field's modifier.
* @return Accessor the accessor for this field
*
* @throws JAXBException reports failures of the method.
*/
Accessor createFieldAccessor(Class bean, Field f, boolean readOnly) throws JAXBException;
/**
* Access a property of the class.
*
* @param bean the class to be processed
* @param getter the getter method to be accessed. The value can be null.
* @param setter the setter method to be accessed. The value can be null.
* @return Accessor the accessor for these methods
*
* @throws JAXBException reports failures of the method.
*/
Accessor createPropertyAccessor(Class bean, Method getter, Method setter) throws JAXBException;
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.xml.bind.JAXBException;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
public class AccessorFactoryImpl implements InternalAccessorFactory {
private static AccessorFactoryImpl instance = new AccessorFactoryImpl();
private AccessorFactoryImpl(){}
public static AccessorFactoryImpl getInstance(){
return instance;
}
/**
* Access a field of the class.
*
* @param bean the class to be processed.
* @param field the field within the class to be accessed.
* @param readOnly the isStatic value of the field's modifier.
* @return Accessor the accessor for this field
*
* @throws JAXBException reports failures of the method.
*/
public Accessor createFieldAccessor(Class bean, Field field, boolean readOnly) {
return readOnly
? new Accessor.ReadOnlyFieldReflection(field)
: new Accessor.FieldReflection(field);
}
/**
* Access a field of the class.
*
* @param bean the class to be processed.
* @param field the field within the class to be accessed.
* @param readOnly the isStatic value of the field's modifier.
* @param supressWarning supress security warning about accessing fields through reflection
* @return Accessor the accessor for this field
*
* @throws JAXBException reports failures of the method.
*/
public Accessor createFieldAccessor(Class bean, Field field, boolean readOnly, boolean supressWarning) {
return readOnly
? new Accessor.ReadOnlyFieldReflection(field, supressWarning)
: new Accessor.FieldReflection(field, supressWarning);
}
/**
* Access a property of the class.
*
* @param bean the class to be processed
* @param getter the getter method to be accessed. The value can be null.
* @param setter the setter method to be accessed. The value can be null.
* @return Accessor the accessor for these methods
*
* @throws JAXBException reports failures of the method.
*/
public Accessor createPropertyAccessor(Class bean, Method getter, Method setter) {
if (getter == null) {
return new Accessor.SetterOnlyReflection(setter);
}
if (setter == null) {
return new Accessor.GetterOnlyReflection(getter);
}
return new Accessor.GetterSetterReflection(getter, setter);
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* {@link XmlAdapter} useful for mapping interfaces.
*
* See <a href="https://jaxb.dev.java.net/guide/Mapping_interfaces.html">The JAXB user's guide</a>
* for more about this adapter class.
*
* @author Kohsuke Kawaguchi
* @since JAXB 2.1
*/
public final class AnyTypeAdapter extends XmlAdapter<Object,Object> {
/**
* Noop. Just returns the object given as the argument.
*/
public Object unmarshal(Object v) {
return v;
}
/**
* Noop. Just returns the object given as the argument.
*/
public Object marshal(Object v) {
return v;
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import javax.xml.bind.Marshaller;
/**
* Optional interface that can be implemented by JAXB-bound objects
* to handle cycles in the object graph.
*
* <p>
* As discussed in <a href="https://jaxb.dev.java.net/guide/Mapping_cyclic_references_to_XML.html">
* the users' guide</a>, normally a cycle in the object graph causes the marshaller to report an error,
* and when an error is found, the JAXB RI recovers by cutting the cycle arbitrarily.
* This is not always a desired behavior.
*
* <p>
* Implementing this interface allows user application to change this behavior.
* Also see <a href="http://forums.java.net/jive/thread.jspa?threadID=13670">this related discussion</a>.
*
* @since JAXB 2.1 EA2
* @author Kohsuke Kawaguchi
*/
public interface CycleRecoverable {
/**
* Called when a cycle is detected by the JAXB RI marshaller
* to nominate a new object to be marshalled instead.
*
* @param context
* This object is provided by the JAXB RI to inform
* the object about the marshalling process that's going on.
*
*
* @return
* the object to be marshalled instead of <tt>this</tt> object.
* Or return null to indicate that the JAXB RI should behave
* just like when your object does not implement {@link CycleRecoverable}
* (IOW, cut the cycle arbitrarily and try to go on.)
*/
Object onCycleDetected(Context context);
/**
* This interface is implemented by the JAXB RI to provide
* information about the on-going marshalling process.
*
* <p>
* We may add more methods in the future, so please do not
* implement this interface in your application.
*/
public interface Context {
/**
* Returns the marshaller object that's doing the marshalling.
*
* @return
* always non-null.
*/
Marshaller getMarshaller();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,160 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import java.util.concurrent.Callable;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.XmlIDREF;
import org.xml.sax.SAXException;
/**
* Pluggable ID/IDREF handling layer.
*
* <p>
* <b>THIS INTERFACE IS SUBJECT TO CHANGE WITHOUT NOTICE.</b>
*
* <p>
* This 'interface' can be implemented by applications and specified to
* {@link Unmarshaller#setProperty(String, Object)} to ovierride the ID/IDREF
* processing of the JAXB RI like this:
*
* <pre>
* unmarshaller.setProperty(IDResolver.class.getName(),new MyIDResolverImpl());
* </pre>
*
* <h2>Error Handling</h2>
* <p>
* This component runs inside the JAXB RI unmarshaller. Therefore, it needs
* to coordinate with the JAXB RI unmarshaller when it comes to reporting
* errors. This makes sure that applications see consistent error handling behaviors.
*
* <p>
* When the {@link #startDocument(ValidationEventHandler)} method is invoked,
* the unmarshaller passes in a {@link ValidationEventHandler} that can be used
* by this component to report any errors encountered during the ID/IDREF processing.
*
* <p>
* When an error is detected, the error should be first reported to this
* {@link ValidationEventHandler}. If the error is fatal or the event handler
* decided to abort, the implementation should throw a {@link SAXException}.
* This signals the unmarshaller to abort the processing.
*
* @author Kohsuke Kawaguchi
* @since JAXB 2.0 beta
*/
public abstract class IDResolver {
/**
* Called when the unmarshalling starts.
*
* <p>
* Since one {@link Unmarshaller} may be used multiple times
* to unmarshal documents, one {@link IDResolver} may be used multiple times, too.
*
* @param eventHandler
* Any errors found during the unmarshalling should be reported to this object.
*/
public void startDocument(ValidationEventHandler eventHandler) throws SAXException {
}
/**
* Called after the unmarshalling completes.
*
* <p>
* This is a good opporunity to reset any internal state of this object,
* so that it doesn't keep references to other objects unnecessarily.
*/
public void endDocument() throws SAXException {
}
/**
* Binds the given object to the specified ID.
*
* <p>
* While a document is being unmarshalled, every time
* an ID value is found, this method is invoked to
* remember the association between ID and objects.
* This association is supposed to be used later to resolve
* IDREFs.
*
* <p>
* This method is invoked right away as soon as a new ID value is found.
*
* @param id
* The ID value found in the document being unmarshalled.
* Always non-null.
* @param obj
* The object being unmarshalled which is going to own the ID.
* Always non-null.
*/
public abstract void bind( String id, Object obj ) throws SAXException;
/**
* Obtains the object to be pointed by the IDREF value.
*
* <p>
* While a document is being unmarshalled, every time
* an IDREF value is found, this method is invoked immediately to
* obtain the object that the IDREF is pointing to.
*
* <p>
* This method returns a {@link Callable} to support forward-references.
* When this method returns with a non-null return value,
* the JAXB RI unmarshaller invokes the {@link Callable#call()} method immediately.
* If the implementation can find the target object (in which case
* it was a backward reference), then a non-null object shall be returned,
* and it is used as the target object.
*
* <p>
* When a forward-reference happens, the <tt>call</tt> method
* should return null. In this case the JAXB RI unmarshaller invokes
* the <tt>call</tt> method again after all the documents are fully unmarshalled.
* If the <tt>call</tt> method still returns null, then the JAXB RI unmarshaller
* treats it as an error.
*
* <p>
* A {@link Callable} object returned from this method may not throw
* any exception other than a {@link SAXException} (which means a fatal error.)
*
* @param id
* The IDREF value found in the document being unmarshalled.
* Always non-null.
* @param targetType
* The expected type to which ID resolves to. JAXB infers this
* information from the signature of the fields that has {@link XmlIDREF}.
* When a property is a collection, this parameter will be the type
* of the individual item in the collection.
* @return
* null if the implementation is sure that the parameter combination
* will never yield a valid object. Otherwise non-null.
*/
public abstract Callable<?> resolve( String id, Class targetType ) throws SAXException;
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind;
import java.lang.reflect.Field;
import com.sun.xml.internal.bind.v2.runtime.reflect.Accessor;
import javax.xml.bind.JAXBException;
/**
* A means to allow the user to provide customized Accessor
* to be used by JAXB. Adds ability to suppress warnings.
*/
public interface InternalAccessorFactory extends AccessorFactory {
/**
* Access a field of the class.
*
* @param bean the class to be processed.
* @param f the field within the class to be accessed.
* @param readOnly the isStatic value of the field's modifier.
* @param supressWarnings suppress reflection warnings
* @return Accessor the accessor for this field
*
* @throws JAXBException reports failures of the method.
*/
Accessor createFieldAccessor(Class bean, Field f, boolean readOnly, boolean supressWarnings) throws JAXBException;
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import com.sun.xml.internal.bind.annotation.XmlLocation;
import org.xml.sax.Locator;
/**
* Optional interface implemented by JAXB objects to expose
* location information from which an object is unmarshalled.
*
* <p>
* This is used during JAXB RI 1.0.x.
* In JAXB 2.0, use {@link XmlLocation}.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*
* @since JAXB RI 1.0
*/
public interface Locatable {
/**
* @return
* null if the location information is unavaiable,
* or otherwise return a immutable valid {@link Locator}
* object.
*/
Locator sourceLocation();
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, 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 com.sun.xml.internal.bind;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Message resources
*/
enum Messages {
FAILED_TO_INITIALE_DATATYPE_FACTORY, // 0 args
;
private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
@Override
public String toString() {
return format();
}
public String format( Object... args ) {
return MessageFormat.format( rb.getString(name()), args );
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 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 com.sun.xml.internal.bind;
import java.util.logging.Logger;
/**
* @author Kohsuke Kawaguchi
*/
public final class Util {
private Util() {} // no instanciation
/**
* Gets the logger for the caller's class.
*
* @since 2.0
*/
public static Logger getClassLogger() {
try {
StackTraceElement[] trace = new Exception().getStackTrace();
return Logger.getLogger(trace[1].getClassName());
} catch( SecurityException e) {
return Logger.getLogger("com.sun.xml.internal.bind"); // use the default
}
}
/**
* Reads the system property value and takes care of {@link SecurityException}.
*/
public static String getSystemProperty(String name) {
try {
return System.getProperty(name);
} catch( SecurityException e ) {
return null;
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import javax.xml.bind.ValidationEventLocator;
/**
* Defines additional accessor methods for the event source location.
* <p>
* This interface exposes the location information only available
* in the JAXB RI specific extension.
* <p>
* <em>DO NOT IMPLEMENT THIS INTERFACE BY YOUR CODE</em> because
* we might add more methods on this interface in the future release
* of the RI.
*
* <h2>Usage</h2>
* <p>
* If you obtain a reference to {@link javax.xml.bind.ValidationEventLocator},
* check if you can cast it to {@link ValidationEventLocatorEx} first, like this:
* <pre>
* void foo( ValidationEvent e ) {
* ValidationEventLocator loc = e.getLocator();
* if( loc instanceof ValidationEventLocatorEx ) {
* String fieldName = ((ValidationEventLocatorEx)loc).getFieldName();
* if( fieldName!=null ) {
* // do something with location.
* }
* }
* }
* </pre>
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public interface ValidationEventLocatorEx extends ValidationEventLocator {
/**
* Returns the field name of the object where the error occured.
* <p>
* This method always returns null when you are doing
* a validation during unmarshalling.
*
* When not null, the field name indicates the field of the object
* designated by the {@link #getObject()} method where the error
* occured.
*/
String getFieldName();
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
/**
* Processes white space normalization.
*
* @since 1.0
*/
public 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 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 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 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,44 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Identifies a user provided customized Accessor
* to be used.
*/
@Retention(RUNTIME)
@Target({TYPE,PACKAGE})
public @interface XmlAccessorFactory {
Class<? extends AccessorFactory> value();
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Designates an annotation from base class which shall be overriden by annotation placed together with this.
*
* @author Martin Grebac
*/
@Retention(RUNTIME)
@Target({FIELD})
public @interface OverrideAnnotationOf {
String value() default "content";
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlValue;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Designates a boolean field/property as a flag to indicate
* whether another property is present or not.
*
* <p>
* Sometimes you'd want to map a Java primitive type to an
* optional element/attribute. Doing this makes it impossible
* to represent the absence of the property, thus you always
* end up producing the value when you marshal to XML.
*
* For example,
* <pre>
* {@link XmlElement}
* class Foo {
* {@link XmlElement}
* int x;
* }
*
* marshaller.marshal(new Foo());
* </pre>
* and you get:
* <pre><xmp>
* <foo><x>0</x></foo>
* </xmp></pre>
*
* <p>
* By creating a side boolean field/property that has this annotation,
* you can indicate the absence of the property by setting this boolean
* to false.
* <pre>
* {@link XmlElement}
* class Foo {
* {@link XmlElement}
* int x;
* {@link XmlIsSet}("x")
* boolean xIsPresent;
* }
*
* Foo f = new Foo();
* f.x = 5;
* f.xIsPresent = false;
*
* marshaller.marshal(f);
*
* <xmp>
* <foo/>
* </xmp>
*
* f.xIsPresent = true;
* <xmp>
* <foo><x>5</x></foo>
* </xmp>
* </pre>
*
* <p>
* A property/field annotated with {@link XmlIsSet} itself will not show up in XML.
* It is an error to use this annotation on the same property/field
* as {@link XmlElement}, {@link XmlAttribute}, {@link XmlValue}, or {@link XmlElementRef},
* ...<b>TBD</b>.
*
* @deprecated
* this hasn't been implemented in the RI, and this hasn't been speced yet.
* I believe Joe asked for this feature. I'd like to drop this.
*
* @author Kohsuke Kawaguchi
*/
@Retention(RUNTIME)
@Target({FIELD,METHOD})
public @interface XmlIsSet {
/**
* Specifies the name of the property to attach to.
*/
String value();
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.xml.sax.Locator;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
/**
* Marks a property that receives a location from which the object is unmarshalled.
*
* <h2>Usage</h2>
* <p>
* The @XmlLocation can be specified on:
* <ul>
* <li>a field whose type is {@link Locator}, or
* <li>a method that takes a {@link Locator} as the sole parameter
* </ul>
*
* <p>
* When a class that contains such a field/method is unmarshalled by the JAXB RI,
* such a field/method will receive an immutable {@link Locator} object that describes
* the location in the XML document where the object is unmarshalled from.
*
* <p>
* If the unmarshaller does not know the source location information, the locator
* will not be set. For example, this happens when it is unmarshalling from a DOM tree.
* This also happens if you use JAXB implementations other than the JAXB RI.
*
* <p>
* This information can be used by applications, for example to provide user-friendly
* error information.
*
*
* @author Kohsuke Kawaguchi
* @since JAXB RI 2.0 EA
*/
@Retention(RUNTIME) @Target({FIELD,METHOD})
public @interface XmlLocation {
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
/**
* Signals an error in {@link RawAccessor}.
*
* <p>
* This error is not reported to the user handler. Once reported
* the error should be wrapped into another exception.
*
* <p>
* This exception happens primarily when JAXB accesses the getter/setter
* method and it throws a checked exception.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @author Kohsuke Kawaguchi
*
* @since 2.0 EA1
*/
public final class AccessorException extends Exception {
public AccessorException() {
}
public AccessorException(String message) {
super(message);
}
public AccessorException(String message, Throwable cause) {
super(message, cause);
}
public AccessorException(Throwable cause) {
super(cause);
}
}

View File

@@ -0,0 +1,320 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.bind.attachment.AttachmentUnmarshaller;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.bind.v2.runtime.BridgeContextImpl;
import com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
/**
* Mini-marshaller/unmarshaller that is specialized for a particular
* element name and a type.
*
* <p>
* Instances of this class is stateless and multi-thread safe.
* They are reentrant.
*
* <p>
* All the marshal operation generates fragments.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @since JAXB 2.0 EA1
* @author Kohsuke Kawaguchi
*/
public abstract class Bridge<T> {
protected Bridge(JAXBContextImpl context) {
this.context = context;
}
protected final JAXBContextImpl context;
/**
* Gets the {@link JAXBRIContext} to which this object belongs.
*
* @since 2.1
*/
public @NotNull JAXBRIContext getContext() {
return context;
}
/**
*
* @throws JAXBException
* if there was an error while marshalling.
*
* @since 2.0 EA1
*/
public final void marshal(T object,XMLStreamWriter output) throws JAXBException {
marshal(object,output,null);
}
public final void marshal(T object,XMLStreamWriter output, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,output);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
public final void marshal(@NotNull BridgeContext context,T object,XMLStreamWriter output) throws JAXBException {
marshal( ((BridgeContextImpl)context).marshaller, object, output );
}
public abstract void marshal(@NotNull Marshaller m,T object,XMLStreamWriter output) throws JAXBException;
/**
* Marshals the specified type object with the implicit element name
* associated with this instance of {@link Bridge}.
*
* @param nsContext
* if this marshalling is done to marshal a subelement, this {@link NamespaceContext}
* represents in-scope namespace bindings available for that element. Can be null,
* in which case JAXB assumes no in-scope namespaces.
* @throws JAXBException
* if there was an error while marshalling.
*
* @since 2.0 EA1
*/
public void marshal(T object,OutputStream output, NamespaceContext nsContext) throws JAXBException {
marshal(object,output,nsContext,null);
}
/**
* @since 2.0.2
*/
public void marshal(T object,OutputStream output, NamespaceContext nsContext, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,output,nsContext);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
public final void marshal(@NotNull BridgeContext context,T object,OutputStream output, NamespaceContext nsContext) throws JAXBException {
marshal( ((BridgeContextImpl)context).marshaller, object, output, nsContext );
}
public abstract void marshal(@NotNull Marshaller m,T object,OutputStream output, NamespaceContext nsContext) throws JAXBException;
public final void marshal(T object,Node output) throws JAXBException {
Marshaller m = context.marshallerPool.take();
marshal(m,object,output);
context.marshallerPool.recycle(m);
}
public final void marshal(@NotNull BridgeContext context,T object,Node output) throws JAXBException {
marshal( ((BridgeContextImpl)context).marshaller, object, output );
}
public abstract void marshal(@NotNull Marshaller m,T object,Node output) throws JAXBException;
/**
* @since 2.0 EA4
*/
public final void marshal(T object, ContentHandler contentHandler) throws JAXBException {
marshal(object,contentHandler,null);
}
/**
* @since 2.0.2
*/
public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException {
Marshaller m = context.marshallerPool.take();
m.setAttachmentMarshaller(am);
marshal(m,object,contentHandler);
m.setAttachmentMarshaller(null);
context.marshallerPool.recycle(m);
}
public final void marshal(@NotNull BridgeContext context,T object, ContentHandler contentHandler) throws JAXBException {
marshal( ((BridgeContextImpl)context).marshaller, object, contentHandler );
}
public abstract void marshal(@NotNull Marshaller m,T object, ContentHandler contentHandler) throws JAXBException;
/**
* @since 2.0 EA4
*/
public final void marshal(T object, Result result) throws JAXBException {
Marshaller m = context.marshallerPool.take();
marshal(m,object,result);
context.marshallerPool.recycle(m);
}
public final void marshal(@NotNull BridgeContext context,T object, Result result) throws JAXBException {
marshal( ((BridgeContextImpl)context).marshaller, object, result );
}
public abstract void marshal(@NotNull Marshaller m,T object, Result result) throws JAXBException;
private T exit(T r, Unmarshaller u) {
u.setAttachmentUnmarshaller(null);
context.unmarshallerPool.recycle(u);
return r;
}
/**
* Unmarshals the specified type object.
*
* @param in
* the parser must be pointing at a start tag
* that encloses the XML type that this {@link Bridge} is
* instanciated for.
*
* @return
* never null.
*
* @throws JAXBException
* if there was an error while unmarshalling.
*
* @since 2.0 EA1
*/
public final @NotNull T unmarshal(@NotNull XMLStreamReader in) throws JAXBException {
return unmarshal(in,null);
}
/**
* @since 2.0.3
*/
public final @NotNull T unmarshal(@NotNull XMLStreamReader in, @Nullable AttachmentUnmarshaller au) throws JAXBException {
Unmarshaller u = context.unmarshallerPool.take();
u.setAttachmentUnmarshaller(au);
return exit(unmarshal(u,in),u);
}
public final @NotNull T unmarshal(@NotNull BridgeContext context, @NotNull XMLStreamReader in) throws JAXBException {
return unmarshal( ((BridgeContextImpl)context).unmarshaller, in );
}
public abstract @NotNull T unmarshal(@NotNull Unmarshaller u, @NotNull XMLStreamReader in) throws JAXBException;
/**
* Unmarshals the specified type object.
*
* @param in
* the parser must be pointing at a start tag
* that encloses the XML type that this {@link Bridge} is
* instanciated for.
*
* @return
* never null.
*
* @throws JAXBException
* if there was an error while unmarshalling.
*
* @since 2.0 EA1
*/
public final @NotNull T unmarshal(@NotNull Source in) throws JAXBException {
return unmarshal(in,null);
}
/**
* @since 2.0.3
*/
public final @NotNull T unmarshal(@NotNull Source in, @Nullable AttachmentUnmarshaller au) throws JAXBException {
Unmarshaller u = context.unmarshallerPool.take();
u.setAttachmentUnmarshaller(au);
return exit(unmarshal(u,in),u);
}
public final @NotNull T unmarshal(@NotNull BridgeContext context, @NotNull Source in) throws JAXBException {
return unmarshal( ((BridgeContextImpl)context).unmarshaller, in );
}
public abstract @NotNull T unmarshal(@NotNull Unmarshaller u, @NotNull Source in) throws JAXBException;
/**
* Unmarshals the specified type object.
*
* @param in
* the parser must be pointing at a start tag
* that encloses the XML type that this {@link Bridge} is
* instanciated for.
*
* @return
* never null.
*
* @throws JAXBException
* if there was an error while unmarshalling.
*
* @since 2.0 EA1
*/
public final @NotNull T unmarshal(@NotNull InputStream in) throws JAXBException {
Unmarshaller u = context.unmarshallerPool.take();
return exit(unmarshal(u,in),u);
}
public final @NotNull T unmarshal(@NotNull BridgeContext context, @NotNull InputStream in) throws JAXBException {
return unmarshal( ((BridgeContextImpl)context).unmarshaller, in );
}
public abstract @NotNull T unmarshal(@NotNull Unmarshaller u, @NotNull InputStream in) throws JAXBException;
/**
* Unmarshals the specified type object.
*
* @param n
* Node to be unmarshalled.
*
* @return
* never null.
*
* @throws JAXBException
* if there was an error while unmarshalling.
*
* @since 2.0 FCS
*/
public final @NotNull T unmarshal(@NotNull Node n) throws JAXBException {
return unmarshal(n,null);
}
/**
* @since 2.0.3
*/
public final @NotNull T unmarshal(@NotNull Node n, @Nullable AttachmentUnmarshaller au) throws JAXBException {
Unmarshaller u = context.unmarshallerPool.take();
u.setAttachmentUnmarshaller(au);
return exit(unmarshal(u,n),u);
}
public final @NotNull T unmarshal(@NotNull BridgeContext context, @NotNull Node n) throws JAXBException {
return unmarshal( ((BridgeContextImpl)context).unmarshaller, n );
}
public abstract @NotNull T unmarshal(@NotNull Unmarshaller context, @NotNull Node n) throws JAXBException;
/**
* Gets the {@link TypeReference} from which this bridge was created.
*/
public abstract TypeReference getTypeReference();
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.bind.attachment.AttachmentUnmarshaller;
/**
* Holds thread specific state information for {@link Bridge}s,
* to make {@link Bridge} thread-safe.
*
* <p>
* This object cannot be used concurrently; two threads cannot
* use the same object with {@link Bridge}s at the same time, nor
* a thread can use a {@link BridgeContext} with one {@link Bridge} while
* the same context is in use by another {@link Bridge}.
*
* <p>
* {@link BridgeContext} is relatively a heavy-weight object, and
* therefore it is expected to be cached by the JAX-RPC RI.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @author Kohsuke Kawaguchi
* @since 2.0 EA1
* @see Bridge
* @deprecated
* The caller no longer needs to use this, as {@link Bridge} has
* methods that can work without {@link BridgeContext}.
*/
public abstract class BridgeContext {
protected BridgeContext() {}
/**
* Registers the error handler that receives unmarshalling/marshalling errors.
*
* @param handler
* can be null, in which case all errors will be considered fatal.
*
* @since 2.0 EA1
*/
public abstract void setErrorHandler(ValidationEventHandler handler);
/**
* Sets the {@link AttachmentMarshaller}.
*
* @since 2.0 EA1
*/
public abstract void setAttachmentMarshaller(AttachmentMarshaller m);
/**
* Sets the {@link AttachmentUnmarshaller}.
*
* @since 2.0 EA1
*/
public abstract void setAttachmentUnmarshaller(AttachmentUnmarshaller m);
/**
* Gets the last {@link AttachmentMarshaller} set through
* {@link AttachmentMarshaller}.
*
* @since 2.0 EA2
*/
public abstract AttachmentMarshaller getAttachmentMarshaller();
/**
* Gets the last {@link AttachmentUnmarshaller} set through
* {@link AttachmentUnmarshaller}.
*
* @since 2.0 EA2
*/
public abstract AttachmentUnmarshaller getAttachmentUnmarshaller();
}

View File

@@ -0,0 +1,104 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.XmlAnyElement;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
/**
* Dynamically locates classes to represent elements discovered during the unmarshalling.
*
* <p>
* <b>THIS INTERFACE IS SUBJECT TO CHANGE WITHOUT NOTICE.</b>
*
* <h2>Background</h2>
* <p>
* {@link JAXBContext#newInstance(Class...)} requires that application informs JAXB
* about all the classes that it may see in the instance document. While this allows
* JAXB to take time to optimize the unmarshalling, it is sometimes inconvenient
* for applications.
*
* <p>
* This is where {@link ClassResolver} comes to resucue.
*
* <p>
* A {@link ClassResolver} instance can be specified on {@link Unmarshaller} via
* {@link Unmarshaller#setProperty(String, Object)} as follows:
*
* <pre>
* unmarshaller.setProperty( ClassResolver.class.getName(), new MyClassResolverImpl() );
* </pre>
*
* <p>
* When an {@link Unmarshaller} encounters (i) an unknown root element or (ii) unknown
* elements where unmarshaller is trying to unmarshal into {@link XmlAnyElement} with
* <tt>lax=true</tt>, unmarshaller calls {@link #resolveElementName(String, String)}
* method to see if the application may be able to supply a class that corresponds
* to that class.
*
* <p>
* When a {@link Class} is returned, a new {@link JAXBContext} is created with
* all the classes known to it so far, plus a new class returned. This operation
* may fail (for example because of some conflicting annotations.) This failure
* is handled just like {@link Exception}s thrown from
* {@link ClassResolver#resolveElementName(String, String)}.
*
* @author Kohsuke Kawaguchi
* @since 2.1
*/
public abstract class ClassResolver {
/**
* JAXB calls this method when it sees an unknown element.
*
* <p>
* See the class javadoc for details.
*
* @param nsUri
* Namespace URI of the unknown element. Can be empty but never null.
* @param localName
* Local name of the unknown element. Never be empty nor null.
*
* @return
* If a non-null class is returned, it will be used to unmarshal this element.
* If null is returned, the resolution is assumed to be failed, and
* the unmarshaller will behave as if there was no {@link ClassResolver}
* to begin with (that is, to report it to {@link ValidationEventHandler},
* then move on.)
*
* @throws Exception
* Throwing any {@link RuntimeException} causes the unmarshaller to stop
* immediately. The exception will be propagated up the call stack.
* Throwing any other checked {@link Exception} results in the error
* reproted to {@link ValidationEventHandler} (just like any other error
* during the unmarshalling.)
*/
public abstract @Nullable Class<?> resolveElementName(@NotNull String nsUri, @NotNull String localName) throws Exception;
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
/**
* A JAXB Bean that works like a DOM.
*
* <p>
* This bean is bound to XML as a sequence of elements, where each
* element[i] is from bridges[i] (which defines the tag name and the expected type)
* and values[i] (which defines the actual value.)
*
* <p>
* This object allows you to treat multiple unrelated JAXB beans as a single tree.
* This in turn allows you to marshal this tree in one marshal method invocation,
* which is faster than multiple invocations of the marshal method.
*
* <p>
* The binding of this class is always known to {@link JAXBRIContext}, so it can be
* used without passing anything to {@link JAXBRIContext#newInstance}.
* This object can be only used for marshalling, not for unmarshalling.
*
* @author Kohsuke Kawaguchi
*/
public class CompositeStructure {
public Bridge[] bridges;
public Object[] values;
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
/**
* Implemented by the driver of the compiler engine to handle
* errors found during the compiliation.
*
* <p>
* This class implements {@link ErrorHandler} so it can be
* passed to anywhere where {@link ErrorHandler} is expected.
*
* <p>
* However, to make the error handling easy (and make it work
* with visitor patterns nicely), this interface is not allowed
* to abort the processing. It merely receives errors.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* @since 2.1 EA2
*/
public interface ErrorListener extends ErrorHandler {
void error(SAXParseException exception);
void fatalError(SAXParseException exception);
void warning(SAXParseException exception);
/**
* Used to report possibly verbose information that
* can be safely ignored.
*/
void info(SAXParseException exception);
}

View File

@@ -0,0 +1,537 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.api;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.bind.annotation.XmlAttachmentRef;
import javax.xml.namespace.QName;
import javax.xml.transform.Result;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.bind.api.impl.NameConverter;
import com.sun.xml.internal.bind.v2.ContextFactory;
import com.sun.xml.internal.bind.v2.model.annotation.RuntimeAnnotationReader;
import com.sun.xml.internal.bind.v2.model.runtime.RuntimeTypeInfoSet;
import java.util.HashMap;
/**
* {@link JAXBContext} enhanced with JAXB RI specific functionalities.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @since 2.0 EA1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public abstract class JAXBRIContext extends JAXBContext {
protected JAXBRIContext() {}
/**
* Creates a new {@link JAXBRIContext}.
*
* <p>
* {@link JAXBContext#newInstance(Class[]) JAXBContext.newInstance()} methods may
* return other JAXB providers that are not compatible with the JAX-RPC RI.
* This method guarantees that the JAX-WS RI will finds the JAXB RI.
*
* @param classes
* Classes to be bound. See {@link JAXBContext#newInstance(Class[])} for the meaning.
* @param typeRefs
* See {@link #TYPE_REFERENCES} for the meaning of this parameter.
* Can be null.
* @param subclassReplacements
* See {@link #SUBCLASS_REPLACEMENTS} for the meaning of this parameter.
* Can be null.
* @param defaultNamespaceRemap
* See {@link #DEFAULT_NAMESPACE_REMAP} for the meaning of this parameter.
* Can be null (and should be null for ordinary use of JAXB.)
* @param c14nSupport
* See {@link #CANONICALIZATION_SUPPORT} for the meaning of this parameter.
* @param ar
* See {@link #ANNOTATION_READER} for the meaning of this parameter.
* Can be null.
* @since JAXB 2.1 EA2
*/
public static JAXBRIContext newInstance(@NotNull Class[] classes,
@Nullable Collection<TypeReference> typeRefs,
@Nullable Map<Class,Class> subclassReplacements,
@Nullable String defaultNamespaceRemap, boolean c14nSupport,
@Nullable RuntimeAnnotationReader ar) throws JAXBException {
return newInstance(classes, typeRefs, subclassReplacements,
defaultNamespaceRemap, c14nSupport, ar, false, false, false, false);
}
/**
* Creates a new {@link JAXBRIContext}.
*
* <p>
* {@link JAXBContext#newInstance(Class[]) JAXBContext.newInstance()} methods may
* return other JAXB providers that are not compatible with the JAX-RPC RI.
* This method guarantees that the JAX-WS RI will finds the JAXB RI.
*
* @param classes
* Classes to be bound. See {@link JAXBContext#newInstance(Class[])} for the meaning.
* @param typeRefs
* See {@link #TYPE_REFERENCES} for the meaning of this parameter.
* Can be null.
* @param subclassReplacements
* See {@link #SUBCLASS_REPLACEMENTS} for the meaning of this parameter.
* Can be null.
* @param defaultNamespaceRemap
* See {@link #DEFAULT_NAMESPACE_REMAP} for the meaning of this parameter.
* Can be null (and should be null for ordinary use of JAXB.)
* @param c14nSupport
* See {@link #CANONICALIZATION_SUPPORT} for the meaning of this parameter.
* @param ar
* See {@link #ANNOTATION_READER} for the meaning of this parameter.
* Can be null.
* @param xmlAccessorFactorySupport
* See {@link #XMLACCESSORFACTORY_SUPPORT} for the meaning of this parameter.
* @param allNillable
* See {@link #TREAT_EVERYTHING_NILLABLE} for the meaning of this parameter.
* @param retainPropertyInfo
* See {@link #RETAIN_REFERENCE_TO_INFO} for the meaning of this parameter.
* @param supressAccessorWarnings
* See {@link #SUPRESS_ACCESSOR_WARNINGS} for the meaning of this parameter.
*/
public static JAXBRIContext newInstance(@NotNull Class[] classes,
@Nullable Collection<TypeReference> typeRefs,
@Nullable Map<Class,Class> subclassReplacements,
@Nullable String defaultNamespaceRemap, boolean c14nSupport,
@Nullable RuntimeAnnotationReader ar,
boolean xmlAccessorFactorySupport,
boolean allNillable,
boolean retainPropertyInfo,
boolean supressAccessorWarnings) throws JAXBException {
Map<String, Object> properties = new HashMap<String, Object>();
if (typeRefs != null) properties.put(JAXBRIContext.TYPE_REFERENCES, typeRefs);
if (subclassReplacements != null) properties.put(JAXBRIContext.SUBCLASS_REPLACEMENTS, subclassReplacements);
if (defaultNamespaceRemap != null) properties.put(JAXBRIContext.DEFAULT_NAMESPACE_REMAP, defaultNamespaceRemap);
if (ar != null) properties.put(JAXBRIContext.ANNOTATION_READER, ar);
properties.put(JAXBRIContext.CANONICALIZATION_SUPPORT, Boolean.valueOf(c14nSupport));
properties.put(JAXBRIContext.XMLACCESSORFACTORY_SUPPORT, Boolean.valueOf(xmlAccessorFactorySupport));
properties.put(JAXBRIContext.TREAT_EVERYTHING_NILLABLE, Boolean.valueOf(allNillable));
properties.put(JAXBRIContext.RETAIN_REFERENCE_TO_INFO, Boolean.valueOf(retainPropertyInfo));
properties.put(JAXBRIContext.SUPRESS_ACCESSOR_WARNINGS, Boolean.valueOf(supressAccessorWarnings));
return (JAXBRIContext) ContextFactory.createContext(classes, properties);
}
/**
* @deprecated
* Compatibility with older versions.
*/
public static JAXBRIContext newInstance(@NotNull Class[] classes,
@Nullable Collection<TypeReference> typeRefs,
@Nullable String defaultNamespaceRemap, boolean c14nSupport ) throws JAXBException {
return newInstance(classes,typeRefs, Collections.<Class,Class>emptyMap(),
defaultNamespaceRemap,c14nSupport,null);
}
/**
* Returns true if this context includes a class
* that has {@link XmlAttachmentRef}.
*
* @since 2.1
*/
public abstract boolean hasSwaRef();
/**
* If the given object is bound to an element in XML by JAXB,
* returns the element name.
*
* @return null
* if the object is not bound to an element.
* @throws JAXBException
* if the object is not known to this context.
*
* @since 2.0 EA1
*/
public abstract @Nullable QName getElementName(@NotNull Object o) throws JAXBException;
/**
* Allows to retrieve the element name based on Class.
* @param o
* @return
* @throws javax.xml.bind.JAXBException
* @since 2.1.10
*/
public abstract @Nullable QName getElementName(@NotNull Class o) throws JAXBException;
/**
* Creates a mini-marshaller/unmarshaller that can process a {@link TypeReference}.
*
* @return
* null if the specified reference is not given to {@link JAXBRIContext#newInstance}.
*
* @since 2.0 EA1
*/
public abstract Bridge createBridge(@NotNull TypeReference ref);
/**
* Creates a new {@link BridgeContext} instance.
*
* @return
* always a valid non-null instance.
*
* @since 2.0 EA1
*/
public abstract @NotNull BridgeContext createBridgeContext();
/**
* Gets a {@link RawAccessor} for the specified element property of the specified wrapper bean class.
*
* <p>
* This method is designed to assist the JAX-RPC RI fill in a wrapper bean (in the doc/lit/wrap mode.)
* In the said mode, a wrapper bean is supposed to only have properties that match elements,
* and for each element that appear in the content model there's one property.
*
* <p>
* Therefore, this method takes a wrapper bean and a tag name that identifies a property
* on the given wrapper bean, then returns a {@link RawAccessor} that allows the caller
* to set/get a value from the property of the bean.
*
* <p>
* This method is not designed for a performance. The caller is expected to cache the result.
*
* @param <B>
* type of the wrapper bean
* @param <V>
* type of the property of the bean
* @return
* always return non-null valid accessor object.
* @throws JAXBException
* if the specified wrapper bean is not bound by JAXB, or if it doesn't have an element property
* of the given name.
*
* @since 2.0 EA1
*/
public abstract <B,V> RawAccessor<B,V> getElementPropertyAccessor( Class<B> wrapperBean, String nsUri, String localName )
throws JAXBException;
/**
* Gets the namespace URIs statically known to this {@link JAXBContext}.
*
* <p>
* When JAXB is used to marshal into sub-trees, it declares
* these namespace URIs at each top-level element that it marshals.
*
* To avoid repeated namespace declarations at sub-elements, the application
* may declare those namespaces at a higher level.
*
* @return
* always non-null.
*
* @since 2.0 EA2
*/
public abstract @NotNull List<String> getKnownNamespaceURIs();
/**
* Generates the schema documents from the model.
*
* <p>
* The caller can use the additionalElementDecls parameter to
* add element declarations to the generate schema.
* For example, if the JAX-RPC passes in the following entry:
*
* {foo}bar -> DeclaredType for java.lang.String
*
* then JAXB generates the following element declaration (in the schema
* document for the namespace "foo")"
*
* &lt;xs:element name="bar" type="xs:string" />
*
* This can be used for generating schema components necessary for WSDL.
*
* @param outputResolver
* this object controls the output to which schemas
* will be sent.
*
* @throws IOException
* if {@link SchemaOutputResolver} throws an {@link IOException}.
*/
@Override
public abstract void generateSchema(@NotNull SchemaOutputResolver outputResolver) throws IOException;
/**
* Returns the name of the XML Type bound to the
* specified Java type.
*
* @param tr
* must not be null. This must be one of the {@link TypeReference}s specified
* in the {@link JAXBRIContext#newInstance} method.
*
* @throws IllegalArgumentException
* if the parameter is null or not a part of the {@link TypeReference}s specified
* in the {@link JAXBRIContext#newInstance} method.
*
* @return null
* if the referenced type is an anonymous and therefore doesn't have a name.
*/
public abstract QName getTypeName(@NotNull TypeReference tr);
/**
* Gets the build information of the JAXB runtime.
*
* @return
* may be null, if the runtime is loaded by a class loader that doesn't support
* the access to the manifest informatino.
*/
public abstract @NotNull String getBuildId();
/**
* Generates the episode file that represents the binding known to this {@link JAXBContext},
* so that XJC can later do separate compilation.
*
* <p>
* Episode file is really just a JAXB customization file, except that currently
* we use the RI-specific SCD to refer to schema components.
*
* @param output
* This receives the generated episode file.
*
* @since 2.1
*/
public abstract void generateEpisode(Result output);
/**
* Allows you to access the runtime model information of the JAXB XML/Java binding.
*
* <p>
* This is useful for doing a deeper integration with the JAXB RI.
* For more information about the model, see https://jaxb2-reflection.dev.java.net/
*
* @since 2.1.10
*/
public abstract RuntimeTypeInfoSet getRuntimeTypeInfoSet();
/**
* Computes a Java identifier from a local name.
*
* <p>
* This method faithfully implements the name mangling rule as specified in the JAXB spec.
*
* <p>
* In JAXB, a collision with a Java reserved word (such as "return") never happens.
* Accordingly, this method may return an identifier that collides with reserved words.
*
* <p>
* Use <tt>JJavaName.isJavaIdentifier(String)</tt> to check for such collision.
*
* @return
* Typically, this method returns "nameLikeThis".
*/
public static @NotNull String mangleNameToVariableName(@NotNull String localName) {
return NameConverter.standard.toVariableName(localName);
}
/**
* Computes a Java class name from a local name.
*
* <p>
* This method faithfully implements the name mangling rule as specified in the JAXB spec.
*
* @return
* Typically, this method returns "NameLikeThis".
*/
public static @NotNull String mangleNameToClassName(@NotNull String localName) {
return NameConverter.standard.toClassName(localName);
}
/**
* Computes a Java class name from a local name.
*
* <p>
* This method faithfully implements the name mangling rule as specified in the JAXB spec.
* This method works like {@link #mangleNameToClassName(String)} except that it looks
* for "getClass" and returns something else.
*
* @return
* Typically, this method returns "NameLikeThis".
*/
public static @NotNull String mangleNameToPropertyName(@NotNull String localName) {
return NameConverter.standard.toPropertyName(localName);
}
/**
* Gets the parameterization of the given base type.
*
* <p>
* For example, given the following
* <pre><xmp>
* interface Foo<T> extends List<List<T>> {}
* interface Bar extends Foo<String> {}
* </xmp></pre>
* This method works like this:
* <pre><xmp>
* getBaseClass( Bar, List ) = List<List<String>
* getBaseClass( Bar, Foo ) = Foo<String>
* getBaseClass( Foo<? extends Number>, Collection ) = Collection<List<? extends Number>>
* getBaseClass( ArrayList<? extends BigInteger>, List ) = List<? extends BigInteger>
* </xmp></pre>
*
* @param type
* The type that derives from {@code baseType}
* @param baseType
* The class whose parameterization we are interested in.
* @return
* The use of {@code baseType} in {@code type}.
* or null if the type is not assignable to the base type.
* @since 2.0 FCS
*/
public static @Nullable Type getBaseType(@NotNull Type type, @NotNull Class baseType) {
return Utils.REFLECTION_NAVIGATOR.getBaseClass(type, baseType);
}
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* to reassign the default namespace URI to something else at the runtime.
*
* <p>
* The value of the property is {@link String}, and it is used as the namespace URI
* that succeeds the default namespace URI.
*
* @since 2.0 EA1
*/
public static final String DEFAULT_NAMESPACE_REMAP = "com.sun.xml.internal.bind.defaultNamespaceRemap";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* to put additional JAXB type references into the {@link JAXBContext}.
*
* <p>
* The value of the property is {@link Collection}&lt;{@link TypeReference}>.
* Those {@link TypeReference}s can then be used to create {@link Bridge}s.
*
* <p>
* This mechanism allows additional element declarations that were not a part of
* the schema into the created {@link JAXBContext}.
*
* @since 2.0 EA1
*/
public static final String TYPE_REFERENCES = "com.sun.xml.internal.bind.typeReferences";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* and {@link Marshaller#setProperty(String, Object)}
* to enable the c14n marshalling support in the {@link JAXBContext}.
*
* Boolean
* @see C14nSupport_ArchitectureDocument
* @since 2.0 EA2
*/
public static final String CANONICALIZATION_SUPPORT = "com.sun.xml.internal.bind.c14n";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* to allow unmarshaller to honor <tt>xsi:nil</tt> anywhere, even if they are
* not specifically allowed by the schema.
*
* Boolean
* @since 2.1.3
*/
public static final String TREAT_EVERYTHING_NILLABLE = "com.sun.xml.internal.bind.treatEverythingNillable";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* to use alternative {@link RuntimeAnnotationReader} implementation.
*
* @since 2.1 EA2
*/
public static final String ANNOTATION_READER = RuntimeAnnotationReader.class.getName();
/**
* Marshaller/Unmarshaller property to enable XOP processing.
*
* @since 2.0 EA2
*/
public static final String ENABLE_XOP = "com.sun.xml.internal.bind.XOP";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* to specify specific classes that replace the reference to generic classes.
*
* <p>
* See the release notes for more details about this feature.
*
* @since 2.1 EA2
*/
public static final String SUBCLASS_REPLACEMENTS = "com.sun.xml.internal.bind.subclassReplacements";
/**
* The property that you can specify to {@link JAXBContext#newInstance}
* enable support of XmlAccessorFactory annotation in the {@link JAXBContext}.
*
* @since 2.1 EA2
*/
public static final String XMLACCESSORFACTORY_SUPPORT = "com.sun.xml.internal.bind.XmlAccessorFactory";
/**
* Retains references to PropertyInfos.
*
* Boolean
* @since 2.1.10
*/
public static final String RETAIN_REFERENCE_TO_INFO = "retainReferenceToInfo";
/**
* Supress security warnings when trying to access fields through reflection.
*
* Boolean
* @since 2.1.14, 2.2.2
*/
public static final String SUPRESS_ACCESSOR_WARNINGS = "supressAccessorWarnings";
/**
* Improves handling of xsi:type used on leaf properties.
*
* Boolean
* @since 2.2.3
*/
public static final String IMPROVED_XSI_TYPE_HANDLING = "com.sun.xml.internal.bind.improvedXsiTypeHandling";
/**
* If true XML security features when parsing XML documents will be disabled.
* The default value is false.
*
* Boolean
* @since 2.2.6
*/
public static final String DISABLE_XML_SECURITY = "com.sun.xml.internal.bind.disableXmlSecurity";
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*
* @since JAXB2.1.10
*/
enum Messages {
// TypeReference
ARGUMENT_CANT_BE_NULL
;
private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
@Override
public String toString() {
return format();
}
public String format( Object... args ) {
return MessageFormat.format( rb.getString(name()), args );
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
/**
* Accesses a particular property of a bean.
*
* <p>
* This interface allows JAX-RPC to access an element property of a JAXB bean.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @author Kohsuke Kawaguchi
*
* @since 2.0 EA1
*/
public abstract class RawAccessor<B,V> {
/**
* Gets the value of the property of the given bean object.
*
* @param bean
* must not be null.
* @throws AccessorException
* if failed to set a value. For example, the getter method
* may throw an exception.
*
* @since 2.0 EA1
*/
public abstract V get(B bean) throws AccessorException;
/**
* Sets the value of the property of the given bean object.
*
* @param bean
* must not be null.
* @param value
* the value to be set. Setting value to null means resetting
* to the VM default value (even for primitive properties.)
* @throws AccessorException
* if failed to set a value. For example, the setter method
* may throw an exception.
*
* @since 2.0 EA1
*/
public abstract void set(B bean,V value) throws AccessorException;
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.namespace.QName;
/**
* A reference to a JAXB-bound type.
*
* <p>
* <b>Subject to change without notice</b>.
*
* @since 2.0 EA1
* @author Kohsuke Kawaguchi
*/
public final class TypeReference {
/**
* The associated XML element name that the JAX-RPC uses with this type reference.
*
* Always non-null. Strings are interned.
*/
public final QName tagName;
/**
* The Java type that's being referenced.
*
* Always non-null.
*/
public final Type type;
/**
* The annotations associated with the reference of this type.
*
* Always non-null.
*/
public final Annotation[] annotations;
public TypeReference(QName tagName, Type type, Annotation... annotations) {
if(tagName==null || type==null || annotations==null) {
String nullArgs = "";
if(tagName == null) nullArgs = "tagName";
if(type == null) nullArgs += (nullArgs.length() > 0 ? ", type" : "type");
if(annotations == null) nullArgs += (nullArgs.length() > 0 ? ", annotations" : "annotations");
Messages.ARGUMENT_CANT_BE_NULL.format(nullArgs);
throw new IllegalArgumentException(Messages.ARGUMENT_CANT_BE_NULL.format(nullArgs));
}
this.tagName = new QName(tagName.getNamespaceURI().intern(), tagName.getLocalPart().intern(), tagName.getPrefix());
this.type = type;
this.annotations = annotations;
}
/**
* Finds the specified annotation from the array and returns it.
* Null if not found.
*/
public <A extends Annotation> A get( Class<A> annotationType ) {
for (Annotation a : annotations) {
if(a.annotationType()==annotationType)
return annotationType.cast(a);
}
return null;
}
/**
* Creates a {@link TypeReference} for the item type,
* if this {@link TypeReference} represents a collection type.
* Otherwise returns an identical type.
*/
public TypeReference toItemType() {
// if we are to reinstitute this check, check JAXB annotations only
// assert annotations.length==0; // not designed to work with adapters.
Type base = Utils.REFLECTION_NAVIGATOR.getBaseClass(type, Collection.class);
if(base==null)
return this; // not a collection
return new TypeReference(tagName, Utils.REFLECTION_NAVIGATOR.getTypeArgument(base,0));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeReference that = (TypeReference) o;
if (!Arrays.equals(annotations, that.annotations)) return false;
if (!tagName.equals(that.tagName)) return false;
if (!type.equals(that.type)) return false;
return true;
}
@Override
public int hashCode() {
int result = tagName.hashCode();
result = 31 * result + type.hashCode();
result = 31 * result + Arrays.hashCode(annotations);
return result;
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2013, 2014, 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 com.sun.xml.internal.bind.api;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utils class.
*
* WARNING: If you are doing any changes don't forget to change other Utils classes in different packages.
*
* Has *package private* access to avoid inappropriate usage.
*/
final class Utils {
private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());
/**
* static ReflectionNavigator field to avoid usage of reflection every time we use it.
*/
static final Navigator<Type, Class, Field, Method> REFLECTION_NAVIGATOR;
static { // we statically initializing REFLECTION_NAVIGATOR property
try {
final Class refNav = Class.forName("com.sun.xml.internal.bind.v2.model.nav.ReflectionNavigator");
// requires accessClassInPackage privilege
final Method getInstance = AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Method run() {
try {
Method getInstance = refNav.getDeclaredMethod("getInstance");
getInstance.setAccessible(true);
return getInstance;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance can't be found");
}
}
}
);
//noinspection unchecked
REFLECTION_NAVIGATOR = (Navigator<Type, Class, Field, Method>) getInstance.invoke(null);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Can't find ReflectionNavigator class");
} catch (InvocationTargetException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance throws the exception");
} catch (IllegalAccessException e) {
throw new IllegalStateException("ReflectionNavigator.getInstance method is inaccessible");
} catch (SecurityException e) {
LOGGER.log(Level.FINE, "Unable to access ReflectionNavigator.getInstance", e);
throw e;
}
}
/**
* private constructor to avoid util class instantiating
*/
private Utils() {
}
}

View File

@@ -0,0 +1,269 @@
/*
* Copyright (c) 1997, 2010, 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 com.sun.xml.internal.bind.api.impl;
import javax.lang.model.SourceVersion;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Converts aribitrary strings into Java identifiers.
*
* @author
* <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
*/
public interface NameConverter
{
/**
* converts a string into an identifier suitable for classes.
*
* In general, this operation should generate "NamesLikeThis".
*/
String toClassName( String token );
/**
* converts a string into an identifier suitable for interfaces.
*
* In general, this operation should generate "NamesLikeThis".
* But for example, it can prepend every interface with 'I'.
*/
String toInterfaceName( String token );
/**
* converts a string into an identifier suitable for properties.
*
* In general, this operation should generate "NamesLikeThis",
* which will be used with known prefixes like "get" or "set".
*/
String toPropertyName( String token );
/**
* converts a string into an identifier suitable for constants.
*
* In the standard Java naming convention, this operation should
* generate "NAMES_LIKE_THIS".
*/
String toConstantName( String token );
/**
* Converts a string into an identifier suitable for variables.
*
* In general it should generate "namesLikeThis".
*/
String toVariableName( String token );
/**
* Converts a namespace URI into a package name.
* This method should expect strings like
* "http://foo.bar.zot/org", "urn:abc:def:ghi" "", or even "###"
* (basically anything) and expected to return a package name,
* liks "org.acme.foo".
*
*/
String toPackageName( String namespaceUri );
/**
* The name converter implemented by Code Model.
*
* This is the standard name conversion for JAXB.
*/
public static final NameConverter standard = new Standard();
static class Standard extends NameUtil implements NameConverter {
public String toClassName(String s) {
return toMixedCaseName(toWordList(s), true);
}
public String toVariableName(String s) {
return toMixedCaseName(toWordList(s), false);
}
public String toInterfaceName( String token ) {
return toClassName(token);
}
public String toPropertyName(String s) {
String prop = toClassName(s);
// property name "Class" with collide with Object.getClass,
// so escape this.
if(prop.equals("Class"))
prop = "Clazz";
return prop;
}
public String toConstantName( String token ) {
return super.toConstantName(token);
}
/**
* Computes a Java package name from a namespace URI,
* as specified in the spec.
*
* @return
* null if it fails to derive a package name.
*/
public String toPackageName( String nsUri ) {
// remove scheme and :, if present
// spec only requires us to remove 'http' and 'urn'...
int idx = nsUri.indexOf(':');
String scheme = "";
if(idx>=0) {
scheme = nsUri.substring(0,idx);
if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") )
nsUri = nsUri.substring(idx+1);
}
// tokenize string
ArrayList<String> tokens = tokenize( nsUri, "/: " );
if( tokens.size() == 0 ) {
return null;
}
// remove trailing file type, if necessary
if( tokens.size() > 1 ) {
// for uri's like "www.foo.com" and "foo.com", there is no trailing
// file, so there's no need to look at the last '.' and substring
// otherwise, we loose the "com" (which would be wrong)
String lastToken = tokens.get( tokens.size()-1 );
idx = lastToken.lastIndexOf( '.' );
if( idx > 0 ) {
lastToken = lastToken.substring( 0, idx );
tokens.set( tokens.size()-1, lastToken );
}
}
// tokenize domain name and reverse. Also remove :port if it exists
String domain = tokens.get( 0 );
idx = domain.indexOf(':');
if( idx >= 0) domain = domain.substring(0, idx);
ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) );
if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) {
// remove leading www
r.remove( r.size()-1 );
}
// replace the domain name with tokenized items
tokens.addAll( 1, r );
tokens.remove( 0 );
// iterate through the tokens and apply xml->java name algorithm
for( int i = 0; i < tokens.size(); i++ ) {
// get the token and remove illegal chars
String token = tokens.get( i );
token = removeIllegalIdentifierChars( token );
// this will check for reserved keywords
if (SourceVersion.isKeyword(token.toLowerCase())) {
token = '_' + token;
}
tokens.set( i, token.toLowerCase() );
}
// concat all the pieces and return it
return combine( tokens, '.' );
}
private static String removeIllegalIdentifierChars(String token) {
StringBuilder newToken = new StringBuilder(token.length() + 1); // max expected length
for( int i = 0; i < token.length(); i++ ) {
char c = token.charAt( i );
if (i == 0 && !Character.isJavaIdentifierStart(c)) { // c can't be used as FIRST char
newToken.append('_');
}
if (!Character.isJavaIdentifierPart(c)) { // c can't be used
newToken.append('_');
} else {
newToken.append(c); // c is valid
}
}
return newToken.toString();
}
private static ArrayList<String> tokenize( String str, String sep ) {
StringTokenizer tokens = new StringTokenizer(str,sep);
ArrayList<String> r = new ArrayList<String>();
while(tokens.hasMoreTokens())
r.add( tokens.nextToken() );
return r;
}
private static <T> ArrayList<T> reverse( List<T> a ) {
ArrayList<T> r = new ArrayList<T>();
for( int i=a.size()-1; i>=0; i-- )
r.add( a.get(i) );
return r;
}
private static String combine( List r, char sep ) {
StringBuilder buf = new StringBuilder(r.get(0).toString());
for( int i=1; i<r.size(); i++ ) {
buf.append(sep);
buf.append(r.get(i));
}
return buf.toString();
}
}
/**
* JAX-PRC compatible name converter implementation.
*
* The only difference is that we treat '_' as a valid character
* and not as a word separator.
*/
public static final NameConverter jaxrpcCompatible = new Standard() {
protected boolean isPunct(char c) {
return (c == '.' || c == '-' || c == ';' /*|| c == '_'*/ || c == '\u00b7'
|| c == '\u0387' || c == '\u06dd' || c == '\u06de');
}
protected boolean isLetter(char c) {
return super.isLetter(c) || c=='_';
}
protected int classify(char c0) {
if(c0=='_') return NameUtil.OTHER_LETTER;
return super.classify(c0);
}
};
/**
* Smarter converter used for RELAX NG support.
*/
public static final NameConverter smart = new Standard() {
public String toConstantName( String token ) {
String name = super.toConstantName(token);
if(!SourceVersion.isKeyword(name))
return name;
else
return '_'+name;
}
};
}

View File

@@ -0,0 +1,328 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.api.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
/**
* Methods that convert strings into various formats.
*
* <p>
* What JAX-RPC name binding tells us is that even such basic method
* like "isLetter" can be different depending on the situation.
*
* For this reason, a whole lot of methods are made non-static,
* even though they look like they should be static.
*/
class NameUtil {
protected boolean isPunct(char c) {
return c == '-' || c == '.' || c == ':' || c == '_' || c == '\u00b7' || c == '\u0387' || c == '\u06dd' || c == '\u06de';
}
protected static boolean isDigit(char c) {
return c >= '0' && c <= '9' || Character.isDigit(c);
}
protected static boolean isUpper(char c) {
return c >= 'A' && c <= 'Z' || Character.isUpperCase(c);
}
protected static boolean isLower(char c) {
return c >= 'a' && c <= 'z' || Character.isLowerCase(c);
}
protected boolean isLetter(char c) {
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || Character.isLetter(c);
}
private String toLowerCase(String s)
{
return s.toLowerCase(Locale.ENGLISH);
}
private String toUpperCase(char c)
{
return String.valueOf(c).toUpperCase(Locale.ENGLISH);
}
private String toUpperCase(String s)
{
return s.toUpperCase(Locale.ENGLISH);
}
/**
* Capitalizes the first character of the specified string,
* and de-capitalize the rest of characters.
*/
public String capitalize(String s) {
if (!isLower(s.charAt(0)))
return s;
StringBuilder sb = new StringBuilder(s.length());
sb.append(toUpperCase(s.charAt(0)));
sb.append(toLowerCase(s.substring(1)));
return sb.toString();
}
// Precondition: s[start] is not punctuation
private int nextBreak(String s, int start) {
int n = s.length();
char c1 = s.charAt(start);
int t1 = classify(c1);
for (int i=start+1; i<n; i++) {
// shift (c1,t1) into (c0,t0)
// char c0 = c1; --- conceptually, but c0 won't be used
int t0 = t1;
c1 = s.charAt(i);
t1 = classify(c1);
switch(actionTable[t0*5+t1]) {
case ACTION_CHECK_PUNCT:
if(isPunct(c1)) return i;
break;
case ACTION_CHECK_C2:
if (i < n-1) {
char c2 = s.charAt(i+1);
if (isLower(c2))
return i;
}
break;
case ACTION_BREAK:
return i;
}
}
return -1;
}
// the 5-category classification that we use in this code
// to find work breaks
static protected final int UPPER_LETTER = 0;
static protected final int LOWER_LETTER = 1;
static protected final int OTHER_LETTER = 2;
static protected final int DIGIT = 3;
static protected final int OTHER = 4;
/**
* Look up table for actions.
* type0*5+type1 would yield the action to be taken.
*/
private static final byte[] actionTable = new byte[5*5];
// action constants. see nextBreak for the meaning
static private final byte ACTION_CHECK_PUNCT = 0;
static private final byte ACTION_CHECK_C2 = 1;
static private final byte ACTION_BREAK = 2;
static private final byte ACTION_NOBREAK = 3;
/**
* Decide the action to be taken given
* the classification of the preceding character 't0' and
* the classification of the next character 't1'.
*/
private static byte decideAction( int t0, int t1 ) {
if(t0==OTHER && t1==OTHER) return ACTION_CHECK_PUNCT;
if(!xor(t0==DIGIT,t1==DIGIT)) return ACTION_BREAK;
if(t0==LOWER_LETTER && t1!=LOWER_LETTER) return ACTION_BREAK;
if(!xor(t0<=OTHER_LETTER,t1<=OTHER_LETTER)) return ACTION_BREAK;
if(!xor(t0==OTHER_LETTER,t1==OTHER_LETTER)) return ACTION_BREAK;
if(t0==UPPER_LETTER && t1==UPPER_LETTER) return ACTION_CHECK_C2;
return ACTION_NOBREAK;
}
private static boolean xor(boolean x,boolean y) {
return (x&&y) || (!x&&!y);
}
static {
// initialize the action table
for( int t0=0; t0<5; t0++ )
for( int t1=0; t1<5; t1++ )
actionTable[t0*5+t1] = decideAction(t0,t1);
}
/**
* Classify a character into 5 categories that determine the word break.
*/
protected int classify(char c0) {
switch(Character.getType(c0)) {
case Character.UPPERCASE_LETTER: return UPPER_LETTER;
case Character.LOWERCASE_LETTER: return LOWER_LETTER;
case Character.TITLECASE_LETTER:
case Character.MODIFIER_LETTER:
case Character.OTHER_LETTER: return OTHER_LETTER;
case Character.DECIMAL_DIGIT_NUMBER: return DIGIT;
default: return OTHER;
}
}
/**
* Tokenizes a string into words and capitalizes the first
* character of each word.
*
* <p>
* This method uses a change in character type as a splitter
* of two words. For example, "abc100ghi" will be splitted into
* {"Abc", "100","Ghi"}.
*/
public List<String> toWordList(String s) {
ArrayList<String> ss = new ArrayList<String>();
int n = s.length();
for (int i = 0; i < n;) {
// Skip punctuation
while (i < n) {
if (!isPunct(s.charAt(i)))
break;
i++;
}
if (i >= n) break;
// Find next break and collect word
int b = nextBreak(s, i);
String w = (b == -1) ? s.substring(i) : s.substring(i, b);
ss.add(escape(capitalize(w)));
if (b == -1) break;
i = b;
}
// we can't guarantee a valid Java identifier anyway,
// so there's not much point in rejecting things in this way.
// if (ss.size() == 0)
// throw new IllegalArgumentException("Zero-length identifier");
return ss;
}
protected String toMixedCaseName(List<String> ss, boolean startUpper) {
StringBuilder sb = new StringBuilder();
if(!ss.isEmpty()) {
sb.append(startUpper ? ss.get(0) : toLowerCase(ss.get(0)));
for (int i = 1; i < ss.size(); i++)
sb.append(ss.get(i));
}
return sb.toString();
}
protected String toMixedCaseVariableName(String[] ss,
boolean startUpper,
boolean cdrUpper) {
if (cdrUpper)
for (int i = 1; i < ss.length; i++)
ss[i] = capitalize(ss[i]);
StringBuilder sb = new StringBuilder();
if( ss.length>0 ) {
sb.append(startUpper ? ss[0] : toLowerCase(ss[0]));
for (int i = 1; i < ss.length; i++)
sb.append(ss[i]);
}
return sb.toString();
}
/**
* Formats a string into "THIS_KIND_OF_FORMAT_ABC_DEF".
*
* @return
* Always return a string but there's no guarantee that
* the generated code is a valid Java identifier.
*/
public String toConstantName(String s) {
return toConstantName(toWordList(s));
}
/**
* Formats a string into "THIS_KIND_OF_FORMAT_ABC_DEF".
*
* @return
* Always return a string but there's no guarantee that
* the generated code is a valid Java identifier.
*/
public String toConstantName(List<String> ss) {
StringBuilder sb = new StringBuilder();
if( !ss.isEmpty() ) {
sb.append(toUpperCase(ss.get(0)));
for (int i = 1; i < ss.size(); i++) {
sb.append('_');
sb.append(toUpperCase(ss.get(i)));
}
}
return sb.toString();
}
/**
* Escapes characters is the given string so that they can be
* printed by only using US-ASCII characters.
*
* The escaped characters will be appended to the given
* StringBuffer.
*
* @param sb
* StringBuffer that receives escaped string.
* @param s
* String to be escaped. <code>s.substring(start)</code>
* will be escaped and copied to the string buffer.
*/
public static void escape(StringBuilder sb, String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (Character.isJavaIdentifierPart(c))
sb.append(c);
else {
sb.append('_');
if (c <= '\u000f') sb.append("000");
else if (c <= '\u00ff') sb.append("00");
else if (c <= '\u0fff') sb.append('0');
sb.append(Integer.toString(c, 16));
}
}
}
/**
* Escapes characters that are unusable as Java identifiers
* by replacing unsafe characters with safe characters.
*/
private static String escape(String s) {
int n = s.length();
for (int i = 0; i < n; i++)
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
StringBuilder sb = new StringBuilder(s.substring(0, i));
escape(sb, s, i);
return sb.toString();
}
return s;
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
/**
* <h1>Runtime API for the JAX-WS RI</h1>.
*
* This API is designed for the use by the JAX-WS RI runtime. The API is is subject to
* change without notice.
*
* <p>
* In an container environment, such as in J2SE/J2EE, if a new version with
* a modified runtime API is loaded into a child class loader, it will still be bound
* against the old runtime API in the base class loader.
*
* <p>
* So the compatibility of this API has to be managed carefully.
*/
package com.sun.xml.internal.bind.api;

View File

@@ -0,0 +1,49 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs character escaping and write the result
* to the output.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public interface CharacterEscapeHandler {
/**
* @param ch The array of characters.
* @param start The starting position.
* @param length The number of characters to use.
* @param isAttVal true if this is an attribute value literal.
*/
void escape( char[] ch, int start, int length, boolean isAttVal, Writer out ) throws IOException;
}

View File

@@ -0,0 +1,377 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
//@@3RD PARTY CODE@@
// DataWriter.java - XML writer for data-oriented files.
package com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* Write data- or field-oriented XML.
*
* <p>This filter pretty-prints field-oriented XML without mixed content.
* all added indentation and newlines will be passed on down
* the filter chain (if any).</p>
*
* <p>In general, all whitespace in an XML document is potentially
* significant, so a general-purpose XML writing tool like the
* {@link XMLWriter} class cannot
* add newlines or indentation.</p>
*
* <p>There is, however, a large class of XML documents where information
* is strictly fielded: each element contains either character data
* or other elements, but not both. For this special case, it is possible
* for a writing tool to provide automatic indentation and newlines
* without requiring extra work from the user. Note that this class
* will likely not yield appropriate results for document-oriented
* XML like XHTML pages, which mix character data and elements together.</p>
*
* <p>This writer will automatically place each start tag on a new line,
* optionally indented if an indent step is provided (by default, there
* is no indentation). If an element contains other elements, the end
* tag will also appear on a new line with leading indentation. Consider,
* for example, the following code:</p>
*
* <pre>
* DataWriter w = new DataWriter();
*
* w.setIndentStep(2);
* w.startDocument();
* w.startElement("Person");
* w.dataElement("name", "Jane Smith");
* w.dataElement("date-of-birth", "1965-05-23");
* w.dataElement("citizenship", "US");
* w.endElement("Person");
* w.endDocument();
* </pre>
*
* <p>This code will produce the following document:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;Person>
* &lt;name>Jane Smith&lt;/name>
* &lt;date-of-birth>1965-05-23&lt;/date-of-birth>
* &lt;citizenship>US&lt;/citizenship>
* &lt;/Person>
* </pre>
*
* <p>This class inherits from {@link XMLWriter},
* and provides all of the same support for Namespaces.</p>
*
* @since 1.0
* @author David Megginson, david@megginson.com
* @version 0.2
* @see XMLWriter
*/
public class DataWriter extends XMLWriter
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Create a new data writer for the specified output.
*
* @param writer The character stream where the XML document
* will be written.
* @param encoding
* If non-null string is specified, it is written as a part
* of the XML declaration.
*/
public DataWriter ( Writer writer, String encoding, CharacterEscapeHandler _escapeHandler )
{
super(writer,encoding,_escapeHandler);
}
public DataWriter (Writer writer, String encoding ) {
this( writer, encoding, DumbEscapeHandler.theInstance );
}
////////////////////////////////////////////////////////////////////
// Accessors and setters.
////////////////////////////////////////////////////////////////////
/**
* Return the current indent step.
*
* <p>Return the current indent step: each start tag will be
* indented by this number of spaces times the number of
* ancestors that the element has.</p>
*
* @return The number of spaces in each indentation step,
* or 0 or less for no indentation.
* @see #setIndentStep(int)
*
* @deprecated
* Only return the length of the indent string.
*/
public int getIndentStep ()
{
return indentStep.length();
}
/**
* Set the current indent step.
*
* @param indentStep The new indent step (0 or less for no
* indentation).
* @see #getIndentStep()
*
* @deprecated
* Should use the version that takes string.
*/
public void setIndentStep (int indentStep)
{
StringBuilder buf = new StringBuilder();
for( ; indentStep>0; indentStep-- )
buf.append(' ');
setIndentStep(buf.toString());
}
public void setIndentStep(String s) {
this.indentStep = s;
}
////////////////////////////////////////////////////////////////////
// Override methods from XMLWriter.
////////////////////////////////////////////////////////////////////
/**
* Reset the writer so that it can be reused.
*
* <p>This method is especially useful if the writer failed
* with an exception the last time through.</p>
*
* @see XMLWriter#reset()
*/
public void reset ()
{
depth = 0;
state = SEEN_NOTHING;
stateStack = new Stack<Object>();
super.reset();
}
protected void writeXmlDecl(String decl) throws IOException {
super.writeXmlDecl(decl);
write('\n');
}
/**
* Write a start tag.
*
* <p>Each tag will begin on a new line, and will be
* indented by the current indent step times the number
* of ancestors that the element has.</p>
*
* <p>The newline and indentation will be passed on down
* the filter chain through regular characters events.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's qualified (prefixed) name.
* @param atts The element's attribute list.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#startElement(String, String, String, Attributes)
*/
public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
stateStack.push(SEEN_ELEMENT);
state = SEEN_NOTHING;
if (depth > 0) {
super.characters("\n");
}
doIndent();
super.startElement(uri, localName, qName, atts);
depth++;
}
/**
* Write an end tag.
*
* <p>If the element has contained other elements, the tag
* will appear indented on a new line; otherwise, it will
* appear immediately following whatever came before.</p>
*
* <p>The newline and indentation will be passed on down
* the filter chain through regular characters events.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's qualified (prefixed) name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#endElement(String, String, String)
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
depth--;
if (state == SEEN_ELEMENT) {
super.characters("\n");
doIndent();
}
super.endElement(uri, localName, qName);
state = stateStack.pop();
}
public void endDocument() throws SAXException {
try {
write('\n');
} catch( IOException e ) {
throw new SAXException(e);
}
super.endDocument();
}
// /**
// * Write a empty element tag.
// *
// * <p>Each tag will appear on a new line, and will be
// * indented by the current indent step times the number
// * of ancestors that the element has.</p>
// *
// * <p>The newline and indentation will be passed on down
// * the filter chain through regular characters events.</p>
// *
// * @param uri The element's Namespace URI.
// * @param localName The element's local name.
// * @param qName The element's qualified (prefixed) name.
// * @param atts The element's attribute list.
// * @exception org.xml.sax.SAXException If there is an error
// * writing the empty tag, or if a filter further
// * down the chain raises an exception.
// * @see XMLWriter#emptyElement(String, String, String, Attributes)
// */
// public void emptyElement (String uri, String localName,
// String qName, Attributes atts)
// throws SAXException
// {
// state = SEEN_ELEMENT;
// if (depth > 0) {
// super.characters("\n");
// }
// doIndent();
// super.emptyElement(uri, localName, qName, atts);
// }
/**
* Write a sequence of characters.
*
* @param ch The characters to write.
* @param start The starting position in the array.
* @param length The number of characters to use.
* @exception org.xml.sax.SAXException If there is an error
* writing the characters, or if a filter further
* down the chain raises an exception.
* @see XMLWriter#characters(char[], int, int)
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
state = SEEN_DATA;
super.characters(ch, start, length);
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Print indentation for the current level.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the indentation characters, or if a filter
* further down the chain raises an exception.
*/
private void doIndent ()
throws SAXException
{
if (depth > 0) {
char[] ch = indentStep.toCharArray();
for( int i=0; i<depth; i++ )
characters(ch, 0, ch.length);
}
}
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
private final static Object SEEN_NOTHING = new Object();
private final static Object SEEN_ELEMENT = new Object();
private final static Object SEEN_DATA = new Object();
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private Object state = SEEN_NOTHING;
private Stack<Object> stateStack = new Stack<Object>();
private String indentStep = "";
private int depth = 0;
}
// end of DataWriter.java

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Escape everything above the US-ASCII code range.
* A fallback position.
*
* Works with any JDK, any encoding.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class DumbEscapeHandler implements CharacterEscapeHandler {
private DumbEscapeHandler() {} // no instanciation please
public static final CharacterEscapeHandler theInstance = new DumbEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
int limit = start+length;
for (int i = start; i < limit; i++) {
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
if (isAttVal) {
out.write("&quot;");
} else {
out.write('\"');
}
break;
default:
if (ch[i] > '\u007f') {
out.write("&#");
out.write(Integer.toString(ch[i]));
out.write(';');
} else {
out.write(ch[i]);
}
}
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*
* @since JAXB1.0
*/
public class Messages
{
public static String format( String property ) {
return format( property, null );
}
public static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
public static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
public 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
//
//
public static final String NOT_MARSHALLABLE = // 0 args
"MarshallerImpl.NotMarshallable";
public static final String UNSUPPORTED_RESULT = // 0 args
"MarshallerImpl.UnsupportedResult";
public static final String UNSUPPORTED_ENCODING = // 1 arg
"MarshallerImpl.UnsupportedEncoding";
public static final String NULL_WRITER = // 0 args
"MarshallerImpl.NullWriterParam";
public static final String ASSERT_FAILED = // 0 args
"SAXMarshaller.AssertFailed";
/**
* @deprecated use ERR_MISSING_OBJECT2
*/
public static final String ERR_MISSING_OBJECT = // 0 args
"SAXMarshaller.MissingObject";
/**
* @deprecated
* use {@link com.sun.xml.internal.bind.v2.runtime.XMLSerializer#reportMissingObjectError(String)}
* Usage not found. TODO Remove
*/
// public static final String ERR_MISSING_OBJECT2 = // 1 arg
// "SAXMarshaller.MissingObject2";
/**
* @deprecated only used from 1.0
*/
public static final String ERR_DANGLING_IDREF = // 1 arg
"SAXMarshaller.DanglingIDREF";
/**
* @deprecated only used from 1.0
*/
public static final String ERR_NOT_IDENTIFIABLE = // 0 args
"SAXMarshaller.NotIdentifiable";
public static final String DOM_IMPL_DOESNT_SUPPORT_CREATELEMENTNS = // 2 args
"SAX2DOMEx.DomImplDoesntSupportCreateElementNs";
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs no character escaping. Usable only when the output encoding
* is UTF, but this handler gives the maximum performance.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class MinimumEscapeHandler implements CharacterEscapeHandler {
private MinimumEscapeHandler() {} // no instanciation please
public static final CharacterEscapeHandler theInstance = new MinimumEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
// avoid calling the Writerwrite method too much by assuming
// that the escaping occurs rarely.
// profiling revealed that this is faster than the naive code.
int limit = start+length;
for (int i = start; i < limit; i++) {
char c = ch[i];
if(c == '&' || c == '<' || c == '>' || c == '\r' || (c == '\"' && isAttVal) ) {
if(i!=start)
out.write(ch,start,i-start);
start = i+1;
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
out.write("&quot;");
break;
}
}
}
if( start!=limit )
out.write(ch,start,limit-start);
}
}

View File

@@ -0,0 +1,256 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Node;
// be careful about changing this class. this class is supposed to be
// extended by users and therefore we are not allowed to break
// those user code.
//
// this means:
// - don't add any abstract method
// - don't change any existing method signature
// - don't remove any existing method.
/**
* Implemented by the user application to determine URI -> prefix
* mapping.
*
* This is considered as an interface, though it's implemented
* as an abstract class to make it easy to add new methods in
* a future.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public abstract class NamespacePrefixMapper {
private static final String[] EMPTY_STRING = new String[0];
/**
* Returns a preferred prefix for the given namespace URI.
*
* This method is intended to be overrided by a derived class.
*
* <p>
* As noted in the return value portion of the javadoc, there
* are several cases where the preference cannot be honored.
* Specifically, as of JAXB RI 2.0 and onward:
*
* <ol>
* <li>
* If the prefix returned is already in use as one of the in-scope
* namespace bindings. This is partly necessary for correctness
* (so that we don't unexpectedly change the meaning of QNames
* bound to {@link String}), partly to simplify the marshaller.
* <li>
* If the prefix returned is "" yet the current {@link JAXBContext}
* includes classes that use the empty namespace URI. This allows
* the JAXB RI to reserve the "" prefix for the empty namespace URI,
* which is the only possible prefix for the URI.
* This restriction is also to simplify the marshaller.
* </ol>
*
* @param namespaceUri
* The namespace URI for which the prefix needs to be found.
* Never be null. "" is used to denote the default namespace.
* @param suggestion
* When the content tree has a suggestion for the prefix
* to the given namespaceUri, that suggestion is passed as a
* parameter. Typicall this value comes from the QName.getPrefix
* to show the preference of the content tree. This parameter
* may be null, and this parameter may represent an already
* occupied prefix.
* @param requirePrefix
* If this method is expected to return non-empty prefix.
* When this flag is true, it means that the given namespace URI
* cannot be set as the default namespace.
*
* @return
* null if there's no prefered prefix for the namespace URI.
* In this case, the system will generate a prefix for you.
*
* Otherwise the system will try to use the returned prefix,
* but generally there's no guarantee if the prefix will be
* actually used or not.
*
* return "" to map this namespace URI to the default namespace.
* Again, there's no guarantee that this preference will be
* honored.
*
* If this method returns "" when requirePrefix=true, the return
* value will be ignored and the system will generate one.
*
* @since JAXB 1.0.1
*/
public abstract String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix);
/**
* Returns a list of namespace URIs that should be declared
* at the root element.
*
* <p>
* By default, the JAXB RI 1.0.x produces namespace declarations only when
* they are necessary, only at where they are used. Because of this
* lack of look-ahead, sometimes the marshaller produces a lot of
* namespace declarations that look redundant to human eyes. For example,
* <pre><xmp>
* <?xml version="1.0"?>
* <root>
* <ns1:child xmlns:ns1="urn:foo"> ... </ns1:child>
* <ns2:child xmlns:ns2="urn:foo"> ... </ns2:child>
* <ns3:child xmlns:ns3="urn:foo"> ... </ns3:child>
* ...
* </root>
* </xmp></pre>
*
* <p>
* The JAXB RI 2.x mostly doesn't exhibit this behavior any more,
* as it declares all statically known namespace URIs (those URIs
* that are used as element/attribute names in JAXB annotations),
* but it may still declare additional namespaces in the middle of
* a document, for example when (i) a QName as an attribute/element value
* requires a new namespace URI, or (ii) DOM nodes as a portion of an object
* tree requires a new namespace URI.
*
* <p>
* If you know in advance that you are going to use a certain set of
* namespace URIs, you can override this method and have the marshaller
* declare those namespace URIs at the root element.
*
* <p>
* For example, by returning <code>new String[]{"urn:foo"}</code>,
* the marshaller will produce:
* <pre><xmp>
* <?xml version="1.0"?>
* <root xmlns:ns1="urn:foo">
* <ns1:child> ... </ns1:child>
* <ns1:child> ... </ns1:child>
* <ns1:child> ... </ns1:child>
* ...
* </root>
* </xmp></pre>
* <p>
* To control prefixes assigned to those namespace URIs, use the
* {@link #getPreferredPrefix(String, String, boolean)} method.
*
* @return
* A list of namespace URIs as an array of {@link String}s.
* This method can return a length-zero array but not null.
* None of the array component can be null. To represent
* the empty namespace, use the empty string <code>""</code>.
*
* @since
* JAXB RI 1.0.2
*/
public String[] getPreDeclaredNamespaceUris() {
return EMPTY_STRING;
}
/**
* Similar to {@link #getPreDeclaredNamespaceUris()} but allows the
* (prefix,nsUri) pairs to be returned.
*
* <p>
* With {@link #getPreDeclaredNamespaceUris()}, applications who wish to control
* the prefixes as well as the namespaces needed to implement both
* {@link #getPreDeclaredNamespaceUris()} and {@link #getPreferredPrefix(String, String, boolean)}.
*
* <p>
* This version eliminates the needs by returning an array of pairs.
*
* @return
* always return a non-null (but possibly empty) array. The array stores
* data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
* the empty namespace URI and the default prefix. Null is not allowed as a value
* in the array.
*
* @since
* JAXB RI 2.0 beta
*/
public String[] getPreDeclaredNamespaceUris2() {
return EMPTY_STRING;
}
/**
* Returns a list of (prefix,namespace URI) pairs that represents
* namespace bindings available on ancestor elements (that need not be repeated
* by the JAXB RI.)
*
* <p>
* Sometimes JAXB is used to marshal an XML document, which will be
* used as a subtree of a bigger document. When this happens, it's nice
* for a JAXB marshaller to be able to use in-scope namespace bindings
* of the larger document and avoid declaring redundant namespace URIs.
*
* <p>
* This is automatically done when you are marshalling to {@link XMLStreamWriter},
* {@link XMLEventWriter}, {@link DOMResult}, or {@link Node}, because
* those output format allows us to inspect what's currently available
* as in-scope namespace binding. However, with other output format,
* such as {@link OutputStream}, the JAXB RI cannot do this automatically.
* That's when this method comes into play.
*
* <p>
* Namespace bindings returned by this method will be used by the JAXB RI,
* but will not be re-declared. They are assumed to be available when you insert
* this subtree into a bigger document.
*
* <p>
* It is <b>NOT</b> OK to return the same binding, or give
* the receiver a conflicting binding information.
* It's a responsibility of the caller to make sure that this doesn't happen
* even if the ancestor elements look like:
* <pre><xmp>
* <foo:abc xmlns:foo="abc">
* <foo:abc xmlns:foo="def">
* <foo:abc xmlns:foo="abc">
* ... JAXB marshalling into here.
* </foo:abc>
* </foo:abc>
* </foo:abc>
* </xmp></pre>
*
* @return
* always return a non-null (but possibly empty) array. The array stores
* data like (prefix1,nsUri1,prefix2,nsUri2,...) Use an empty string to represent
* the empty namespace URI and the default prefix. Null is not allowed as a value
* in the array.
*
* @since JAXB RI 2.0 beta
*/
public String[] getContextualNamespaceDecls() {
return EMPTY_STRING;
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
/**
* Uses JDK1.4 NIO functionality to escape characters smartly.
*
* @since 1.0.1
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class NioEscapeHandler implements CharacterEscapeHandler {
private final CharsetEncoder encoder;
// exposing those variations upset javac 1.3.1, since it needs to
// know about those classes to determine which overloaded version
// of the method it wants to use. So comment it out for the compatibility.
// public NioEscapeHandler(CharsetEncoder _encoder) {
// this.encoder = _encoder;
// if(encoder==null)
// throw new NullPointerException();
// }
//
// public NioEscapeHandler(Charset charset) {
// this(charset.newEncoder());
// }
public NioEscapeHandler(String charsetName) {
// this(Charset.forName(charsetName));
this.encoder = Charset.forName(charsetName).newEncoder();
}
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
int limit = start+length;
for (int i = start; i < limit; i++) {
switch (ch[i]) {
case '&':
out.write("&amp;");
break;
case '<':
out.write("&lt;");
break;
case '>':
out.write("&gt;");
break;
case '\"':
if (isAttVal) {
out.write("&quot;");
} else {
out.write('\"');
}
break;
default:
if( encoder.canEncode(ch[i]) ) {
out.write(ch[i]);
} else {
out.write("&#");
out.write(Integer.toString(ch[i]));
out.write(';');
}
}
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (c) 2017, 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 com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs no character escaping.
*
* @author
* Roman Grigoriadi (roman.grigoriadi@oracle.com)
*/
public class NoEscapeHandler implements CharacterEscapeHandler {
public static final NoEscapeHandler theInstance = new NoEscapeHandler();
@Override
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
out.write(ch, start, length);
}
}

View File

@@ -0,0 +1,234 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.marshaller;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.xml.internal.bind.util.Which;
import com.sun.istack.internal.FinalArrayList;
import com.sun.xml.internal.bind.v2.util.XmlFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
/**
* Builds a DOM tree from SAX2 events.
*
* @author Vivek Pandey
* @since 1.0
*/
public class SAX2DOMEx implements ContentHandler {
private Node node = null;
private boolean isConsolidate;
protected final Stack<Node> nodeStack = new Stack<Node>();
private final FinalArrayList<String> unprocessedNamespaces = new FinalArrayList<String>();
/**
* Document object that owns the specified node.
*/
protected final Document document;
/**
* @param node
* Nodes will be created and added under this object.
*/
public SAX2DOMEx(Node node) {
this(node, false);
}
/**
* @param node
* Nodes will be created and added under this object.
*/
public SAX2DOMEx(Node node, boolean isConsolidate) {
this.node = node;
this.isConsolidate = isConsolidate;
nodeStack.push(this.node);
if (node instanceof Document) {
this.document = (Document) node;
} else {
this.document = node.getOwnerDocument();
}
}
/**
* Creates a fresh empty DOM document and adds nodes under this document.
*/
public SAX2DOMEx(DocumentBuilderFactory f) throws ParserConfigurationException {
f.setValidating(false);
document = f.newDocumentBuilder().newDocument();
node = document;
nodeStack.push(document);
}
/**
* Creates a fresh empty DOM document and adds nodes under this document.
* @deprecated
*/
public SAX2DOMEx() throws ParserConfigurationException {
DocumentBuilderFactory factory = XmlFactory.createDocumentBuilderFactory(false);
factory.setValidating(false);
document = factory.newDocumentBuilder().newDocument();
node = document;
nodeStack.push(document);
}
public final Element getCurrentElement() {
return (Element) nodeStack.peek();
}
public Node getDOM() {
return node;
}
public void startDocument() {
}
public void endDocument() {
}
protected void namespace(Element element, String prefix, String uri) {
String qname;
if ("".equals(prefix) || prefix == null) {
qname = "xmlns";
} else {
qname = "xmlns:" + prefix;
}
// older version of Xerces (I confirmed that the bug is gone with Xerces 2.4.0)
// have a problem of re-setting the same namespace attribute twice.
// work around this bug removing it first.
if (element.hasAttributeNS("http://www.w3.org/2000/xmlns/", qname)) {
// further workaround for an old Crimson bug where the removeAttribtueNS
// method throws NPE when the element doesn't have any attribute.
// to be on the safe side, check the existence of attributes before
// attempting to remove it.
// for details about this bug, see org.apache.crimson.tree.ElementNode2
// line 540 or the following message:
// https://jaxb.dev.java.net/servlets/ReadMsg?list=users&msgNo=2767
element.removeAttributeNS("http://www.w3.org/2000/xmlns/", qname);
}
// workaround until here
element.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, uri);
}
public void startElement(String namespace, String localName, String qName, Attributes attrs) {
Node parent = nodeStack.peek();
// some broken DOM implementation (we confirmed it with SAXON)
// return null from this method.
Element element = document.createElementNS(namespace, qName);
if (element == null) {
// if so, report an user-friendly error message,
// rather than dying mysteriously with NPE.
throw new AssertionError(
Messages.format(Messages.DOM_IMPL_DOESNT_SUPPORT_CREATELEMENTNS,
document.getClass().getName(),
Which.which(document.getClass())));
}
// process namespace bindings
for (int i = 0; i < unprocessedNamespaces.size(); i += 2) {
String prefix = unprocessedNamespaces.get(i);
String uri = unprocessedNamespaces.get(i + 1);
namespace(element, prefix, uri);
}
unprocessedNamespaces.clear();
if (attrs != null) {
int length = attrs.getLength();
for (int i = 0; i < length; i++) {
String namespaceuri = attrs.getURI(i);
String value = attrs.getValue(i);
String qname = attrs.getQName(i);
element.setAttributeNS(namespaceuri, qname, value);
}
}
// append this new node onto current stack node
parent.appendChild(element);
// push this node onto stack
nodeStack.push(element);
}
public void endElement(String namespace, String localName, String qName) {
nodeStack.pop();
}
public void characters(char[] ch, int start, int length) {
characters(new String(ch, start, length));
}
protected Text characters(String s) {
Node parent = nodeStack.peek();
Node lastChild = parent.getLastChild();
Text text;
if (isConsolidate && lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
text = (Text) lastChild;
text.appendData(s);
} else {
text = document.createTextNode(s);
parent.appendChild(text);
}
return text;
}
public void ignorableWhitespace(char[] ch, int start, int length) {
}
public void processingInstruction(String target, String data) throws org.xml.sax.SAXException {
Node parent = nodeStack.peek();
Node n = document.createProcessingInstruction(target, data);
parent.appendChild(n);
}
public void setDocumentLocator(Locator locator) {
}
public void skippedEntity(String name) {
}
public void startPrefixMapping(String prefix, String uri) {
unprocessedNamespaces.add(prefix);
unprocessedNamespaces.add(uri);
}
public void endPrefixMapping(String prefix) {
}
}

View File

@@ -0,0 +1,976 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
// @@3RD PARTY CODE@@
// XMLWriter.java - serialize an XML document.
// Written by David Megginson, david@megginson.com
// NO WARRANTY! This class is in the public domain.
// Id: XMLWriter.java,v 1.5 2000/09/17 01:08:16 david Exp
package com.sun.xml.internal.bind.marshaller;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* Filter to write an XML document from a SAX event stream.
*
* <p>This class can be used by itself or as part of a SAX event
* stream: it takes as input a series of SAX2 ContentHandler
* events and uses the information in those events to write
* an XML document. Since this class is a filter, it can also
* pass the events on down a filter chain for further processing
* (you can use the XMLWriter to take a snapshot of the current
* state at any point in a filter chain), and it can be
* used directly as a ContentHandler for a SAX2 XMLReader.</p>
*
* <p>The client creates a document by invoking the methods for
* standard SAX2 events, always beginning with the
* {@link #startDocument startDocument} method and ending with
* the {@link #endDocument endDocument} method. There are convenience
* methods provided so that clients to not have to create empty
* attribute lists or provide empty strings as parameters; for
* example, the method invocation</p>
*
* <pre>
* w.startElement("foo");
* </pre>
*
* <p>is equivalent to the regular SAX2 ContentHandler method</p>
*
* <pre>
* w.startElement("", "foo", "", new AttributesImpl());
* </pre>
*
* <p>Except that it is more efficient because it does not allocate
* a new empty attribute list each time. The following code will send
* a simple XML document to standard output:</p>
*
* <pre>
* XMLWriter w = new XMLWriter();
*
* w.startDocument();
* w.startElement("greeting");
* w.characters("Hello, world!");
* w.endElement("greeting");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;greeting>Hello, world!&lt;/greeting>
* </pre>
*
* <p>In fact, there is an even simpler convenience method,
* <var>dataElement</var>, designed for writing elements that
* contain only character data, so the code to generate the
* document could be shortened to</p>
*
* <pre>
* XMLWriter w = new XMLWriter();
*
* w.startDocument();
* w.dataElement("greeting", "Hello, world!");
* w.endDocument();
* </pre>
*
* <h2>Whitespace</h2>
*
* <p>According to the XML Recommendation, <em>all</em> whitespace
* in an XML document is potentially significant to an application,
* so this class never adds newlines or indentation. If you
* insert three elements in a row, as in</p>
*
* <pre>
* w.dataElement("item", "1");
* w.dataElement("item", "2");
* w.dataElement("item", "3");
* </pre>
*
* <p>you will end up with</p>
*
* <pre>
* &lt;item>1&lt;/item>&lt;item>3&lt;/item>&lt;item>3&lt;/item>
* </pre>
*
* <p>You need to invoke one of the <var>characters</var> methods
* explicitly to add newlines or indentation. Alternatively, you
* can use {@link DataWriter}, which
* is derived from this class -- it is optimized for writing
* purely data-oriented (or field-oriented) XML, and does automatic
* linebreaks and indentation (but does not support mixed content
* properly).</p>
*
*
* <h2>Namespace Support</h2>
*
* <p>The writer contains extensive support for XML Namespaces, so that
* a client application does not have to keep track of prefixes and
* supply <var>xmlns</var> attributes. By default, the XML writer will
* generate Namespace declarations in the form _NS1, _NS2, etc., wherever
* they are needed, as in the following example:</p>
*
* <pre>
* w.startDocument();
* w.emptyElement("http://www.foo.com/ns/", "foo");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;_NS1:foo xmlns:_NS1="http://www.foo.com/ns/"/>
* </pre>
*
* <p>In many cases, document authors will prefer to choose their
* own prefixes rather than using the (ugly) default names. The
* XML writer allows two methods for selecting prefixes:</p>
*
* <ol>
* <li>the qualified name</li>
* </ol>
*
* <p>Whenever the XML writer finds a new Namespace URI, it checks
* to see if a qualified (prefixed) name is also available; if so
* it attempts to use the name's prefix (as long as the prefix is
* not already in use for another Namespace URI).</p>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;foo:foo xmlns:foo="http://www.foo.com/ns/"/>
* </pre>
*
* <p>The default Namespace simply uses an empty string as the prefix:</p>
*
* <pre>
* w.setPrefix("http://www.foo.com/ns/", "");
* w.startDocument();
* w.emptyElement("http://www.foo.com/ns/", "foo");
* w.endDocument();
* </pre>
*
* <p>The resulting document will look like this:</p>
*
* <pre>
* &lt;?xml version="1.0" standalone="yes"?>
*
* &lt;foo xmlns="http://www.foo.com/ns/"/>
* </pre>
*
* <p>By default, the XML writer will not declare a Namespace until
* it is actually used. Sometimes, this approach will create
* a large number of Namespace declarations, as in the following
* example:</p>
*
* <pre>
* &lt;xml version="1.0" standalone="yes"?>
*
* &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
* &lt;rdf:Description about="http://www.foo.com/ids/books/12345">
* &lt;dc:title xmlns:dc="http://www.purl.org/dc/">A Dark Night&lt;/dc:title>
* &lt;dc:creator xmlns:dc="http://www.purl.org/dc/">Jane Smith&lt;/dc:title>
* &lt;dc:date xmlns:dc="http://www.purl.org/dc/">2000-09-09&lt;/dc:title>
* &lt;/rdf:Description>
* &lt;/rdf:RDF>
* </pre>
*
* <p>The "rdf" prefix is declared only once, because the RDF Namespace
* is used by the root element and can be inherited by all of its
* descendants; the "dc" prefix, on the other hand, is declared three
* times, because no higher element uses the Namespace. To solve this
* problem, you can instruct the XML writer to predeclare Namespaces
* on the root element even if they are not used there:</p>
*
* <pre>
* w.forceNSDecl("http://www.purl.org/dc/");
* </pre>
*
* <p>Now, the "dc" prefix will be declared on the root element even
* though it's not needed there, and can be inherited by its
* descendants:</p>
*
* <pre>
* &lt;xml version="1.0" standalone="yes"?>
*
* &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
* xmlns:dc="http://www.purl.org/dc/">
* &lt;rdf:Description about="http://www.foo.com/ids/books/12345">
* &lt;dc:title>A Dark Night&lt;/dc:title>
* &lt;dc:creator>Jane Smith&lt;/dc:title>
* &lt;dc:date>2000-09-09&lt;/dc:title>
* &lt;/rdf:Description>
* &lt;/rdf:RDF>
* </pre>
*
* <p>This approach is also useful for declaring Namespace prefixes
* that be used by qualified names appearing in attribute values or
* character data.</p>
*
* @author David Megginson, david@megginson.com
* @version 0.2
* @since JAXB1.0
* @see org.xml.sax.XMLFilter
* @see org.xml.sax.ContentHandler
*/
public class XMLWriter extends XMLFilterImpl
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Create a new XML writer.
*
* <p>Write to the writer provided.</p>
*
* @param writer
* The output destination, or null to use standard output.
* @param encoding
* If non-null string is specified, it is written as a part
* of the XML declaration.
*/
public XMLWriter (Writer writer, String encoding, CharacterEscapeHandler _escapeHandler )
{
init(writer,encoding);
this.escapeHandler = _escapeHandler;
}
public XMLWriter (Writer writer, String encoding ) {
this( writer, encoding, DumbEscapeHandler.theInstance );
}
/**
* Internal initialization method.
*
* <p>All of the public constructors invoke this method.
*
* @param writer The output destination, or null to use
* standard output.
*/
private void init (Writer writer,String encoding)
{
setOutput(writer,encoding);
}
////////////////////////////////////////////////////////////////////
// Public methods.
////////////////////////////////////////////////////////////////////
/**
* Reset the writer.
*
* <p>This method is especially useful if the writer throws an
* exception before it is finished, and you want to reuse the
* writer for a new document. It is usually a good idea to
* invoke {@link #flush flush} before resetting the writer,
* to make sure that no output is lost.</p>
*
* <p>This method is invoked automatically by the
* {@link #startDocument startDocument} method before writing
* a new document.</p>
*
* <p><strong>Note:</strong> this method will <em>not</em>
* clear the prefix or URI information in the writer or
* the selected output writer.</p>
*
* @see #flush()
*/
public void reset ()
{
elementLevel = 0;
startTagIsClosed = true;
}
/**
* Flush the output.
*
* <p>This method flushes the output stream. It is especially useful
* when you need to make certain that the entire document has
* been written to output but do not want to close the output
* stream.</p>
*
* <p>This method is invoked automatically by the
* {@link #endDocument endDocument} method after writing a
* document.</p>
*
* @see #reset()
*/
public void flush ()
throws IOException
{
output.flush();
}
/**
* Set a new output destination for the document.
*
* @param writer The output destination, or null to use
* standard output.
* @see #flush()
*/
public void setOutput (Writer writer,String _encoding)
{
if (writer == null) {
output = new OutputStreamWriter(System.out);
} else {
output = writer;
}
encoding = _encoding;
}
/**
* Set whether the writer should print out the XML declaration
* (&lt;?xml version='1.0' ... ?>).
* <p>
* This option is set to true by default.
*/
public void setXmlDecl( boolean _writeXmlDecl ) {
this.writeXmlDecl = _writeXmlDecl;
}
/**
* Sets the header string.
*
* This string will be written right after the xml declaration
* without any escaping. Useful for generating a boiler-plate
* DOCTYPE decl, PIs, and comments.
*
* @param _header
* passing null will work as if the empty string is passed.
*/
public void setHeader( String _header ) {
this.header = _header;
}
private final HashMap<String,String> locallyDeclaredPrefix = new HashMap<String,String>();
public void startPrefixMapping( String prefix, String uri ) throws SAXException {
locallyDeclaredPrefix.put(prefix,uri);
}
////////////////////////////////////////////////////////////////////
// Methods from org.xml.sax.ContentHandler.
////////////////////////////////////////////////////////////////////
/**
* Write the XML declaration at the beginning of the document.
*
* Pass the event on down the filter chain for further processing.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the XML declaration, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#startDocument()
*/
public void startDocument ()
throws SAXException
{
try {
reset();
if(writeXmlDecl) {
String e="";
if(encoding!=null)
e = " encoding=\""+encoding+'\"';
writeXmlDecl("<?xml version=\"1.0\""+e +" standalone=\"yes\"?>");
}
if(header!=null)
write(header);
super.startDocument();
} catch( IOException e ) {
throw new SAXException(e);
}
}
protected void writeXmlDecl(String decl) throws IOException {
write(decl);
}
/**
* Write a newline at the end of the document.
*
* Pass the event on down the filter chain for further processing.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the newline, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#endDocument()
*/
public void endDocument ()
throws SAXException
{
try {
super.endDocument();
flush();
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write a start tag.
*
* Pass the event on down the filter chain for further processing.
*
* @param uri The Namespace URI, or the empty string if none
* is available.
* @param localName The element's local (unprefixed) name (required).
* @param qName The element's qualified (prefixed) name, or the
* empty string is none is available. This method will
* use the qName as a template for generating a prefix
* if necessary, but it is not guaranteed to use the
* same qName.
* @param atts The element's attribute list (must not be null).
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
try {
if (!startTagIsClosed) {
write(">");
}
elementLevel++;
// nsSupport.pushContext();
write('<');
write(qName);
writeAttributes(atts);
// declare namespaces specified by the startPrefixMapping methods
if(!locallyDeclaredPrefix.isEmpty()) {
for (Map.Entry<String,String> e : locallyDeclaredPrefix.entrySet()) {
String p = e.getKey();
String u = e.getValue();
if (u == null) {
u = "";
}
write(' ');
if ("".equals(p)) {
write("xmlns=\"");
} else {
write("xmlns:");
write(p);
write("=\"");
}
char ch[] = u.toCharArray();
writeEsc(ch, 0, ch.length, true);
write('\"');
}
locallyDeclaredPrefix.clear(); // clear the contents
}
// if (elementLevel == 1) {
// forceNSDecls();
// }
// writeNSDecls();
super.startElement(uri, localName, qName, atts);
startTagIsClosed = false;
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write an end tag.
*
* Pass the event on down the filter chain for further processing.
*
* @param uri The Namespace URI, or the empty string if none
* is available.
* @param localName The element's local (unprefixed) name (required).
* @param qName The element's qualified (prefixed) name, or the
* empty string is none is available. This method will
* use the qName as a template for generating a prefix
* if necessary, but it is not guaranteed to use the
* same qName.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
try {
if (startTagIsClosed) {
write("</");
write(qName);
write('>');
} else {
write("/>");
startTagIsClosed = true;
}
super.endElement(uri, localName, qName);
// nsSupport.popContext();
elementLevel--;
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write character data.
*
* Pass the event on down the filter chain for further processing.
*
* @param ch The array of characters to write.
* @param start The starting position in the array.
* @param len The number of characters to write.
* @exception org.xml.sax.SAXException If there is an error
* writing the characters, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters (char ch[], int start, int len)
throws SAXException
{
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
writeEsc(ch, start, len, false);
super.characters(ch, start, len);
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write ignorable whitespace.
*
* Pass the event on down the filter chain for further processing.
*
* @param ch The array of characters to write.
* @param start The starting position in the array.
* @param length The number of characters to write.
* @exception org.xml.sax.SAXException If there is an error
* writing the whitespace, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException
{
try {
writeEsc(ch, start, length, false);
super.ignorableWhitespace(ch, start, length);
} catch( IOException e ) {
throw new SAXException(e);
}
}
/**
* Write a processing instruction.
*
* Pass the event on down the filter chain for further processing.
*
* @param target The PI target.
* @param data The PI data.
* @exception org.xml.sax.SAXException If there is an error
* writing the PI, or if a handler further down
* the filter chain raises an exception.
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String)
*/
public void processingInstruction (String target, String data)
throws SAXException
{
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
write("<?");
write(target);
write(' ');
write(data);
write("?>");
if (elementLevel < 1) {
write('\n');
}
super.processingInstruction(target, data);
} catch( IOException e ) {
throw new SAXException(e);
}
}
////////////////////////////////////////////////////////////////////
// Convenience methods.
////////////////////////////////////////////////////////////////////
/**
* Start a new element without a qname or attributes.
*
* <p>This method will provide a default empty attribute
* list and an empty string for the qualified name.
* It invokes {@link
* #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
*/
public void startElement (String uri, String localName)
throws SAXException
{
startElement(uri, localName, "", EMPTY_ATTS);
}
/**
* Start a new element without a qname, attributes or a Namespace URI.
*
* <p>This method will provide an empty string for the
* Namespace URI, and empty string for the qualified name,
* and a default empty attribute list. It invokes
* #startElement(String, String, String, Attributes)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the start tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
*/
public void startElement (String localName)
throws SAXException
{
startElement("", localName, "", EMPTY_ATTS);
}
/**
* End an element without a qname.
*
* <p>This method will supply an empty string for the qName.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see #endElement(String, String, String)
*/
public void endElement (String uri, String localName)
throws SAXException
{
endElement(uri, localName, "");
}
/**
* End an element without a Namespace URI or qname.
*
* <p>This method will supply an empty string for the qName
* and an empty string for the Namespace URI.
* It invokes {@link #endElement(String, String, String)}
* directly.</p>
*
* @param localName The element's local name.
* @exception org.xml.sax.SAXException If there is an error
* writing the end tag, or if a handler further down
* the filter chain raises an exception.
* @see #endElement(String, String, String)
*/
public void endElement (String localName)
throws SAXException
{
endElement("", localName, "");
}
/**
* Write an element with character data content.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param qName The element's default qualified name.
* @param atts The element's attributes.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String uri, String localName,
String qName, Attributes atts,
String content)
throws SAXException
{
startElement(uri, localName, qName, atts);
characters(content);
endElement(uri, localName, qName);
}
/**
* Write an element with character data content but no attributes.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag. This method provides an empty string
* for the qname and an empty attribute list.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param uri The element's Namespace URI.
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String uri, String localName, String content)
throws SAXException
{
dataElement(uri, localName, "", EMPTY_ATTS, content);
}
/**
* Write an element with character data content but no attributes or Namespace URI.
*
* <p>This is a convenience method to write a complete element
* with character data content, including the start tag
* and end tag. The method provides an empty string for the
* Namespace URI, and empty string for the qualified name,
* and an empty attribute list.</p>
*
* <p>This method invokes
* {@link #startElement(String, String, String, Attributes)},
* followed by
* {@link #characters(String)}, followed by
* {@link #endElement(String, String, String)}.</p>
*
* @param localName The element's local name.
* @param content The character data content.
* @exception org.xml.sax.SAXException If there is an error
* writing the empty tag, or if a handler further down
* the filter chain raises an exception.
* @see #startElement(String, String, String, Attributes)
* @see #characters(String)
* @see #endElement(String, String, String)
*/
public void dataElement (String localName, String content)
throws SAXException
{
dataElement("", localName, "", EMPTY_ATTS, content);
}
/**
* Write a string of character data, with XML escaping.
*
* <p>This is a convenience method that takes an XML
* String, converts it to a character array, then invokes
* {@link #characters(char[], int, int)}.</p>
*
* @param data The character data.
* @exception org.xml.sax.SAXException If there is an error
* writing the string, or if a handler further down
* the filter chain raises an exception.
* @see #characters(char[], int, int)
*/
public void characters (String data) throws SAXException {
try {
if (!startTagIsClosed) {
write('>');
startTagIsClosed = true;
}
char ch[] = data.toCharArray();
characters(ch, 0, ch.length);
} catch( IOException e ) {
throw new SAXException(e);
}
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Write a raw character.
*
* @param c The character to write.
*/
protected final void write (char c) throws IOException {
output.write(c);
}
/**
* Write a raw string.
*/
protected final void write(String s) throws IOException {
output.write(s);
}
/**
* Write out an attribute list, escaping values.
*
* The names will have prefixes added to them.
*
* @param atts The attribute list to write.
*/
private void writeAttributes (Attributes atts) throws IOException {
int len = atts.getLength();
for (int i = 0; i < len; i++) {
char ch[] = atts.getValue(i).toCharArray();
write(' ');
write(atts.getQName(i));
write("=\"");
writeEsc(ch, 0, ch.length, true);
write('"');
}
}
/**
* Write an array of data characters with escaping.
*
* @param ch The array of characters.
* @param start The starting position.
* @param length The number of characters to use.
* @param isAttVal true if this is an attribute value literal.
*/
private void writeEsc (char ch[], int start,
int length, boolean isAttVal)
throws IOException
{
escapeHandler.escape(ch, start, length, isAttVal, output);
}
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
private final Attributes EMPTY_ATTS = new AttributesImpl();
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private int elementLevel = 0;
private Writer output;
private String encoding;
private boolean writeXmlDecl = true;
/**
* This string will be written right after the xml declaration
* without any escaping. Useful for generating a boiler-plate DOCTYPE decl
* , PIs, and comments.
*/
private String header=null;
private final CharacterEscapeHandler escapeHandler;
private boolean startTagIsClosed = true;
}
// end of XMLWriter.java

View File

@@ -0,0 +1,316 @@
/*
* Copyright (c) 1997, 2010, 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 com.sun.xml.internal.bind.unmarshaller;
import java.util.Enumeration;
import javax.xml.bind.ValidationEventLocator;
import javax.xml.bind.helpers.AbstractUnmarshallerImpl;
import javax.xml.bind.helpers.ValidationEventLocatorImpl;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.LocatorEx;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;
/**
* Visits a W3C DOM tree and generates SAX2 events from it.
*
* <p>
* This class is just intended to be used by {@link AbstractUnmarshallerImpl}.
* The javax.xml.bind.helpers package is generally a wrong place to put
* classes like this.
*
* @author <ul><li>Kohsuke Kawaguchi, Sun Microsystems, Inc.</li></ul>
* @since JAXB1.0
*/
public class DOMScanner implements LocatorEx,InfosetScanner/*<Node> --- but can't do this to protect 1.0 clients, or can I? */
{
/** reference to the current node being scanned - used for determining
* location info for validation events */
private Node currentNode = null;
/** To save memory, only one instance of AttributesImpl will be used. */
private final AttributesImpl atts = new AttributesImpl();
/** This handler will receive SAX2 events. */
private ContentHandler receiver=null;
private Locator locator=this;
public DOMScanner() {
}
/**
* Configures the locator object that the SAX {@link ContentHandler} will see.
*/
public void setLocator( Locator loc ) {
this.locator = loc;
}
public void scan(Object node) throws SAXException {
if( node instanceof Document ) {
scan( (Document)node );
} else {
scan( (Element)node );
}
}
public void scan( Document doc ) throws SAXException {
scan( doc.getDocumentElement() );
}
public void scan( Element e) throws SAXException {
setCurrentLocation( e );
receiver.setDocumentLocator(locator);
receiver.startDocument();
NamespaceSupport nss = new NamespaceSupport();
buildNamespaceSupport( nss, e.getParentNode() );
for( Enumeration en = nss.getPrefixes(); en.hasMoreElements(); ) {
String prefix = (String)en.nextElement();
receiver.startPrefixMapping( prefix, nss.getURI(prefix) );
}
visit(e);
for( Enumeration en = nss.getPrefixes(); en.hasMoreElements(); ) {
String prefix = (String)en.nextElement();
receiver.endPrefixMapping( prefix );
}
setCurrentLocation( e );
receiver.endDocument();
}
/**
* Parses a subtree starting from the element e and
* reports SAX2 events to the specified handler.
*
* @deprecated in JAXB 2.0
* Use {@link #scan(Element)}
*/
public void parse( Element e, ContentHandler handler ) throws SAXException {
// it might be better to set receiver at the constructor.
receiver = handler;
setCurrentLocation( e );
receiver.startDocument();
receiver.setDocumentLocator(locator);
visit(e);
setCurrentLocation( e );
receiver.endDocument();
}
/**
* Similar to the parse method but it visits the ancestor nodes
* and properly emulate the all in-scope namespace declarations.
*
* @deprecated in JAXB 2.0
* Use {@link #scan(Element)}
*/
public void parseWithContext( Element e, ContentHandler handler ) throws SAXException {
setContentHandler(handler);
scan(e);
}
/**
* Recursively visit ancestors and build up {@link NamespaceSupport} oject.
*/
private void buildNamespaceSupport(NamespaceSupport nss, Node node) {
if(node==null || node.getNodeType()!=Node.ELEMENT_NODE)
return;
buildNamespaceSupport( nss, node.getParentNode() );
nss.pushContext();
NamedNodeMap atts = node.getAttributes();
for( int i=0; i<atts.getLength(); i++ ) {
Attr a = (Attr)atts.item(i);
if( "xmlns".equals(a.getPrefix()) ) {
nss.declarePrefix( a.getLocalName(), a.getValue() );
continue;
}
if( "xmlns".equals(a.getName()) ) {
nss.declarePrefix( "", a.getValue() );
continue;
}
}
}
/**
* Visits an element and its subtree.
*/
public void visit( Element e ) throws SAXException {
setCurrentLocation( e );
final NamedNodeMap attributes = e.getAttributes();
atts.clear();
int len = attributes==null ? 0: attributes.getLength();
for( int i=len-1; i>=0; i-- ) {
Attr a = (Attr)attributes.item(i);
String name = a.getName();
// start namespace binding
if(name.startsWith("xmlns")) {
if(name.length()==5) {
receiver.startPrefixMapping( "", a.getValue() );
} else {
String localName = a.getLocalName();
if(localName==null) {
// DOM built without namespace support has this problem
localName = name.substring(6);
}
receiver.startPrefixMapping( localName, a.getValue() );
}
continue;
}
String uri = a.getNamespaceURI();
if(uri==null) uri="";
String local = a.getLocalName();
if(local==null) local = a.getName();
// add other attributes to the attribute list
// that we will pass to the ContentHandler
atts.addAttribute(
uri,
local,
a.getName(),
"CDATA",
a.getValue());
}
String uri = e.getNamespaceURI();
if(uri==null) uri="";
String local = e.getLocalName();
String qname = e.getTagName();
if(local==null) local = qname;
receiver.startElement( uri, local, qname, atts );
// visit its children
NodeList children = e.getChildNodes();
int clen = children.getLength();
for( int i=0; i<clen; i++ )
visit(children.item(i));
setCurrentLocation( e );
receiver.endElement( uri, local, qname );
// call the endPrefixMapping method
for( int i=len-1; i>=0; i-- ) {
Attr a = (Attr)attributes.item(i);
String name = a.getName();
if(name.startsWith("xmlns")) {
if(name.length()==5)
receiver.endPrefixMapping("");
else
receiver.endPrefixMapping(a.getLocalName());
}
}
}
private void visit( Node n ) throws SAXException {
setCurrentLocation( n );
// if a case statement gets too big, it should be made into a separate method.
switch(n.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
String value = n.getNodeValue();
receiver.characters( value.toCharArray(), 0, value.length() );
break;
case Node.ELEMENT_NODE:
visit( (Element)n );
break;
case Node.ENTITY_REFERENCE_NODE:
receiver.skippedEntity(n.getNodeName());
break;
case Node.PROCESSING_INSTRUCTION_NODE:
ProcessingInstruction pi = (ProcessingInstruction)n;
receiver.processingInstruction(pi.getTarget(),pi.getData());
break;
}
}
private void setCurrentLocation( Node currNode ) {
currentNode = currNode;
}
/**
* The same as {@link #getCurrentElement()} but
* better typed.
*/
public Node getCurrentLocation() {
return currentNode;
}
public Object getCurrentElement() {
return currentNode;
}
public LocatorEx getLocator() {
return this;
}
public void setContentHandler(ContentHandler handler) {
this.receiver = handler;
}
public ContentHandler getContentHandler() {
return this.receiver;
}
// LocatorEx implementation
public String getPublicId() { return null; }
public String getSystemId() { return null; }
public int getLineNumber() { return -1; }
public int getColumnNumber() { return -1; }
public ValidationEventLocator getLocation() {
return new ValidationEventLocatorImpl(getCurrentLocation());
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.unmarshaller;
import javax.xml.bind.Binder;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.LocatorEx;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* Visits a DOM-ish API and generates SAX events.
*
* <p>
* This interface is not tied to any particular DOM API.
* Used by the {@link Binder}.
*
* <p>
* Since we are parsing a DOM-ish tree, I don't think this
* scanner itself will ever find an error, so this class
* doesn't have its own error reporting scheme.
*
* <p>
* This interface <b>MAY NOT</b> be implemented by the generated
* runtime nor the generated code. We may add new methods on
* this interface later. This is to be implemented by the static runtime
* only.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
* @since 2.0
*/
public interface InfosetScanner<XmlNode> {
/**
* Parses the given DOM-ish element/document and generates
* SAX events.
*
* @throws ClassCastException
* If the type of the node is not known to this implementation.
*
* @throws SAXException
* If the {@link ContentHandler} throws a {@link SAXException}.
* Do not throw an exception just because the scanner failed
* (if that can happen we need to change the API.)
*/
void scan( XmlNode node ) throws SAXException;
/**
* Sets the {@link ContentHandler}.
*
* This handler receives the SAX events.
*/
void setContentHandler( ContentHandler handler );
ContentHandler getContentHandler();
/**
* Gets the current element we are parsing.
*
* <p>
* This method could
* be called from the {@link ContentHandler#startElement(String, String, String, Attributes)}
* or {@link ContentHandler#endElement(String, String, String)}.
*
* <p>
* Otherwise the behavior of this method is undefined.
*
* @return
* never return null.
*/
XmlNode getCurrentElement();
LocatorEx getLocator();
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.unmarshaller;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*
* @since JAXB1.0
*/
public class Messages
{
public static String format( String property ) {
return format( property, null );
}
public static String format( String property, Object arg1 ) {
return format( property, new Object[]{arg1} );
}
public static String format( String property, Object arg1, Object arg2 ) {
return format( property, new Object[]{arg1,arg2} );
}
public 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. */
public static String format( String property, Object[] args ) {
String text = ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
//
//
// Message resources
//
//
public static final String UNEXPECTED_ENTER_ELEMENT = // arg:2
"ContentHandlerEx.UnexpectedEnterElement";
public static final String UNEXPECTED_LEAVE_ELEMENT = // arg:2
"ContentHandlerEx.UnexpectedLeaveElement";
public static final String UNEXPECTED_ENTER_ATTRIBUTE =// arg:2
"ContentHandlerEx.UnexpectedEnterAttribute";
public static final String UNEXPECTED_LEAVE_ATTRIBUTE =// arg:2
"ContentHandlerEx.UnexpectedLeaveAttribute";
public static final String UNEXPECTED_TEXT =// arg:1
"ContentHandlerEx.UnexpectedText";
public static final String UNEXPECTED_LEAVE_CHILD = // 0 args
"ContentHandlerEx.UnexpectedLeaveChild";
public static final String UNEXPECTED_ROOT_ELEMENT = // 1 arg
"SAXUnmarshallerHandlerImpl.UnexpectedRootElement";
// Usage not found. TODO Remove
// public static final String UNEXPECTED_ROOT_ELEMENT2 = // 3 arg
// "SAXUnmarshallerHandlerImpl.UnexpectedRootElement2";
public static final String UNDEFINED_PREFIX = // 1 arg
"Util.UndefinedPrefix";
public static final String NULL_READER = // 0 args
"Unmarshaller.NullReader";
public static final String ILLEGAL_READER_STATE = // 1 arg
"Unmarshaller.IllegalReaderState";
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.unmarshaller;
import org.xml.sax.SAXException;
/**
* Runs by UnmarshallingContext after all the parsing is done.
*
* Primarily used to resolve forward IDREFs, but it can run any action.
*
* @author Kohsuke Kawaguchi
*/
public interface Patcher {
/**
* Runs an post-action.
*
* @throws SAXException
* if an error is found during the action, it should be reporeted to the context.
* The context may then throw a {@link SAXException} to abort the processing,
* and that's when you can throw a {@link SAXException}.
*/
void run() throws SAXException;
}

View File

@@ -0,0 +1,654 @@
/*
* Copyright (c) 1997, 2011, 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.
*/
// AttributesImpl.java - default implementation of Attributes.
// http://www.saxproject.org
// Written by David Megginson
// NO WARRANTY! This class is in the public domain.
package com.sun.xml.internal.bind.util;
import org.xml.sax.Attributes;
/**
* Default implementation of the Attributes interface.
*
* <blockquote>
* <em>This module, both source code and documentation, is in the
* Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
* See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
* for further information.
* </blockquote>
*
* <p>This class provides a default implementation of the SAX2
* {@link org.xml.sax.Attributes Attributes} interface, with the
* addition of manipulators so that the list can be modified or
* reused.</p>
*
* <p>There are two typical uses of this class:</p>
*
* <ol>
* <li>to take a persistent snapshot of an Attributes object
* in a {@link org.xml.sax.ContentHandler#startElement startElement} event; or</li>
* <li>to construct or modify an Attributes object in a SAX2 driver or filter.</li>
* </ol>
*
* <p>This class replaces the now-deprecated SAX1 {@link
* org.xml.sax.helpers.AttributeListImpl AttributeListImpl}
* class; in addition to supporting the updated Attributes
* interface rather than the deprecated {@link org.xml.sax.AttributeList
* AttributeList} interface, it also includes a much more efficient
* implementation using a single array rather than a set of Vectors.</p>
*
* @since JAXB1.0
* @since SAX 2.0
* @author David Megginson
* @version 2.0.1 (sax2r2)
*/
public class AttributesImpl implements Attributes
{
////////////////////////////////////////////////////////////////////
// Constructors.
////////////////////////////////////////////////////////////////////
/**
* Construct a new, empty AttributesImpl object.
*/
public AttributesImpl ()
{
length = 0;
data = null;
}
/**
* Copy an existing Attributes object.
*
* <p>This constructor is especially useful inside a
* {@link org.xml.sax.ContentHandler#startElement startElement} event.</p>
*
* @param atts The existing Attributes object.
*/
public AttributesImpl (Attributes atts)
{
setAttributes(atts);
}
////////////////////////////////////////////////////////////////////
// Implementation of org.xml.sax.Attributes.
////////////////////////////////////////////////////////////////////
/**
* Return the number of attributes in the list.
*
* @return The number of attributes in the list.
* @see org.xml.sax.Attributes#getLength()
*/
public int getLength ()
{
return length;
}
/**
* Return an attribute's Namespace URI.
*
* @param index The attribute's index (zero-based).
* @return The Namespace URI, the empty string if none is
* available, or null if the index is out of range.
* @see org.xml.sax.Attributes#getURI(int)
*/
public String getURI (int index)
{
if (index >= 0 && index < length) {
return data[index*5];
} else {
return null;
}
}
/**
* Return an attribute's local name.
*
* @param index The attribute's index (zero-based).
* @return The attribute's local name, the empty string if
* none is available, or null if the index if out of range.
* @see org.xml.sax.Attributes#getLocalName(int)
*/
public String getLocalName (int index)
{
if (index >= 0 && index < length) {
return data[index*5+1];
} else {
return null;
}
}
/**
* Return an attribute's qualified (prefixed) name.
*
* @param index The attribute's index (zero-based).
* @return The attribute's qualified name, the empty string if
* none is available, or null if the index is out of bounds.
* @see org.xml.sax.Attributes#getQName(int)
*/
public String getQName (int index)
{
if (index >= 0 && index < length) {
return data[index*5+2];
} else {
return null;
}
}
/**
* Return an attribute's type by index.
*
* @param index The attribute's index (zero-based).
* @return The attribute's type, "CDATA" if the type is unknown, or null
* if the index is out of bounds.
* @see org.xml.sax.Attributes#getType(int)
*/
public String getType (int index)
{
if (index >= 0 && index < length) {
return data[index*5+3];
} else {
return null;
}
}
/**
* Return an attribute's value by index.
*
* @param index The attribute's index (zero-based).
* @return The attribute's value or null if the index is out of bounds.
* @see org.xml.sax.Attributes#getValue(int)
*/
public String getValue (int index)
{
if (index >= 0 && index < length) {
return data[index*5+4];
} else {
return null;
}
}
/**
* Look up an attribute's index by Namespace name.
*
* <p>In many cases, it will be more efficient to look up the name once and
* use the index query methods rather than using the name query methods
* repeatedly.</p>
*
* @param uri The attribute's Namespace URI, or the empty
* string if none is available.
* @param localName The attribute's local name.
* @return The attribute's index, or -1 if none matches.
* @see org.xml.sax.Attributes#getIndex(java.lang.String,java.lang.String)
*/
public int getIndex (String uri, String localName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i].equals(uri) && data[i+1].equals(localName)) {
return i / 5;
}
}
return -1;
}
/**
* Can be used if parameters are interned.
*/
public int getIndexFast(String uri, String localName) {
for (int i = (length-1)*5; i>=0; i-=5) {
// local names tend to be different, so test it first
if (data[i + 1] == localName && data[i] == uri ) {
return i / 5;
}
}
return -1;
}
/**
* Look up an attribute's index by qualified (prefixed) name.
*
* @param qName The qualified name.
* @return The attribute's index, or -1 if none matches.
* @see org.xml.sax.Attributes#getIndex(java.lang.String)
*/
public int getIndex (String qName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i+2].equals(qName)) {
return i / 5;
}
}
return -1;
}
/**
* Look up an attribute's type by Namespace-qualified name.
*
* @param uri The Namespace URI, or the empty string for a name
* with no explicit Namespace URI.
* @param localName The local name.
* @return The attribute's type, or null if there is no
* matching attribute.
* @see org.xml.sax.Attributes#getType(java.lang.String,java.lang.String)
*/
public String getType (String uri, String localName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i].equals(uri) && data[i+1].equals(localName)) {
return data[i+3];
}
}
return null;
}
/**
* Look up an attribute's type by qualified (prefixed) name.
*
* @param qName The qualified name.
* @return The attribute's type, or null if there is no
* matching attribute.
* @see org.xml.sax.Attributes#getType(java.lang.String)
*/
public String getType (String qName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i+2].equals(qName)) {
return data[i+3];
}
}
return null;
}
/**
* Look up an attribute's value by Namespace-qualified name.
*
* @param uri The Namespace URI, or the empty string for a name
* with no explicit Namespace URI.
* @param localName The local name.
* @return The attribute's value, or null if there is no
* matching attribute.
* @see org.xml.sax.Attributes#getValue(java.lang.String,java.lang.String)
*/
public String getValue (String uri, String localName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i].equals(uri) && data[i+1].equals(localName)) {
return data[i+4];
}
}
return null;
}
/**
* Look up an attribute's value by qualified (prefixed) name.
*
* @param qName The qualified name.
* @return The attribute's value, or null if there is no
* matching attribute.
* @see org.xml.sax.Attributes#getValue(java.lang.String)
*/
public String getValue (String qName)
{
int max = length * 5;
for (int i = 0; i < max; i += 5) {
if (data[i+2].equals(qName)) {
return data[i+4];
}
}
return null;
}
////////////////////////////////////////////////////////////////////
// Manipulators.
////////////////////////////////////////////////////////////////////
/**
* Clear the attribute list for reuse.
*
* <p>Note that little memory is freed by this call:
* the current array is kept so it can be
* reused.</p>
*/
public void clear ()
{
if (data != null) {
for (int i = 0; i < (length * 5); i++)
data [i] = null;
}
length = 0;
}
/**
* Copy an entire Attributes object.
*
* <p>It may be more efficient to reuse an existing object
* rather than constantly allocating new ones.</p>
*
* @param atts The attributes to copy.
*/
public void setAttributes (Attributes atts)
{
clear();
length = atts.getLength();
if (length > 0) {
data = new String[length*5];
for (int i = 0; i < length; i++) {
data[i*5] = atts.getURI(i);
data[i*5+1] = atts.getLocalName(i);
data[i*5+2] = atts.getQName(i);
data[i*5+3] = atts.getType(i);
data[i*5+4] = atts.getValue(i);
}
}
}
/**
* Add an attribute to the end of the list.
*
* <p>For the sake of speed, this method does no checking
* to see if the attribute is already in the list: that is
* the responsibility of the application.</p>
*
* @param uri The Namespace URI, or the empty string if
* none is available or Namespace processing is not
* being performed.
* @param localName The local name, or the empty string if
* Namespace processing is not being performed.
* @param qName The qualified (prefixed) name, or the empty string
* if qualified names are not available.
* @param type The attribute type as a string.
* @param value The attribute value.
*/
public void addAttribute (String uri, String localName, String qName,
String type, String value)
{
ensureCapacity(length+1);
data[length*5] = uri;
data[length*5+1] = localName;
data[length*5+2] = qName;
data[length*5+3] = type;
data[length*5+4] = value;
length++;
}
/**
* Set an attribute in the list.
*
* <p>For the sake of speed, this method does no checking
* for name conflicts or well-formedness: such checks are the
* responsibility of the application.</p>
*
* @param index The index of the attribute (zero-based).
* @param uri The Namespace URI, or the empty string if
* none is available or Namespace processing is not
* being performed.
* @param localName The local name, or the empty string if
* Namespace processing is not being performed.
* @param qName The qualified name, or the empty string
* if qualified names are not available.
* @param type The attribute type as a string.
* @param value The attribute value.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setAttribute (int index, String uri, String localName,
String qName, String type, String value)
{
if (index >= 0 && index < length) {
data[index*5] = uri;
data[index*5+1] = localName;
data[index*5+2] = qName;
data[index*5+3] = type;
data[index*5+4] = value;
} else {
badIndex(index);
}
}
/**
* Remove an attribute from the list.
*
* @param index The index of the attribute (zero-based).
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void removeAttribute (int index)
{
if (index >= 0 && index < length) {
if (index < length - 1) {
System.arraycopy(data, (index+1)*5, data, index*5,
(length-index-1)*5);
}
index = (length - 1) * 5;
data [index++] = null;
data [index++] = null;
data [index++] = null;
data [index++] = null;
data [index] = null;
length--;
} else {
badIndex(index);
}
}
/**
* Set the Namespace URI of a specific attribute.
*
* @param index The index of the attribute (zero-based).
* @param uri The attribute's Namespace URI, or the empty
* string for none.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setURI (int index, String uri)
{
if (index >= 0 && index < length) {
data[index*5] = uri;
} else {
badIndex(index);
}
}
/**
* Set the local name of a specific attribute.
*
* @param index The index of the attribute (zero-based).
* @param localName The attribute's local name, or the empty
* string for none.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setLocalName (int index, String localName)
{
if (index >= 0 && index < length) {
data[index*5+1] = localName;
} else {
badIndex(index);
}
}
/**
* Set the qualified name of a specific attribute.
*
* @param index The index of the attribute (zero-based).
* @param qName The attribute's qualified name, or the empty
* string for none.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setQName (int index, String qName)
{
if (index >= 0 && index < length) {
data[index*5+2] = qName;
} else {
badIndex(index);
}
}
/**
* Set the type of a specific attribute.
*
* @param index The index of the attribute (zero-based).
* @param type The attribute's type.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setType (int index, String type)
{
if (index >= 0 && index < length) {
data[index*5+3] = type;
} else {
badIndex(index);
}
}
/**
* Set the value of a specific attribute.
*
* @param index The index of the attribute (zero-based).
* @param value The attribute's value.
* @exception java.lang.ArrayIndexOutOfBoundsException When the
* supplied index does not point to an attribute
* in the list.
*/
public void setValue (int index, String value)
{
if (index >= 0 && index < length) {
data[index*5+4] = value;
} else {
badIndex(index);
}
}
////////////////////////////////////////////////////////////////////
// Internal methods.
////////////////////////////////////////////////////////////////////
/**
* Ensure the internal array's capacity.
*
* @param n The minimum number of attributes that the array must
* be able to hold.
*/
private void ensureCapacity (int n) {
if (n <= 0) {
return;
}
int max;
if (data == null || data.length == 0) {
max = 25;
}
else if (data.length >= n * 5) {
return;
}
else {
max = data.length;
}
while (max < n * 5) {
max *= 2;
}
String newData[] = new String[max];
if (length > 0) {
System.arraycopy(data, 0, newData, 0, length*5);
}
data = newData;
}
/**
* Report a bad array index in a manipulator.
*
* @param index The index to report.
* @exception java.lang.ArrayIndexOutOfBoundsException Always.
*/
private void badIndex (int index)
throws ArrayIndexOutOfBoundsException
{
String msg =
"Attempt to modify attribute at illegal index: " + index;
throw new ArrayIndexOutOfBoundsException(msg);
}
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
int length;
String data [];
}
// end of AttributesImpl.java

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.util;
/**
* Class defined for safe calls of getClassLoader methods of any kind (context/system/class
* classloader. This MUST be package private and defined in every package which
* uses such invocations.
* @author snajper
*/
class SecureLoader {
static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
}
static ClassLoader getClassClassLoader(final Class c) {
if (System.getSecurityManager() == null) {
return c.getClassLoader();
} else {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return c.getClassLoader();
}
});
}
}
static ClassLoader getSystemClassLoader() {
if (System.getSecurityManager() == null) {
return ClassLoader.getSystemClassLoader();
} else {
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return ClassLoader.getSystemClassLoader();
}
});
}
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.util;
import javax.xml.bind.helpers.ValidationEventLocatorImpl;
import com.sun.xml.internal.bind.ValidationEventLocatorEx;
/**
*
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class ValidationEventLocatorExImpl
extends ValidationEventLocatorImpl implements ValidationEventLocatorEx {
private final String fieldName;
public ValidationEventLocatorExImpl( Object target, String fieldName ) {
super(target);
this.fieldName = fieldName;
}
public String getFieldName() {
return fieldName;
}
/**
* Returns a nice string representation for better debug experience.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[url=");
buf.append(getURL());
buf.append(",line=");
buf.append(getLineNumber());
buf.append(",column=");
buf.append(getColumnNumber());
buf.append(",node=");
buf.append(getNode());
buf.append(",object=");
buf.append(getObject());
buf.append(",field=");
buf.append(getFieldName());
buf.append("]");
return buf.toString();
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.util;
import java.net.URL;
/**
* Finds out where a class file is loaded from.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class Which {
public static String which( Class clazz ) {
return which( clazz.getName(), SecureLoader.getClassClassLoader(clazz));
}
/**
* Search the specified classloader for the given classname.
*
* @param classname the fully qualified name of the class to search for
* @param loader the classloader to search
* @return the source location of the resource, or null if it wasn't found
*/
public static String which(String classname, ClassLoader loader) {
String classnameAsResource = classname.replace('.', '/') + ".class";
if(loader == null) {
loader = SecureLoader.getSystemClassLoader();
}
URL it = loader.getResource(classnameAsResource);
if (it != null) {
return it.toString();
} else {
return null;
}
}
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.xml.internal.bind.Util;
/**
* Creates new instances of classes.
*
* <p>
* This code handles the case where the class is not public or the constructor is
* not public.
*
* @since 2.0
* @author Kohsuke Kawaguchi
*/
public final class ClassFactory {
private static final Class[] emptyClass = new Class[0];
private static final Object[] emptyObject = new Object[0];
private static final Logger logger = Util.getClassLogger();
/**
* Cache from a class to its default constructor.
*
* To avoid synchronization among threads, we use {@link ThreadLocal}.
*/
private static final ThreadLocal<Map<Class, WeakReference<Constructor>>> tls = new ThreadLocal<Map<Class,WeakReference<Constructor>>>() {
@Override
public Map<Class,WeakReference<Constructor>> initialValue() {
return new WeakHashMap<Class,WeakReference<Constructor>>();
}
};
public static void cleanCache() {
if (tls != null) {
try {
tls.remove();
} catch (Exception e) {
logger.log(Level.WARNING, "Unable to clean Thread Local cache of classes used in Unmarshaller: {0}", e.getLocalizedMessage());
}
}
}
/**
* Creates a new instance of the class but throw exceptions without catching it.
*/
public static <T> T create0( final Class<T> clazz ) throws IllegalAccessException, InvocationTargetException, InstantiationException {
Map<Class,WeakReference<Constructor>> m = tls.get();
Constructor<T> cons = null;
WeakReference<Constructor> consRef = m.get(clazz);
if(consRef!=null)
cons = consRef.get();
if(cons==null) {
try {
cons = clazz.getDeclaredConstructor(emptyClass);
} catch (NoSuchMethodException e) {
logger.log(Level.INFO,"No default constructor found on "+clazz,e);
NoSuchMethodError exp;
if(clazz.getDeclaringClass()!=null && !Modifier.isStatic(clazz.getModifiers())) {
exp = new NoSuchMethodError(Messages.NO_DEFAULT_CONSTRUCTOR_IN_INNER_CLASS.format(clazz.getName()));
} else {
exp = new NoSuchMethodError(e.getMessage());
}
exp.initCause(e);
throw exp;
}
int classMod = clazz.getModifiers();
if(!Modifier.isPublic(classMod) || !Modifier.isPublic(cons.getModifiers())) {
// attempt to make it work even if the constructor is not accessible
try {
cons.setAccessible(true);
} catch(SecurityException e) {
// but if we don't have a permission to do so, work gracefully.
logger.log(Level.FINE,"Unable to make the constructor of "+clazz+" accessible",e);
throw e;
}
}
m.put(clazz,new WeakReference<Constructor>(cons));
}
return cons.newInstance(emptyObject);
}
/**
* The same as {@link #create0} but with an error handling to make
* the instantiation error fatal.
*/
public static <T> T create( Class<T> clazz ) {
try {
return create0(clazz);
} catch (InstantiationException e) {
logger.log(Level.INFO,"failed to create a new instance of "+clazz,e);
throw new InstantiationError(e.toString());
} catch (IllegalAccessException e) {
logger.log(Level.INFO,"failed to create a new instance of "+clazz,e);
throw new IllegalAccessError(e.toString());
} catch (InvocationTargetException e) {
Throwable target = e.getTargetException();
// most likely an error on the user's code.
// just let it through for the ease of debugging
if(target instanceof RuntimeException)
throw (RuntimeException)target;
// error. just forward it for the ease of debugging
if(target instanceof Error)
throw (Error)target;
// a checked exception.
// not sure how we should report this error,
// but for now we just forward it by wrapping it into a runtime exception
throw new IllegalStateException(target);
}
}
/**
* Call a method in the factory class to get the object.
*/
public static Object create(Method method) {
Throwable errorMsg;
try {
return method.invoke(null, emptyObject);
} catch (InvocationTargetException ive) {
Throwable target = ive.getTargetException();
if(target instanceof RuntimeException)
throw (RuntimeException)target;
if(target instanceof Error)
throw (Error)target;
throw new IllegalStateException(target);
} catch (IllegalAccessException e) {
logger.log(Level.INFO,"failed to create a new instance of "+method.getReturnType().getName(),e);
throw new IllegalAccessError(e.toString());
} catch (IllegalArgumentException iae){
logger.log(Level.INFO,"failed to create a new instance of "+method.getReturnType().getName(),iae);
errorMsg = iae;
} catch (NullPointerException npe){
logger.log(Level.INFO,"failed to create a new instance of "+method.getReturnType().getName(),npe);
errorMsg = npe;
} catch (ExceptionInInitializerError eie){
logger.log(Level.INFO,"failed to create a new instance of "+method.getReturnType().getName(),eie);
errorMsg = eie;
}
NoSuchMethodError exp;
exp = new NoSuchMethodError(errorMsg.getMessage());
exp.initCause(errorMsg);
throw exp;
}
/**
* Infers the instanciable implementation class that can be assigned to the given field type.
*
* @return null
* if inference fails.
*/
public static <T> Class<? extends T> inferImplClass(Class<T> fieldType, Class[] knownImplClasses) {
if(!fieldType.isInterface())
return fieldType;
for( Class<?> impl : knownImplClasses ) {
if(fieldType.isAssignableFrom(impl))
return impl.asSubclass(fieldType);
}
// if we can't find an implementation class,
// let's just hope that we will never need to create a new object,
// and returns null
return null;
}
}

View File

@@ -0,0 +1,322 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import com.sun.istack.internal.FinalArrayList;
import com.sun.xml.internal.bind.Util;
import com.sun.xml.internal.bind.api.JAXBRIContext;
import com.sun.xml.internal.bind.api.TypeReference;
import com.sun.xml.internal.bind.v2.model.annotation.RuntimeAnnotationReader;
import com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl;
import com.sun.xml.internal.bind.v2.util.TypeCast;
/**
* This class is responsible for producing RI JAXBContext objects. In
* the RI, this is the class that the javax.xml.bind.context.factory
* property will point to.
*
* <p>
* Used to create JAXBContext objects for v1.0.1 and forward
*
* @since 2.0
* @author Kohsuke Kawaguchi
*/
public class ContextFactory {
/**
* The API will invoke this method via reflection
*/
public static JAXBContext createContext(Class[] classes, Map<String,Object> properties ) throws JAXBException {
// fool-proof check, and copy the map to make it easier to find unrecognized properties.
if(properties==null)
properties = Collections.emptyMap();
else
properties = new HashMap<String,Object>(properties);
String defaultNsUri = getPropertyValue(properties,JAXBRIContext.DEFAULT_NAMESPACE_REMAP,String.class);
Boolean c14nSupport = getPropertyValue(properties,JAXBRIContext.CANONICALIZATION_SUPPORT,Boolean.class);
if(c14nSupport==null)
c14nSupport = false;
Boolean disablesecurityProcessing = getPropertyValue(properties, JAXBRIContext.DISABLE_XML_SECURITY, Boolean.class);
if (disablesecurityProcessing==null)
disablesecurityProcessing = false;
Boolean allNillable = getPropertyValue(properties,JAXBRIContext.TREAT_EVERYTHING_NILLABLE,Boolean.class);
if(allNillable==null)
allNillable = false;
Boolean retainPropertyInfo = getPropertyValue(properties, JAXBRIContext.RETAIN_REFERENCE_TO_INFO, Boolean.class);
if(retainPropertyInfo==null)
retainPropertyInfo = false;
Boolean supressAccessorWarnings = getPropertyValue(properties, JAXBRIContext.SUPRESS_ACCESSOR_WARNINGS, Boolean.class);
if(supressAccessorWarnings==null)
supressAccessorWarnings = false;
Boolean improvedXsiTypeHandling = getPropertyValue(properties, JAXBRIContext.IMPROVED_XSI_TYPE_HANDLING, Boolean.class);
if (improvedXsiTypeHandling == null) {
String improvedXsiSystemProperty = Util.getSystemProperty(JAXBRIContext.IMPROVED_XSI_TYPE_HANDLING);
if (improvedXsiSystemProperty == null) {
improvedXsiTypeHandling = true;
} else {
improvedXsiTypeHandling = Boolean.valueOf(improvedXsiSystemProperty);
}
}
Boolean xmlAccessorFactorySupport = getPropertyValue(properties,
JAXBRIContext.XMLACCESSORFACTORY_SUPPORT,Boolean.class);
if(xmlAccessorFactorySupport==null){
xmlAccessorFactorySupport = false;
Util.getClassLogger().log(Level.FINE, "Property " +
JAXBRIContext.XMLACCESSORFACTORY_SUPPORT +
"is not active. Using JAXB's implementation");
}
RuntimeAnnotationReader ar = getPropertyValue(properties,JAXBRIContext.ANNOTATION_READER,RuntimeAnnotationReader.class);
Collection<TypeReference> tr = getPropertyValue(properties, JAXBRIContext.TYPE_REFERENCES, Collection.class);
if (tr == null) {
tr = Collections.<TypeReference>emptyList();
}
Map<Class,Class> subclassReplacements;
try {
subclassReplacements = TypeCast.checkedCast(
getPropertyValue(properties, JAXBRIContext.SUBCLASS_REPLACEMENTS, Map.class), Class.class, Class.class);
} catch (ClassCastException e) {
throw new JAXBException(Messages.INVALID_TYPE_IN_MAP.format(),e);
}
if(!properties.isEmpty()) {
throw new JAXBException(Messages.UNSUPPORTED_PROPERTY.format(properties.keySet().iterator().next()));
}
JAXBContextImpl.JAXBContextBuilder builder = new JAXBContextImpl.JAXBContextBuilder();
builder.setClasses(classes);
builder.setTypeRefs(tr);
builder.setSubclassReplacements(subclassReplacements);
builder.setDefaultNsUri(defaultNsUri);
builder.setC14NSupport(c14nSupport);
builder.setAnnotationReader(ar);
builder.setXmlAccessorFactorySupport(xmlAccessorFactorySupport);
builder.setAllNillable(allNillable);
builder.setRetainPropertyInfo(retainPropertyInfo);
builder.setSupressAccessorWarnings(supressAccessorWarnings);
builder.setImprovedXsiTypeHandling(improvedXsiTypeHandling);
builder.setDisableSecurityProcessing(disablesecurityProcessing);
return builder.build();
}
/**
* If a key is present in the map, remove the value and return it.
*/
private static <T> T getPropertyValue(Map<String, Object> properties, String keyName, Class<T> type ) throws JAXBException {
Object o = properties.get(keyName);
if(o==null) return null;
properties.remove(keyName);
if(!type.isInstance(o))
throw new JAXBException(Messages.INVALID_PROPERTY_VALUE.format(keyName,o));
else
return type.cast(o);
}
/**
*
* @param classes
* @param typeRefs
* @param subclassReplacements
* @param defaultNsUri
* @param c14nSupport
* @param ar
* @param xmlAccessorFactorySupport
* @param allNillable
* @param retainPropertyInfo
* @return
* @throws JAXBException
* @deprecated use createContext(Class[] classes, Map<String,Object> properties) method instead
*/
@Deprecated
public static JAXBRIContext createContext( Class[] classes,
Collection<TypeReference> typeRefs, Map<Class,Class> subclassReplacements,
String defaultNsUri, boolean c14nSupport, RuntimeAnnotationReader ar,
boolean xmlAccessorFactorySupport, boolean allNillable, boolean retainPropertyInfo) throws JAXBException {
return createContext(classes, typeRefs, subclassReplacements,
defaultNsUri, c14nSupport, ar, xmlAccessorFactorySupport,
allNillable, retainPropertyInfo, false);
}
/**
*
* @param classes
* @param typeRefs
* @param subclassReplacements
* @param defaultNsUri
* @param c14nSupport
* @param ar
* @param xmlAccessorFactorySupport
* @param allNillable
* @param retainPropertyInfo
* @param improvedXsiTypeHandling
* @return
* @throws JAXBException
* @deprecated use createContext( Class[] classes, Map<String,Object> properties) method instead
*/
@Deprecated
public static JAXBRIContext createContext( Class[] classes,
Collection<TypeReference> typeRefs, Map<Class,Class> subclassReplacements,
String defaultNsUri, boolean c14nSupport, RuntimeAnnotationReader ar,
boolean xmlAccessorFactorySupport, boolean allNillable, boolean retainPropertyInfo, boolean improvedXsiTypeHandling) throws JAXBException {
JAXBContextImpl.JAXBContextBuilder builder = new JAXBContextImpl.JAXBContextBuilder();
builder.setClasses(classes);
builder.setTypeRefs(typeRefs);
builder.setSubclassReplacements(subclassReplacements);
builder.setDefaultNsUri(defaultNsUri);
builder.setC14NSupport(c14nSupport);
builder.setAnnotationReader(ar);
builder.setXmlAccessorFactorySupport(xmlAccessorFactorySupport);
builder.setAllNillable(allNillable);
builder.setRetainPropertyInfo(retainPropertyInfo);
builder.setImprovedXsiTypeHandling(improvedXsiTypeHandling);
return builder.build();
}
/**
* The API will invoke this method via reflection.
*/
public static JAXBContext createContext( String contextPath,
ClassLoader classLoader, Map<String,Object> properties ) throws JAXBException {
FinalArrayList<Class> classes = new FinalArrayList<Class>();
StringTokenizer tokens = new StringTokenizer(contextPath,":");
List<Class> indexedClasses;
// at least on of these must be true per package
boolean foundObjectFactory;
boolean foundJaxbIndex;
while(tokens.hasMoreTokens()) {
foundObjectFactory = foundJaxbIndex = false;
String pkg = tokens.nextToken();
// look for ObjectFactory and load it
final Class<?> o;
try {
o = classLoader.loadClass(pkg+".ObjectFactory");
classes.add(o);
foundObjectFactory = true;
} catch (ClassNotFoundException e) {
// not necessarily an error
}
// look for jaxb.index and load the list of classes
try {
indexedClasses = loadIndexedClasses(pkg, classLoader);
} catch (IOException e) {
//TODO: think about this more
throw new JAXBException(e);
}
if(indexedClasses != null) {
classes.addAll(indexedClasses);
foundJaxbIndex = true;
}
if( !(foundObjectFactory || foundJaxbIndex) ) {
throw new JAXBException( Messages.BROKEN_CONTEXTPATH.format(pkg));
}
}
return createContext(classes.toArray(new Class[classes.size()]),properties);
}
/**
* Look for jaxb.index file in the specified package and load it's contents
*
* @param pkg package name to search in
* @param classLoader ClassLoader to search in
* @return a List of Class objects to load, null if there weren't any
* @throws IOException if there is an error reading the index file
* @throws JAXBException if there are any errors in the index file
*/
private static List<Class> loadIndexedClasses(String pkg, ClassLoader classLoader) throws IOException, JAXBException {
final String resource = pkg.replace('.', '/') + "/jaxb.index";
final InputStream resourceAsStream = classLoader.getResourceAsStream(resource);
if (resourceAsStream == null) {
return null;
}
BufferedReader in =
new BufferedReader(new InputStreamReader(resourceAsStream, "UTF-8"));
try {
FinalArrayList<Class> classes = new FinalArrayList<Class>();
String className = in.readLine();
while (className != null) {
className = className.trim();
if (className.startsWith("#") || (className.length() == 0)) {
className = in.readLine();
continue;
}
if (className.endsWith(".class")) {
throw new JAXBException(Messages.ILLEGAL_ENTRY.format(className));
}
try {
classes.add(classLoader.loadClass(pkg + '.' + className));
} catch (ClassNotFoundException e) {
throw new JAXBException(Messages.ERROR_LOADING_CLASS.format(className, resource),e);
}
className = in.readLine();
}
return classes;
} finally {
in.close();
}
}
public static final String USE_JAXB_PROPERTIES = "_useJAXBProperties";
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 1997, 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 com.sun.xml.internal.bind.v2;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Formats error messages.
*/
public enum Messages {
ILLEGAL_ENTRY, // 1 arg
ERROR_LOADING_CLASS, // 2 args
INVALID_PROPERTY_VALUE, // 2 args
UNSUPPORTED_PROPERTY, // 1 arg
BROKEN_CONTEXTPATH, // 1 arg
NO_DEFAULT_CONSTRUCTOR_IN_INNER_CLASS, // 1 arg
INVALID_TYPE_IN_MAP, // 0args
INVALID_JAXP_IMPLEMENTATION, // 1 arg
JAXP_SUPPORTED_PROPERTY, // 1 arg
JAXP_UNSUPPORTED_PROPERTY, // 1 arg
JAXP_XML_SECURITY_DISABLED, // no arg
JAXP_EXTERNAL_ACCESS_CONFIGURED, // no arg
;
private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
public String toString() {
return format();
}
public String format( Object... args ) {
return MessageFormat.format( rb.getString(name()), args );
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2;
/**
* Place holder for TODOs.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public abstract class TODO {
/**
* When this method is called,
* that means we need to check the spec and corrects
* the behavior.
*
* Search the usage of this method.
*/
public static void checkSpec() {}
public static void checkSpec(String comment) {}
/**
* When this method iscalled,
* that means the current code is a mock up and
* it needs to be properly implemented later.
*/
public static void prototype() {}
public static void prototype(String comment) {}
/**
* When this method is called, it means that there is an
* unimplemeted portion of the spec in the schema generator.
*/
public static void schemaGenerator(String comment) {}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2;
import javax.xml.XMLConstants;
/**
* Well-known namespace URIs.
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com), Martin Grebac (martin.grebac@oracle.com)
* @since 2.0
*/
public abstract class WellKnownNamespace {
private WellKnownNamespace() {} // no instanciation please
/**
* @deprecated Use javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI instead;
* @return
* @throws CloneNotSupportedException
*/
@Deprecated()
public static final String XML_SCHEMA = XMLConstants.W3C_XML_SCHEMA_NS_URI;
/**
* @deprecated Use javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI instead
* @return
* @throws CloneNotSupportedException
*/
@Deprecated()
public static final String XML_SCHEMA_INSTANCE = XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI;
/**
* @deprecated Use javax.xml.XMLConstants.XML_NS_URI instead;
* @return
* @throws CloneNotSupportedException
*/
@Deprecated()
public static final String XML_NAMESPACE_URI = XMLConstants.XML_NS_URI;
public static final String XOP = "http://www.w3.org/2004/08/xop/include";
public static final String SWA_URI = "http://ws-i.org/profiles/basic/1.1/xsd";
public static final String XML_MIME_URI = "http://www.w3.org/2005/05/xmlmime";
public static final String JAXB = "http://java.sun.com/xml/ns/jaxb";
}

View File

@@ -0,0 +1,191 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.bytecode;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.xml.internal.bind.Util;
/**
* Replaces a few constant pool tokens from a class "template" and then loads it into the VM.
*
* @author Kohsuke Kawaguchi
*/
public final class ClassTailor {
private ClassTailor() {} // no instanciation please
private static final Logger logger = Util.getClassLogger();
/**
* Returns the class name in the JVM format (such as "java/lang/String")
*/
public static String toVMClassName( Class c ) {
assert !c.isPrimitive();
if(c.isArray())
// I have no idea why it is designed like this, but javap says so.
return toVMTypeName(c);
return c.getName().replace('.','/');
}
public static String toVMTypeName( Class c ) {
if(c.isArray()) {
// TODO: study how an array type is encoded.
return '['+toVMTypeName(c.getComponentType());
}
if(c.isPrimitive()) {
if(c==Boolean.TYPE) return "Z";
if(c==Character.TYPE) return "C";
if(c==Byte.TYPE) return "B";
if(c==Double.TYPE) return "D";
if(c==Float.TYPE) return "F";
if(c==Integer.TYPE) return "I";
if(c==Long.TYPE) return "J";
if(c==Short.TYPE) return "S";
throw new IllegalArgumentException(c.getName());
}
return 'L'+c.getName().replace('.','/')+';';
}
public static byte[] tailor( Class templateClass, String newClassName, String... replacements ) {
String vmname = toVMClassName(templateClass);
return tailor(
SecureLoader.getClassClassLoader(templateClass).getResourceAsStream(vmname+".class"),
vmname, newClassName, replacements );
}
/**
* Customizes a class file by replacing constant pools.
*
* @param image
* The image of the template class.
* @param replacements
* A list of pair of strings that specify the substitution
* {@code String[]{search_0, replace_0, search_1, replace_1, ..., search_n, replace_n }}
*
* The search strings found in the constant pool will be replaced by the corresponding
* replacement string.
*/
public static byte[] tailor( InputStream image, String templateClassName, String newClassName, String... replacements ) {
DataInputStream in = new DataInputStream(image);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
DataOutputStream out = new DataOutputStream(baos);
// skip until the constant pool count
long l = in.readLong();
out.writeLong(l);
// read the constant pool size
short count = in.readShort();
out.writeShort(count);
// replace constant pools
for( int i=0; i<count; i++ ) {
byte tag = in.readByte();
out.writeByte(tag);
switch(tag) {
case 0:
// this isn't described in the spec,
// but class files often seem to have this '0' tag.
// we can apparently just ignore it, but not sure
// what this really means.
break;
case 1: // CONSTANT_UTF8
{
String value = in.readUTF();
if(value.equals(templateClassName))
value = newClassName;
else {
for( int j=0; j<replacements.length; j+=2 )
if(value.equals(replacements[j])) {
value = replacements[j+1];
break;
}
}
out.writeUTF(value);
}
break;
case 3: // CONSTANT_Integer
case 4: // CONSTANT_Float
out.writeInt(in.readInt());
break;
case 5: // CONSTANT_Long
case 6: // CONSTANT_Double
i++; // doubles and longs take two entries
out.writeLong(in.readLong());
break;
case 7: // CONSTANT_Class
case 8: // CONSTANT_String
out.writeShort(in.readShort());
break;
case 9: // CONSTANT_Fieldref
case 10: // CONSTANT_Methodref
case 11: // CONSTANT_InterfaceMethodref
case 12: // CONSTANT_NameAndType
out.writeInt(in.readInt());
break;
default:
throw new IllegalArgumentException("Unknown constant type "+tag);
}
}
// then copy the rest
byte[] buf = new byte[512];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
in.close();
out.close();
// by now we got the properly tailored class file image
return baos.toByteArray();
} catch( IOException e ) {
// never happen
logger.log(Level.WARNING,"failed to tailor",e);
return null;
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.bytecode;
/**
* Class defined for safe calls of getClassLoader methods of any kind (context/system/class
* classloader. This MUST be package private and defined in every package which
* uses such invocations.
* @author snajper
*/
class SecureLoader {
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();
}
});
}
}
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();
}
});
}
}
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,102 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import com.sun.xml.internal.bind.v2.model.core.ErrorHandler;
import com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationException;
/**
* {@link AnnotationReader} that reads annotation from classes,
* not from external binding files.
*
* This is meant to be used as a convenient partial implementation.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public abstract class AbstractInlineAnnotationReaderImpl<T,C,F,M>
implements AnnotationReader<T,C,F,M> {
private ErrorHandler errorHandler;
public void setErrorHandler(ErrorHandler errorHandler) {
if(errorHandler==null)
throw new IllegalArgumentException();
this.errorHandler = errorHandler;
}
/**
* Always return a non-null valid {@link ErrorHandler}
*/
public final ErrorHandler getErrorHandler() {
assert errorHandler!=null : "error handler must be set before use";
return errorHandler;
}
public final <A extends Annotation> A getMethodAnnotation(Class<A> annotation, M getter, M setter, Locatable srcPos) {
A a1 = getter==null?null:getMethodAnnotation(annotation,getter,srcPos);
A a2 = setter==null?null:getMethodAnnotation(annotation,setter,srcPos);
if(a1==null) {
if(a2==null)
return null;
else
return a2;
} else {
if(a2==null)
return a1;
else {
// both are present
getErrorHandler().error(new IllegalAnnotationException(
Messages.DUPLICATE_ANNOTATIONS.format(
annotation.getName(), fullName(getter),fullName(setter)),
a1, a2 ));
// recover by ignoring one of them
return a1;
}
}
}
public boolean hasMethodAnnotation(Class<? extends Annotation> annotation, String propertyName, M getter, M setter, Locatable srcPos) {
boolean x = ( getter != null && hasMethodAnnotation(annotation, getter) );
boolean y = ( setter != null && hasMethodAnnotation(annotation, setter) );
if(x && y) {
// both are present. have getMethodAnnotation report an error
getMethodAnnotation(annotation,getter,setter,srcPos);
}
return x||y;
}
/**
* Gets the fully-qualified name of the method.
*
* Used for error messages.
*/
protected abstract String fullName(M m);
}

View File

@@ -0,0 +1,162 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.bind.v2.model.core.ErrorHandler;
/**
* Reads annotations for the given property.
*
* <p>
* This is the lowest abstraction that encapsulates the difference
* between reading inline annotations and external binding files.
*
* <p>
* Because the former operates on a {@link Field} and {@link Method}
* while the latter operates on a "property", the methods defined
* on this interface takes both, and the callee gets to choose which
* to use.
*
* <p>
* Most of the get method takes {@link Locatable}, which points to
* the place/context in which the annotation is read. The returned
* annotation also implements {@link Locatable} (so that it can
* point to the place where the annotation is placed), and its
* {@link Locatable#getUpstream()} will return the given
* {@link Locatable}.
*
*
* <p>
* Errors found during reading annotations are reported through the error handler.
* A valid {@link ErrorHandler} must be registered before the {@link AnnotationReader}
* is used.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public interface AnnotationReader<T,C,F,M> {
/**
* Sets the error handler that receives errors found
* during reading annotations.
*
* @param errorHandler
* must not be null.
*/
void setErrorHandler(ErrorHandler errorHandler);
/**
* Reads an annotation on a property that consists of a field.
*/
<A extends Annotation> A getFieldAnnotation(Class<A> annotation,
F field, Locatable srcpos);
/**
* Checks if the given field has an annotation.
*/
boolean hasFieldAnnotation(Class<? extends Annotation> annotationType, F field);
/**
* Checks if a class has the annotation.
*/
boolean hasClassAnnotation(C clazz, Class<? extends Annotation> annotationType);
/**
* Gets all the annotations on a field.
*/
Annotation[] getAllFieldAnnotations(F field, Locatable srcPos);
/**
* Reads an annotation on a property that consists of a getter and a setter.
*
*/
<A extends Annotation> A getMethodAnnotation(Class<A> annotation,
M getter, M setter, Locatable srcpos);
/**
* Checks if the given method has an annotation.
*/
boolean hasMethodAnnotation(Class<? extends Annotation> annotation, String propertyName, M getter, M setter, Locatable srcPos);
/**
* Gets all the annotations on a method.
*
* @param srcPos
* the location from which this annotation is read.
*/
Annotation[] getAllMethodAnnotations(M method, Locatable srcPos);
// TODO: we do need this to read certain annotations,
// but that shows inconsistency wrt the spec. consult the spec team about the abstraction.
<A extends Annotation> A getMethodAnnotation(Class<A> annotation, M method, Locatable srcpos );
boolean hasMethodAnnotation(Class<? extends Annotation> annotation, M method );
/**
* Reads an annotation on a parameter of the method.
*
* @return null
* if the annotation was not found.
*/
@Nullable
<A extends Annotation> A getMethodParameterAnnotation(
Class<A> annotation, M method, int paramIndex, Locatable srcPos );
/**
* Reads an annotation on a class.
*/
@Nullable
<A extends Annotation> A getClassAnnotation(Class<A> annotation, C clazz, Locatable srcpos) ;
/**
* Reads an annotation on the package that the given class belongs to.
*/
@Nullable
<A extends Annotation> A getPackageAnnotation(Class<A> annotation, C clazz, Locatable srcpos);
/**
* Reads a value of an annotation that returns a Class object.
*
* <p>
* Depending on the underlying reflection library, you can't always
* obtain the {@link Class} object directly (see the Annotation Processing MirrorTypeException
* for example), so use this method to avoid that.
*
* @param name
* The name of the annotation parameter to be read.
*/
T getClassValue( Annotation a, String name );
/**
* Similar to {@link #getClassValue(Annotation, String)} method but
* obtains an array parameter.
*/
T[] getClassArrayValue( Annotation a, String name );
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
/**
* Implemented by objects that can have annotations.
*
* @author Kohsuke Kawaguchi
*/
public interface AnnotationSource {
/**
* Gets the value of the specified annotation from the given property.
*
* <p>
* When this method is used for a property that consists of a getter and setter,
* it returns the annotation on either of those methods. If both methods have
* the same annotation, it is an error.
*
* @return
* null if the annotation is not present.
*/
<A extends Annotation> A readAnnotation(Class<A> annotationType);
/**
* Returns true if the property has the specified annotation.
* <p>
* Short for <code>readAnnotation(annotationType)!=null</code>,
* but this method is typically faster.
*/
boolean hasAnnotation(Class<? extends Annotation> annotationType);
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* {@link Locatable} implementation for a class.
*
* @author Kohsuke Kawaguchi
*/
public class ClassLocatable<C> implements Locatable {
private final Locatable upstream;
private final C clazz;
private final Navigator<?,C,?,?> nav;
public ClassLocatable(Locatable upstream, C clazz, Navigator<?,C,?,?> nav) {
this.upstream = upstream;
this.clazz = clazz;
this.nav = nav;
}
public Locatable getUpstream() {
return upstream;
}
public Location getLocation() {
return nav.getClassLocation(clazz);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* {@link Locatable} implementation for a field.
*
* @author Kohsuke Kawaguchi
*/
public class FieldLocatable<F> implements Locatable {
private final Locatable upstream;
private final F field;
private final Navigator<?,?,F,?> nav;
public FieldLocatable(Locatable upstream, F field, Navigator<?,?,F,?> nav) {
this.upstream = upstream;
this.field = field;
this.nav = nav;
}
public Locatable getUpstream() {
return upstream;
}
public Location getLocation() {
return nav.getFieldLocation(field);
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
class Init {
static Quick[] getAll() {
return new Quick[] {new XmlAttributeQuick(null, null), new XmlElementQuick(null, null), new XmlElementDeclQuick(null, null), new XmlElementRefQuick(null, null), new XmlElementRefsQuick(null, null), new XmlEnumQuick(null, null), new XmlRootElementQuick(null, null), new XmlSchemaQuick(null, null), new XmlSchemaTypeQuick(null, null), new XmlTransientQuick(null, null), new XmlTypeQuick(null, null), new XmlValueQuick(null, null)};
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* {@link Location} that is chained.
*
* <p>
* {@link Locatable} forms a tree structure, where each {@link Locatable}
* points back to the upstream {@link Locatable}.
* For example, imagine {@link Locatable} X that points to a particular annotation,
* whose upstream is {@link Locatable} Y, which points to a particular method
* (on which the annotation is put), whose upstream is {@link Locatable} Z,
* which points to a particular class (in which the method is defined),
* whose upstream is {@link Locatable} W,
* which points to another class (which refers to the class Z), and so on.
*
* <p>
* This chain will be turned into a list when we report the error to users.
* This allows them to know where the error happened
* and why that place became relevant.
*
* @author Kohsuke Kawaguchi
*/
public interface Locatable {
/**
* Gets the upstream {@link Location} information.
*
* @return
* can be null.
*/
Locatable getUpstream();
/**
* Gets the location object that this object points to.
*
* This operation could be inefficient and costly.
*/
Location getLocation();
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* {@link Annotation} that also implements {@link Locatable}.
*
* @author Kohsuke Kawaguchi
*/
public class LocatableAnnotation implements InvocationHandler, Locatable, Location {
private final Annotation core;
private final Locatable upstream;
/**
* Wraps the annotation into a proxy so that the returned object will also implement
* {@link Locatable}.
*/
public static <A extends Annotation> A create( A annotation, Locatable parentSourcePos ) {
if(annotation==null) return null;
Class<? extends Annotation> type = annotation.annotationType();
if(quicks.containsKey(type)) {
// use the existing proxy implementation if available
return (A)quicks.get(type).newInstance(parentSourcePos,annotation);
}
// otherwise take the slow route
ClassLoader cl = SecureLoader.getClassClassLoader(LocatableAnnotation.class);
try {
Class loadableT = Class.forName(type.getName(), false, cl);
if(loadableT !=type)
return annotation; // annotation type not loadable from this class loader
return (A)Proxy.newProxyInstance(cl,
new Class[]{ type, Locatable.class },
new LocatableAnnotation(annotation,parentSourcePos));
} catch (ClassNotFoundException e) {
// annotation not loadable
return annotation;
} catch (IllegalArgumentException e) {
// Proxy.newProxyInstance throws this if it cannot resolve this annotation
// in this classloader
return annotation;
}
}
LocatableAnnotation(Annotation core, Locatable upstream) {
this.core = core;
this.upstream = upstream;
}
public Locatable getUpstream() {
return upstream;
}
public Location getLocation() {
return this;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if(method.getDeclaringClass()==Locatable.class)
return method.invoke(this,args);
if(Modifier.isStatic(method.getModifiers()))
// malicious code can pass in a static Method object.
// doing method.invoke() would end up executing it,
// so we need to protect against it.
throw new IllegalArgumentException();
return method.invoke(core,args);
} catch (InvocationTargetException e) {
if(e.getTargetException()!=null)
throw e.getTargetException();
throw e;
}
}
public String toString() {
return core.toString();
}
/**
* List of {@link Quick} implementations keyed by their annotation type.
*/
private static final Map<Class,Quick> quicks = new HashMap<Class, Quick>();
static {
for( Quick q : Init.getAll() ) {
quicks.put(q.annotationType(),q);
}
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.text.MessageFormat;
import java.util.ResourceBundle;
/**
* Message resources
*/
enum Messages {
// AnnotationParser
DUPLICATE_ANNOTATIONS,
CLASS_NOT_FOUND
;
private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
public String toString() {
return format();
}
public String format( Object... args ) {
return MessageFormat.format( rb.getString(name()), args );
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* {@link Locatable} implementation for a method.
*
* @author Kohsuke Kawaguchi
*/
public class MethodLocatable<M> implements Locatable {
private final Locatable upstream;
private final M method;
private final Navigator<?,?,?,M> nav;
public MethodLocatable(Locatable upstream, M method, Navigator<?,?,?,M> nav) {
this.upstream = upstream;
this.method = method;
this.nav = nav;
}
public Locatable getUpstream() {
return upstream;
}
public Location getLocation() {
return nav.getMethodLocation(method);
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import com.sun.xml.internal.bind.v2.runtime.Location;
/**
* Base implementation of {@link Locatable} {@link Annotation}.
*
* <p>
* Derived classes of this class is provided for annotations that are commonly
* used in JAXB, to improve the performance of {@link LocatableAnnotation#create}.
*
* @author Kohsuke Kawaguchi
*/
public /*so that our code generator can refer to this class*/ abstract class Quick implements Annotation, Locatable, Location {
private final Locatable upstream;
protected Quick(Locatable upstream) {
this.upstream = upstream;
}
/**
* Gets the annotation object that this object is wrapping.
*/
protected abstract Annotation getAnnotation();
/**
* Factory method to create a new instance of the same kind.
* A {@link Quick} object also works as a factory of itself
*/
protected abstract Quick newInstance( Locatable upstream, Annotation core );
public final Location getLocation() {
return this;
}
public final Locatable getUpstream() {
return upstream;
}
public final String toString() {
return getAnnotation().toString();
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
/**
* @author Kohsuke Kawaguchi
*/
public interface RuntimeAnnotationReader extends AnnotationReader<Type,Class,Field,Method> {
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
/**
* {@link AnnotationReader} that uses {@code java.lang.reflect} to
* read annotations from class files.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public final class RuntimeInlineAnnotationReader extends AbstractInlineAnnotationReaderImpl<Type,Class,Field,Method>
implements RuntimeAnnotationReader {
public <A extends Annotation> A getFieldAnnotation(Class<A> annotation, Field field, Locatable srcPos) {
return LocatableAnnotation.create(field.getAnnotation(annotation),srcPos);
}
public boolean hasFieldAnnotation(Class<? extends Annotation> annotationType, Field field) {
return field.isAnnotationPresent(annotationType);
}
public boolean hasClassAnnotation(Class clazz, Class<? extends Annotation> annotationType) {
return clazz.isAnnotationPresent(annotationType);
}
public Annotation[] getAllFieldAnnotations(Field field, Locatable srcPos) {
Annotation[] r = field.getAnnotations();
for( int i=0; i<r.length; i++ ) {
r[i] = LocatableAnnotation.create(r[i],srcPos);
}
return r;
}
public <A extends Annotation> A getMethodAnnotation(Class<A> annotation, Method method, Locatable srcPos) {
return LocatableAnnotation.create(method.getAnnotation(annotation),srcPos);
}
public boolean hasMethodAnnotation(Class<? extends Annotation> annotation, Method method) {
return method.isAnnotationPresent(annotation);
}
public Annotation[] getAllMethodAnnotations(Method method, Locatable srcPos) {
Annotation[] r = method.getAnnotations();
for( int i=0; i<r.length; i++ ) {
r[i] = LocatableAnnotation.create(r[i],srcPos);
}
return r;
}
public <A extends Annotation> A getMethodParameterAnnotation(Class<A> annotation, Method method, int paramIndex, Locatable srcPos) {
Annotation[] pa = method.getParameterAnnotations()[paramIndex];
for( Annotation a : pa ) {
if(a.annotationType()==annotation)
return LocatableAnnotation.create((A)a,srcPos);
}
return null;
}
public <A extends Annotation> A getClassAnnotation(Class<A> a, Class clazz, Locatable srcPos) {
return LocatableAnnotation.create(((Class<?>)clazz).getAnnotation(a),srcPos);
}
/**
* Cache for package-level annotations.
*/
private final Map<Class<? extends Annotation>,Map<Package,Annotation>> packageCache =
new HashMap<Class<? extends Annotation>,Map<Package,Annotation>>();
public <A extends Annotation> A getPackageAnnotation(Class<A> a, Class clazz, Locatable srcPos) {
Package p = clazz.getPackage();
if(p==null) return null;
Map<Package,Annotation> cache = packageCache.get(a);
if(cache==null) {
cache = new HashMap<Package,Annotation>();
packageCache.put(a,cache);
}
if(cache.containsKey(p))
return (A)cache.get(p);
else {
A ann = LocatableAnnotation.create(p.getAnnotation(a),srcPos);
cache.put(p,ann);
return ann;
}
}
public Class getClassValue(Annotation a, String name) {
try {
return (Class)a.annotationType().getMethod(name).invoke(a);
} catch (IllegalAccessException e) {
// impossible
throw new IllegalAccessError(e.getMessage());
} catch (InvocationTargetException e) {
// impossible
throw new InternalError(Messages.CLASS_NOT_FOUND.format(a.annotationType(), e.getMessage()));
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
public Class[] getClassArrayValue(Annotation a, String name) {
try {
return (Class[])a.annotationType().getMethod(name).invoke(a);
} catch (IllegalAccessException e) {
// impossible
throw new IllegalAccessError(e.getMessage());
} catch (InvocationTargetException e) {
// impossible
throw new InternalError(e.getMessage());
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
protected String fullName(Method m) {
return m.getDeclaringClass().getName()+'#'+m.getName();
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.annotation;
/**
* Class defined for safe calls of getClassLoader methods of any kind (context/system/class
* classloader. This MUST be package private and defined in every package which
* uses such invocations.
* @author snajper
*/
class SecureLoader {
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();
}
});
}
}
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();
}
});
}
}
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,72 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlAttribute;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlAttributeQuick
extends Quick
implements XmlAttribute
{
private final XmlAttribute core;
public XmlAttributeQuick(Locatable upstream, XmlAttribute core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlAttributeQuick(upstream, ((XmlAttribute) core));
}
public Class<XmlAttribute> annotationType() {
return XmlAttribute.class;
}
public String name() {
return core.name();
}
public String namespace() {
return core.namespace();
}
public boolean required() {
return core.required();
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlElementDecl;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlElementDeclQuick
extends Quick
implements XmlElementDecl
{
private final XmlElementDecl core;
public XmlElementDeclQuick(Locatable upstream, XmlElementDecl core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlElementDeclQuick(upstream, ((XmlElementDecl) core));
}
public Class<XmlElementDecl> annotationType() {
return XmlElementDecl.class;
}
public String name() {
return core.name();
}
public Class scope() {
return core.scope();
}
public String namespace() {
return core.namespace();
}
public String defaultValue() {
return core.defaultValue();
}
public String substitutionHeadNamespace() {
return core.substitutionHeadNamespace();
}
public String substitutionHeadName() {
return core.substitutionHeadName();
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlElement;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlElementQuick
extends Quick
implements XmlElement
{
private final XmlElement core;
public XmlElementQuick(Locatable upstream, XmlElement core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlElementQuick(upstream, ((XmlElement) core));
}
public Class<XmlElement> annotationType() {
return XmlElement.class;
}
public String name() {
return core.name();
}
public Class type() {
return core.type();
}
public String namespace() {
return core.namespace();
}
public String defaultValue() {
return core.defaultValue();
}
public boolean required() {
return core.required();
}
public boolean nillable() {
return core.nillable();
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlElementRef;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlElementRefQuick
extends Quick
implements XmlElementRef
{
private final XmlElementRef core;
public XmlElementRefQuick(Locatable upstream, XmlElementRef core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlElementRefQuick(upstream, ((XmlElementRef) core));
}
public Class<XmlElementRef> annotationType() {
return XmlElementRef.class;
}
public String name() {
return core.name();
}
public Class type() {
return core.type();
}
public String namespace() {
return core.namespace();
}
public boolean required() {
return core.required();
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlElementRefsQuick
extends Quick
implements XmlElementRefs
{
private final XmlElementRefs core;
public XmlElementRefsQuick(Locatable upstream, XmlElementRefs core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlElementRefsQuick(upstream, ((XmlElementRefs) core));
}
public Class<XmlElementRefs> annotationType() {
return XmlElementRefs.class;
}
public XmlElementRef[] value() {
return core.value();
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlEnum;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlEnumQuick
extends Quick
implements XmlEnum
{
private final XmlEnum core;
public XmlEnumQuick(Locatable upstream, XmlEnum core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlEnumQuick(upstream, ((XmlEnum) core));
}
public Class<XmlEnum> annotationType() {
return XmlEnum.class;
}
public Class value() {
return core.value();
}
}

View File

@@ -0,0 +1,68 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlRootElement;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlRootElementQuick
extends Quick
implements XmlRootElement
{
private final XmlRootElement core;
public XmlRootElementQuick(Locatable upstream, XmlRootElement core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlRootElementQuick(upstream, ((XmlRootElement) core));
}
public Class<XmlRootElement> annotationType() {
return XmlRootElement.class;
}
public String name() {
return core.name();
}
public String namespace() {
return core.namespace();
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlSchemaQuick
extends Quick
implements XmlSchema
{
private final XmlSchema core;
public XmlSchemaQuick(Locatable upstream, XmlSchema core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlSchemaQuick(upstream, ((XmlSchema) core));
}
public Class<XmlSchema> annotationType() {
return XmlSchema.class;
}
public String location() {
return core.location();
}
public String namespace() {
return core.namespace();
}
public XmlNs[] xmlns() {
return core.xmlns();
}
public XmlNsForm elementFormDefault() {
return core.elementFormDefault();
}
public XmlNsForm attributeFormDefault() {
return core.attributeFormDefault();
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlSchemaType;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlSchemaTypeQuick
extends Quick
implements XmlSchemaType
{
private final XmlSchemaType core;
public XmlSchemaTypeQuick(Locatable upstream, XmlSchemaType core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlSchemaTypeQuick(upstream, ((XmlSchemaType) core));
}
public Class<XmlSchemaType> annotationType() {
return XmlSchemaType.class;
}
public String name() {
return core.name();
}
public Class type() {
return core.type();
}
public String namespace() {
return core.namespace();
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlTransient;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlTransientQuick
extends Quick
implements XmlTransient
{
private final XmlTransient core;
public XmlTransientQuick(Locatable upstream, XmlTransient core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlTransientQuick(upstream, ((XmlTransient) core));
}
public Class<XmlTransient> annotationType() {
return XmlTransient.class;
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlType;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlTypeQuick
extends Quick
implements XmlType
{
private final XmlType core;
public XmlTypeQuick(Locatable upstream, XmlType core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlTypeQuick(upstream, ((XmlType) core));
}
public Class<XmlType> annotationType() {
return XmlType.class;
}
public String name() {
return core.name();
}
public String namespace() {
return core.namespace();
}
public String[] propOrder() {
return core.propOrder();
}
public Class factoryClass() {
return core.factoryClass();
}
public String factoryMethod() {
return core.factoryMethod();
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2012, 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 com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlValue;
/**
* <p><b>Auto-generated, do not edit.</b></p>
*
*/
final class XmlValueQuick
extends Quick
implements XmlValue
{
private final XmlValue core;
public XmlValueQuick(Locatable upstream, XmlValue core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlValueQuick(upstream, ((XmlValue) core));
}
public Class<XmlValue> annotationType() {
return XmlValue.class;
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.sun.xml.internal.bind.v2.model.annotation.AnnotationReader;
import com.sun.xml.internal.bind.v2.model.nav.Navigator;
/**
* {@link Adapter} that wraps {@link XmlJavaTypeAdapter}.
*
* @author Kohsuke Kawaguchi
*/
public class Adapter<TypeT,ClassDeclT> {
/**
* The adapter class. Always non-null.
*
* A class that derives from {@link javax.xml.bind.annotation.adapters.XmlAdapter}.
*/
public final ClassDeclT adapterType;
/**
* The type that the JAXB can handle natively.
* The <tt>Default</tt> parameter of <tt>XmlAdapter&lt;Default,Custom></tt>.
*
* Always non-null.
*/
public final TypeT defaultType;
/**
* The type that is stored in memory.
* The <tt>Custom</tt> parameter of <tt>XmlAdapter&lt;Default,Custom></tt>.
*/
public final TypeT customType;
public Adapter(
XmlJavaTypeAdapter spec,
AnnotationReader<TypeT,ClassDeclT,?,?> reader,
Navigator<TypeT,ClassDeclT,?,?> nav) {
this( nav.asDecl(reader.getClassValue(spec,"value")), nav );
}
public Adapter(ClassDeclT adapterType,Navigator<TypeT,ClassDeclT,?,?> nav) {
this.adapterType = adapterType;
TypeT baseClass = nav.getBaseClass(nav.use(adapterType), nav.asDecl(XmlAdapter.class));
// because the parameterization of XmlJavaTypeAdapter requires that the class derives from XmlAdapter.
assert baseClass!=null;
if(nav.isParameterizedType(baseClass))
defaultType = nav.getTypeArgument(baseClass,0);
else
defaultType = nav.ref(Object.class);
if(nav.isParameterizedType(baseClass))
customType = nav.getTypeArgument(baseClass,1);
else
customType = nav.ref(Object.class);
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
/**
* Stand-alone array that can be marshalled/unmarshalled on its own
* (without being part of any encloding {@link ClassInfo}.)
*
* <p>
* Most of the times arrays are treated as properties of their enclosing classes,
* but sometimes we do need to map an array class to its own XML type.
* This object is used for that purpose.
*
* @author Kohsuke Kawaguchi
*/
public interface ArrayInfo<T,C> extends NonElement<T,C> {
/**
* T of T[]. The type of the items of the array.
*
* @return never null
*/
NonElement<T,C> getItemType();
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.namespace.QName;
/**
* Attribute {@link PropertyInfo}.
*
* @author Kohsuke Kawaguchi
*/
public interface AttributePropertyInfo<T,C> extends PropertyInfo<T,C>, NonElementRef<T,C> {
/**
* Gets the type of the attribute.
*
* <p>
* Note that when this property is a collection, this method returns
* the type of each item in the collection.
*
* @return
* always non-null.
*/
NonElement<T,C> getTarget();
/**
* Returns true if this attribute is mandatory.
*/
boolean isRequired();
/**
* Gets the attribute name.
*
* @return
* must be non-null.
*/
QName getXmlName();
Adapter<T,C> getAdapter();
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.namespace.QName;
/**
* JAXB spec designates a few Java classes to be mapped to leaves in XML.
*
* <p>
* Built-in leaves also have another priviledge; specifically, they often
* have more than one XML type names associated with it.
*
* @author Kohsuke Kawaguchi
*/
public interface BuiltinLeafInfo<T,C> extends LeafInfo<T,C> {
/**
* {@inheritDoc}
*
* <p>
* This method returns the 'primary' type name of this built-in leaf,
* which should be used when values of this type are marshalled.
*
* @return
* never null.
*/
public QName getTypeName();
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import java.util.List;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlValue;
/**
* Information about JAXB-bound class.
*
* <p>
* All the JAXB annotations are already reflected to the model so that
* the caller doesn't have to worry about them. For this reason, you
* cannot access annotations on properties.
*
* <h2>XML representation</h2>
* <p>
* A JAXB-bound class always have at least one representation
* (called "type representation"),but it can optionally have another
* representation ("element representation").
*
* <p>
* In the type representaion, a class
* is represented as a set of attributes and (elements or values).
* You can inspect the details of those attributes/elements/values by {@link #getProperties()}.
* This representation corresponds to a complex/simple type in XML Schema.
* You can obtain the schema type name by {@link #getTypeName()}.
*
* <p>
* If a class has an element representation, {@link #isElement()} returns true.
* This representation is mostly similar to the type representation
* except that the whoe attributes/elements/values are wrapped into
* one element. You can obtain the name of this element through {@link #asElement()}.
*
* @author Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public interface ClassInfo<T,C> extends MaybeElement<T,C> {
/**
* Obtains the information about the base class.
*
* @return null
* if this info extends from {@link Object}.
*/
ClassInfo<T,C> getBaseClass();
/**
* Gets the declaration this object is wrapping.
*/
C getClazz();
/**
* Gets the fully-qualified name of the class.
*/
String getName();
/**
* Returns all the properties newly declared in this class.
*
* <p>
* This excludes properties defined in the super class.
*
* <p>
* If the properties are {@link #isOrdered() ordered},
* it will be returned in the order that appear in XML.
* Otherwise it will be returned in no particular order.
*
* <p>
* Properties marked with {@link XmlTransient} will not show up
* in this list. As far as JAXB is concerned, they are considered
* non-existent.
*
* @return
* always non-null, but can be empty.
*/
List<? extends PropertyInfo<T,C>> getProperties();
/**
* Returns true if this class or its ancestor has {@link XmlValue}
* property.
*/
boolean hasValueProperty();
/**
* Gets the property that has the specified name.
*
* <p>
* This is just a convenience method for:
* <pre>
* for( PropertyInfo p : getProperties() ) {
* if(p.getName().equals(name))
* return p;
* }
* return null;
* </pre>
*
* @return null
* if the property was not found.
*
* @see PropertyInfo#getName()
*/
PropertyInfo<T,C> getProperty(String name);
/**
* If the class has properties, return true. This is only
* true if the Collection object returned by {@link #getProperties()}
* is not empty.
*/
boolean hasProperties();
/**
* If this class is abstract and thus shall never be directly instanciated.
*/
boolean isAbstract();
/**
* Returns true if the properties of this class is ordered in XML.
* False if it't not.
*
* <p>
* In RELAX NG context, ordered properties mean &lt;group> and
* unordered properties mean &lt;interleave>.
*/
boolean isOrdered();
/**
* If this class is marked as final and no further extension/restriction is allowed.
*/
boolean isFinal();
/**
* True if there's a known sub-type of this class in {@link TypeInfoSet}.
*/
boolean hasSubClasses();
/**
* Returns true if this bean class has an attribute wildcard.
*
* <p>
* This is true if the class declares an attribute wildcard,
* or it is inherited from its super classes.
*
* @see #inheritsAttributeWildcard()
*/
boolean hasAttributeWildcard();
/**
* Returns true iff this class inherits a wildcard attribute
* from its ancestor classes.
*/
boolean inheritsAttributeWildcard();
/**
* Returns true iff this class declares a wildcard attribute.
*/
boolean declaresAttributeWildcard();
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.namespace.QName;
/**
* {@link TypeInfo} that maps to an element.
*
* Either {@link ElementInfo} or {@link ClassInfo}.
*
* @author Kohsuke Kawaguchi
*/
public interface Element<T,C> extends TypeInfo<T,C> {
/**
* Gets the element name of the class.
*
* @return
* Always non-null.
*/
QName getElementName();
/**
* If this element can substitute another element, return that element.
*
* <p>
* Substitutability of elements are transitive.
*
* @return
* null if no such element exists.
*/
Element<T,C> getSubstitutionHead();
/**
* If non-null, this element is only active inside the given scope.
*/
ClassInfo<T,C> getScope();
}

View File

@@ -0,0 +1,97 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import java.util.Collection;
import javax.xml.bind.JAXBElement;
/**
* A particular use (specialization) of {@link JAXBElement}.
*
* TODO: is ElementInfo adaptable?
*
* @author Kohsuke Kawaguchi
*/
public interface ElementInfo<T,C> extends Element<T,C> {
/**
* Gets the object that represents the value property.
*
* @return
* non-null.
*/
ElementPropertyInfo<T,C> getProperty();
/**
* Short for <code>getProperty().ref().get(0)</code>.
*
* The type of the value this element holds.
*
* Normally, this is the T of {@code JAXBElement<T>}.
* But if the property is adapted, this is the on-the-wire type.
*
* Or if the element has a list of values, then this field
* represents the type of the individual item.
*
* @see #getContentInMemoryType()
*/
NonElement<T,C> getContentType();
/**
* T of {@code JAXBElement<T>}.
*
* <p>
* This is tied to the in-memory representation.
*
* @see #getContentType()
*/
T getContentInMemoryType();
/**
* Returns the representation for {@link JAXBElement}&lt;<i>contentInMemoryType</i>&gt;.
*
* <p>
* This returns the signature in Java and thus isn't affected by the adapter.
*/
T getType();
/**
* @inheritDoc
*
* {@link ElementInfo} can only substitute {@link ElementInfo}.
*/
ElementInfo<T,C> getSubstitutionHead();
/**
* All the {@link ElementInfo}s whose {@link #getSubstitutionHead()} points
* to this object.
*
* @return
* can be empty but never null.
*/
Collection<? extends ElementInfo<T,C>> getSubstitutionMembers();
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import java.util.List;
import javax.xml.namespace.QName;
/**
* Property that maps to an element.
*
* @author Kohsuke Kawaguchi
*/
// TODO: there seems to be too much interactions between switches, and that's no good.
public interface ElementPropertyInfo<T,C> extends PropertyInfo<T,C> {
/**
* Returns the information about the types allowed in this property.
*
* <p>
* In a simple case like the following, an element property only has
* one {@link TypeRef} that points to {@link String} and tag name "foo".
* <pre>
* &#64;XmlElement
* String abc;
* </pre>
*
* <p>
* However, in a general case an element property can be heterogeneous,
* meaning you can put different types in it, each with a different tag name
* (and a few other settings.)
* <pre>
* // list can contain String or Integer.
* &#64;XmlElements({
* &#64;XmlElement(name="a",type=String.class),
* &#64;XmlElement(name="b",type=Integer.class),
* })
* List&lt;Object> abc;
* </pre>
* <p>
* In this case this method returns a list of two {@link TypeRef}s.
*
*
* @return
* Always non-null. Contains at least one entry.
* If {@link #isValueList()}==true, there's always exactly one type.
*/
List<? extends TypeRef<T,C>> getTypes();
/**
* Gets the wrapper element name.
*
* @return
* must be null if {@link #isCollection()}==false or
* if {@link #isValueList()}==true.
*
* Otherwise,
* this can be null (in which case there'll be no wrapper),
* or it can be non-null (in which case there'll be a wrapper)
*/
QName getXmlName();
/**
* Checks if the wrapper element is required.
*
* @return
* Always false if {@link #getXmlName()}==null.
*/
boolean isCollectionRequired();
/**
* Returns true if this property is nillable
* (meaning the absence of the value is treated as nil='true')
*
* <p>
* This method is only used when this property is a collection.
*/
boolean isCollectionNillable();
/**
* Returns true if this property is a collection but its XML
* representation is a list of values, not repeated elements.
*
* <p>
* If {@link #isCollection()}==false, this property is always false.
*
* <p>
* When this flag is true, <tt>getTypes().size()==1</tt> always holds.
*/
boolean isValueList();
/**
* Returns true if this element is mandatory.
*
* For collections, this property isn't used.
* TODO: define the semantics when this is a collection
*/
boolean isRequired();
Adapter<T,C> getAdapter();
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* Individual constant of an enumeration.
*
* <p>
* Javadoc in this class uses the following sample to explain the semantics:
* <pre>
* &#64;XmlEnum(Integer.class)
* enum Foo {
* &#64;XmlEnumValue("1")
* ONE,
* &#64;XmlEnumValue("2")
* TWO
* }
* </pre>
*
* @see EnumLeafInfo
* @author Kohsuke Kawaguchi
*/
public interface EnumConstant<T,C> {
/**
* Gets the {@link EnumLeafInfo} to which this constant belongs to.
*
* @return never null.
*/
EnumLeafInfo<T,C> getEnclosingClass();
/**
* Lexical value of this constant.
*
* <p>
* This value should be evaluated against
* {@link EnumLeafInfo#getBaseType()} to obtain the typed value.
*
* <p>
* This is the same value as written in the {@link XmlEnumValue} annotation.
* In the above example, this method returns "1" and "2".
*
* @return
* never null.
*/
String getLexicalValue();
/**
* Gets the constant name.
*
* <p>
* In the above example this method return "ONE" and "TWO".
*
* @return
* never null. A valid Java identifier.
*/
String getName();
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
/**
* {@link NonElement} that represents an {@link Enum} class.
*
* @author Kohsuke Kawaguchi
*/
public interface EnumLeafInfo<T,C> extends LeafInfo<T,C> {
/**
* The same as {@link #getType()} but an {@link EnumLeafInfo}
* is guaranteed to represent an enum declaration, which is a
* kind of a class declaration.
*
* @return
* always non-null.
*/
C getClazz();
/**
* Returns the base type of the enumeration.
*
* <p>
* For example, with the following enum class, this method
* returns {@link BuiltinLeafInfo} for {@link Integer}.
*
* <pre>
* &amp;XmlEnum(Integer.class)
* enum Foo {
* &amp;XmlEnumValue("1")
* ONE,
* &amp;XmlEnumValue("2")
* TWO
* }
* </pre>
*
* @return
* never null.
*/
NonElement<T,C> getBaseType();
/**
* Returns the read-only list of enumeration constants.
*
* @return
* never null. Can be empty (really?).
*/
Iterable<? extends EnumConstant> getConstants();
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationException;
/**
* listen to static errors found during building a JAXB model from a set of classes.
* Implemented by the client of {@link com.sun.xml.internal.bind.v2.model.impl.ModelBuilder}.
*
* <p>
* All the static errors have to be reported while constructing a
* model, not when a model is used (IOW, until the {@link com.sun.xml.internal.bind.v2.model.impl.ModelBuilder#link} completes.
* Internally, {@link com.sun.xml.internal.bind.v2.model.impl.ModelBuilder} wraps an {@link ErrorHandler} and all the model
* components should report errors through it.
*
* <p>
* {@link IllegalAnnotationException} is a checked exception to remind
* the model classes to report it rather than to throw it.
*
* @see com.sun.xml.internal.bind.v2.model.impl.ModelBuilder
* @author Kohsuke Kawaguchi
*/
public interface ErrorHandler {
/**
* Receives a notification for an error in the annotated code.
*/
void error( IllegalAnnotationException e );
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
/**
* @author Kohsuke Kawaguchi
*/
public enum ID {
ID,IDREF,NONE
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
/**
* Either {@link BuiltinLeafInfo} or {@link EnumLeafInfo}.
*
* <p>
* Those Java types are all mapped to a chunk of text, so we call
* them "leaves".
* This interface represents the mapping information for those
* special Java types.
*
* @author Kohsuke Kawaguchi
*/
public interface LeafInfo<T,C> extends MaybeElement<T,C> {
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import java.util.Map;
import javax.xml.namespace.QName;
/**
* Property that maps to the following schema fragment.
*
* <pre><xmp>
* <xs:complexType>
* <xs:sequence>
* <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">
* <xs:complexType>
* <xs:sequence>
* <xs:element name="key" type="XXXX"/>
* <xs:element name="value" type="YYYY"/>
* </xs:sequence>
* </xs:complexType>
* </xs:element>
* </xs:sequence>
* </xs:complexType>
* </xmp></pre>
*
* <p>
* This property is used to represent a default binding of a {@link Map} property.
* ({@link Map} properties with adapters will be represented by {@link ElementPropertyInfo}.)
*
*
* <h2>Design Thinking Led to This</h2>
* <p>
* I didn't like the idea of adding such a special-purpose {@link PropertyInfo} to a model.
* The alternative was to implicitly assume an adapter, and have internal representation of
* the Entry class ready.
* But the fact that the key type and the value type changes with the parameterization makes
* it very difficult to have such a class (especially inside Annotation Processing, where we can't even generate
* classes.)
*
* @author Kohsuke Kawaguchi
*/
public interface MapPropertyInfo<T,C> extends PropertyInfo<T,C> {
/**
* Gets the wrapper element name.
*
* @return
* always non-null.
*/
QName getXmlName();
/**
* Returns true if this property is nillable
* (meaning the absence of the value is treated as nil='true')
*
* <p>
* This method is only used when this property is a collection.
*/
boolean isCollectionNillable();
/**
* Type of the key of the map. K of {@code HashMap<K,V>}
*
* @return never null.
*/
NonElement<T,C> getKeyType();
/**
* Type of the value of the map. V of {@code HashMap<K,V>}
*
* @return never null.
*/
NonElement<T,C> getValueType();
// TODO
// Adapter<T,C> getKeyAdapter();
// Adapter<T,C> getValueAdapter();
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.namespace.QName;
/**
* Some {@link NonElement} can optionally be an {@link Element}.
*
* This interface captures such characteristics.
*
* @author Kohsuke Kawaguchi
*/
public interface MaybeElement<T,C> extends NonElement<T,C> {
/**
* If the class is bound to an element, return true.
*
* <p>
* Note that when this is true, the class is bound to both an element
* and a type.
*/
boolean isElement();
/**
* Gets the element name of the class, if the class is bound
* to an element.
*
* @return
* non-null iff {@link #isElement()}.
*/
QName getElementName();
/**
* Returns the {@link Element} aspect of this {@link ClassInfo}.
*
* @return
* null if {@link #isElement()}==false, non-null if {@link #isElement()}==true.
*/
Element<T,C> asElement();
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import com.sun.xml.internal.bind.v2.WellKnownNamespace;
import javax.xml.namespace.QName;
/**
* {@link TypeInfo} that maps to an element.
*
* Either {@link LeafInfo} or {@link ClassInfo}.
*
* TODO: better ANYTYPE_NAME.
*
* @author Kohsuke Kawaguchi
*/
public interface NonElement<T,C> extends TypeInfo<T,C> {
public static final QName ANYTYPE_NAME = new QName(WellKnownNamespace.XML_SCHEMA, "anyType");
/**
* Gets the primary XML type ANYTYPE_NAME of the class.
*
* <p>
* A Java type can be mapped to multiple XML types, but one of them is
* considered "primary" and used when we generate a schema.
*
* @return
* null if the object doesn't have an explicit type ANYTYPE_NAME (AKA anonymous.)
*/
QName getTypeName();
/**
* Returns true if this {@link NonElement} maps to text in XML,
* without any attribute nor child elements.
*/
boolean isSimpleType();
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
/**
* Reference to a {@link NonElement}.
*
* This interface defines properties of a reference.
*
* @author Kohsuke Kawaguchi
*/
public interface NonElementRef<T,C> {
/**
* Target of the reference.
*
* @return never null
*/
NonElement<T,C> getTarget();
/**
* Gets the property which is the source of this reference.
*
* @return never null
*/
PropertyInfo<T,C> getSource();
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import java.util.Collection;
import javax.activation.MimeType;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.namespace.QName;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.bind.v2.model.annotation.AnnotationSource;
/**
* Information about a JAXB-bound property.
*
* <p>
* All the JAXB annotations are already incorporated into the model so that
* the caller doesn't have to worry about reading them. For this reason, you
* cannot access annotations on properties directly.
*
* TODO: don't we need a visitor?
*
* @author Kohsuke Kawaguchi
*/
public interface PropertyInfo<T,C> extends AnnotationSource {
/**
* Gets the {@link ClassInfo} or {@link ElementInfo} to which this property belongs.
*/
TypeInfo<T,C> parent();
/**
* Gets the name of the property.
*
* <p>
* For example, "foo" or "bar".
* Generally, a property name is different from XML,
* (although they are often related, as a property name is often
* computed from tag names / attribute names.)
* In fact, <b>property names do not directly affect XML</b>.
* The property name uniquely identifies a property within a class.
*
* @see XmlType#propOrder()
*/
String getName();
/**
* Gets the display name of the property.
*
* <p>
* This is a convenience method for
* {@code parent().getName()+'#'+getName()}.
*/
String displayName();
/**
* Returns true if this is a multi-valued collection property.
* Otherwise false, in which case the property is a single value.
*/
boolean isCollection();
/**
* List of {@link TypeInfo}s that this property references.
*
* This allows the caller to traverse the reference graph without
* getting into the details of each different property type.
*
* @return
* non-null read-only collection.
*/
Collection<? extends TypeInfo<T,C>> ref();
/**
* Gets the kind of this property.
*
* @return
* always non-null.
*/
PropertyKind kind();
/**
* @return
* null if the property is not adapted.
*/
Adapter<T,C> getAdapter();
/**
* Returns the IDness of the value of this element.
*
* @see XmlID
* @see XmlIDREF
*
* @return
* always non-null
*/
ID id();
/**
* Expected MIME type, if any.
*/
MimeType getExpectedMimeType();
/**
* If this is true and this property indeed represents a binary data,
* it should be always inlined.
*/
boolean inlineBinaryData();
/**
* The effective value of {@link XmlSchemaType} annotation, if any.
*
* <p>
* If the property doesn't have {@link XmlSchemaType} annotation,
* this method returns null.
*
* <p>
* Since a type name is a property of a Java type, not a Java property,
* A schema type name of a Java type should be primarily obtained
* by using {@link NonElement#getTypeName()}. This method is to correctly
* implement the ugly semantics of {@link XmlSchemaType} (namely
* when this returns non-null, it overrides the type names of all types
* that are in this property.)
*/
@Nullable QName getSchemaType();
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 1997, 2011, 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 com.sun.xml.internal.bind.v2.model.core;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlInlineBinaryData;
/**
* An Enum that indicates if the property is
* Element, ElementRef, Value, or Attribute.
*
* <p>
* Corresponds to the four different kind of {@link PropertyInfo}.
* @author Bhakti Mehta (bhakti.mehta@sun.com)
*/
public enum PropertyKind {
VALUE(true,false,Integer.MAX_VALUE),
ATTRIBUTE(false,false,Integer.MAX_VALUE),
ELEMENT(true,true,0),
REFERENCE(false,true,1),
MAP(false,true,2),
;
/**
* This kind of property can have {@link XmlMimeType} and {@link XmlInlineBinaryData}
* annotation with it.
*/
public final boolean canHaveXmlMimeType;
/**
* This kind of properties need to show up in {@link XmlType#propOrder()}.
*/
public final boolean isOrdered;
/**
* {@link com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory} benefits from having index numbers assigned to
* {@link #ELEMENT}, {@link #REFERENCE}, and {@link #MAP} in this order.
*/
public final int propertyIndex;
PropertyKind(boolean canHaveExpectedContentType, boolean isOrdered, int propertyIndex) {
this.canHaveXmlMimeType = canHaveExpectedContentType;
this.isOrdered = isOrdered;
this.propertyIndex = propertyIndex;
}
}

Some files were not shown because too many files have changed in this diff Show More