aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMarcel Valovy2014-07-09 15:18:04 (EDT)
committerTomas Kraus2014-07-10 11:55:16 (EDT)
commitd9f3d286a4c85876983b97a76640101d13b9c950 (patch)
tree7a48e8a3c03ade3da5aceca0fc6b323e8aba1c46
parentde2cddc0c43339813c246fdeb065709e41cca2d7 (diff)
downloadeclipselink.runtime-d9f3d286a4c85876983b97a76640101d13b9c950.zip
eclipselink.runtime-d9f3d286a4c85876983b97a76640101d13b9c950.tar.gz
eclipselink.runtime-d9f3d286a4c85876983b97a76640101d13b9c950.tar.bz2
Bug #431803: MOXy support for Bean Validation (JSR-303/349)
WARNING: This commit breaks remote build. Use ant -f antbuild.xml -Dlocal.compdeps=true -Declipse.install.dir=/path/to/eclipse build to build EclipseLink locally. Signed-off-by: Marcel Valovy <marcel.valovy@oracle.com>
-rw-r--r--.gitignore4
-rw-r--r--antbuild.properties6
-rw-r--r--antbuild.xml2
-rw-r--r--buildsystem/compdeps/antbuild.xml73
-rw-r--r--buildsystem/compdeps/org.eclipse.persistence.compdeps/feature.xml26
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/BeanValidationException.java78
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/ValidationException.java4
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/BeanValidationExceptionResource.java44
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java2
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XPathObjectBuilder.java4
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/SchemaModelProject.java102
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/ComplexType.java17
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Element.java162
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Restriction.java177
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/SimpleType.java28
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java10
-rw-r--r--jpa/eclipselink.jpa.test/antbuild.properties14
-rw-r--r--jpa/eclipselink.jpa.test/antbuild.xml26
-rw-r--r--jpa/eclipselink.jpars.test/antbuild.properties1
-rw-r--r--jpa/org.eclipse.persistence.jpa/antbuild.properties28
-rwxr-xr-xmoxy/bin/jaxb-compiler.cmd13
-rwxr-xr-xmoxy/bin/jaxb-compiler.sh1
-rw-r--r--moxy/eclipselink.moxy.test/antbuild.properties15
-rw-r--r--moxy/eclipselink.moxy.test/antbuild.xml74
-rw-r--r--moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/customized_schema.xsd35
-rw-r--r--moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/golden_file.xsd119
-rw-r--r--moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/rich_schema.xsd154
-rw-r--r--moxy/eclipselink.moxy.test/resource/schema1.xsd21
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBSRGTestSuite.java28
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java3
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite5.java43
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/PropertyTypeTestCases.java3
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationBindingsTestCase.java401
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationRuntimeTestCase.java240
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/ContentComparator.java157
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Department.java24
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Drivers.java21
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/DrivingLicense.java77
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Employee.java146
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/casesensitivity/Customer.java4
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmlnametransformer/NameTransformerExceptionTestCases.java14
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/emptyroot/EmptyNullMarshalUnmarshalTestCases.java235
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsNonRootTestCases.java37
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsNamespaceTestCases.java14
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsTestCases.java14
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/SchemaGenTestSuite.java13
-rw-r--r--moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/Employee.java46
-rw-r--r--moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.properties23
-rw-r--r--moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.xml8
-rw-r--r--moxy/org.eclipse.persistence.moxy/META-INF/MANIFEST.MF17
-rw-r--r--moxy/org.eclipse.persistence.moxy/antbuild.properties40
-rw-r--r--moxy/org.eclipse.persistence.moxy/antbuild.xml47
-rw-r--r--moxy/org.eclipse.persistence.moxy/resource/META-INF/services/com.sun.tools.xjc.Plugin1
-rw-r--r--moxy/org.eclipse.persistence.moxy/resource/org/eclipse/persistence/jaxb/beanval.xsd40
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/BeanValidationMode.java40
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBBeanValidator.java268
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContext.java303
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextFactory.java180
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextProperties.java45
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBMarshaller.java479
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBUnmarshaller.java810
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/MarshallerProperties.java47
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/UnmarshallerProperties.java33
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/AnnotationsProcessor.java4566
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/CompilerHelper.java14
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/ElementDeclaration.java14
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/EnumTypeInfo.java14
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Generator.java250
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/MappingsGenerator.java94
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Property.java101
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/SchemaGenerator.java2265
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/TypeInfo.java38
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/XMLProcessor.java160
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/DecimalMaxFacet.java45
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/DecimalMinFacet.java45
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/DigitsFacet.java45
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/Facet.java27
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/FacetVisitor.java87
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/MaxFacet.java38
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/MinFacet.java38
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/PatternFacet.java46
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/PatternListFacet.java44
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/facets/SizeFacet.java45
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/javamodel/Helper.java56
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/javamodel/reflection/JavaClassImpl.java109
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/javamodel/reflection/JavaModelInputImpl.java26
-rw-r--r--moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/plugins/BeanValidationPlugin.java974
-rw-r--r--plugins/classmate-1.0.0.jarbin0 -> 60282 bytes
-rw-r--r--plugins/com.sun.tools.xjc.source_2.2.0.zipbin1625751 -> 0 bytes
-rw-r--r--plugins/com.sun.tools.xjc_2.2.0.jarbin3101294 -> 0 bytes
-rw-r--r--plugins/com.sun.xml.bind.source_2.2.0.v201004141950.jarbin1017805 -> 0 bytes
-rw-r--r--plugins/com.sun.xml.bind_2.2.0.v201004141950.jarbin890453 -> 0 bytes
-rw-r--r--plugins/com.sun.xml.bind_2.2.11.v201406210428.jarbin0 -> 1040064 bytes
-rw-r--r--plugins/hibernate-validator-5.1.0.Final-sources.jarbin0 -> 564214 bytes
-rw-r--r--plugins/hibernate-validator-5.1.0.Final.jarbin0 -> 622634 bytes
-rw-r--r--plugins/javax.el-2.2.2.jarbin0 -> 117471 bytes
-rw-r--r--plugins/javax.el-api-2.2.jarbin0 -> 33936 bytes
-rw-r--r--plugins/javax.xml.bind.source_2.2.0.v201005080402.jarbin177500 -> 0 bytes
-rw-r--r--plugins/jaxb-core_2.2.11.v201406210428.jarbin0 -> 250579 bytes
-rw-r--r--plugins/jaxb-xjc_2.2.11.v201406210428.jarbin0 -> 2032141 bytes
-rw-r--r--plugins/jboss-logging-3.1.4.GA.jarbin0 -> 57193 bytes
-rw-r--r--plugins/tmpfix.osgi.manifest.core/MANIFEST.MF85
-rw-r--r--plugins/tmpfix.osgi.manifest.xjc/MANIFEST.MF311
-rw-r--r--utils/eclipselink.utils.jaxb/antbuild.properties4
-rw-r--r--utils/eclipselink.utils.jaxb/antbuild.xml4
105 files changed, 9681 insertions, 5005 deletions
diff --git a/.gitignore b/.gitignore
index 364c550..ab5c11c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,3 +24,7 @@ foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/Version.java
/jpa/eclipselink.jpa.test/jpa-performance.jar
/jpa/eclipselink.jpa.test/jpa-performance2.jar
/foundation/targets/target.oracle/oracle.libs/*.jar
+*.iml
+.idea*
+out/
+eclipselink_extracted/*
diff --git a/antbuild.properties b/antbuild.properties
index 71091cc..5c5b548 100644
--- a/antbuild.properties
+++ b/antbuild.properties
@@ -160,11 +160,11 @@ persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
unsigned.persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
-jaxb-api.src.jar=javax.xml.bind.source_2.2.0.v201005080402.jar
-jaxb-xjc.jar=com.sun.tools.xjc_2.2.0.jar
-jaxb-impl.jar=com.sun.xml.bind_2.2.0.v201004141950.jar
+jaxb-xjc.jar=jaxb-xjc_2.2.11.v201406210428.jar
+jaxb-impl.jar=com.sun.xml.bind_2.2.11.v201406210428.jar
stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
activation.jar=javax.activation_1.1.0.v201108011116.jar
+javax.validation.jar=javax.validation_1.1.0.v201304101302.jar
mail.jar=javax.mail_1.4.0.v201005080615.jar
commonj.sdo.jar=commonj.sdo_2.1.1.v201112051852.jar
commonj.sdo.src.zip=commonj.sdo.source_2.1.1.v201112051852.jar
diff --git a/antbuild.xml b/antbuild.xml
index e93bb58..bc13b41 100644
--- a/antbuild.xml
+++ b/antbuild.xml
@@ -340,7 +340,7 @@
<jvmarg value="-DforceContextQualifier=${version.qualifier}"/>
<jvmarg value="-Dlocal.compdeps=${local.compdeps}"/>
<jvmarg value="-Declipselink.full=true"/>
- <!-- arg value="-X"/ -->
+ <!--<arg value="-X"/>-->
<arg value="verify"/>
<classpath>
<fileset dir="${M2_HOME}/boot">
diff --git a/buildsystem/compdeps/antbuild.xml b/buildsystem/compdeps/antbuild.xml
index 16719c5..83c4248 100644
--- a/buildsystem/compdeps/antbuild.xml
+++ b/buildsystem/compdeps/antbuild.xml
@@ -131,7 +131,11 @@
<!-- Feature Dependency variables -->
<!-- Defaults, set var in ${user.home}/build.properties if different version required -->
- <property name="sun.xml.bind.prefix" value="com.sun.xml.bind"/>
+ <property name="javax.xml.bind.prefix" value="javax.xml.bind"/>
+ <property name="javax.xml.bind.criteria" value="[0.0.1,5.0.0)"/>
+ <property name="sun.tools.xjc.prefix" value="jaxb-xjc"/>
+ <property name="sun.tools.xjc.criteria" value="[0.0.1,5.0.0)"/>
+ <property name="sun.xml.bind.prefix" value="jaxb-core"/>
<property name="sun.xml.bind.criteria" value="[0.0.1,5.0.0)"/>
<property name="jersey.prefix" value="com.sun.jersey"/>
<property name="jersey.criteria" value="[1.8.0,5.0.0)"/>
@@ -178,9 +182,40 @@
<target name="resolve-feature-dependencies" if="eclipse.install.exist" depends="init">
<echo message="Searching ${compdeps.2.common.plugins.dir}..."/>
- <selectbundle basename="${sun.xml.bind.prefix}" directory="${compdeps.2.common.plugins.dir}"
- criterion="${sun.xml.bind.criteria}" property="sun.xml.bind.version" versiononly="true"
+ <selectbundle basename="${javax.xml.bind.prefix}" directory="${compdeps.2.common.plugins.dir}"
+ criterion="${javax.xml.bind.criteria}" property="javax.xml.bind.version" versiononly="true"
/>
+
+ <!--START OF HOTFIX for JAXB-CORE and JAXB-XJC dependencies.
+ When JAXB-RI builds will generate correct OSGi headers, update the
+ dependencies and remove this hotfix.-->
+ <unjar overwrite="true"
+ src="${compdeps.2.common.plugins.dir}/jaxb-core_2.2.11.v201406210428.jar"
+ dest="${compdeps.2.common.plugins.dir}/tmpfix.osgi.core"
+ />
+ <jar update="false"
+ destfile="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux/jaxb-core_2.2.11.v201406210428.jar"
+ basedir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.core"
+ manifest="${compdeps.2.common.plugins.dir}/tmpfix.osgi.manifest.core/MANIFEST.MF"
+ />
+ <selectbundle basename="${sun.xml.bind.prefix}" directory="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux"
+ criterion="${sun.xml.bind.criteria}" property="sun.xml.bind.version" versiononly="true"
+ />
+
+ <unjar overwrite="true"
+ src="${compdeps.2.common.plugins.dir}/jaxb-xjc_2.2.11.v201406210428.jar"
+ dest="${compdeps.2.common.plugins.dir}/tmpfix.osgi.xjc"
+ />
+ <jar update="false"
+ destfile="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux/jaxb-xjc_2.2.11.v201406210428.jar"
+ basedir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.xjc"
+ manifest="${compdeps.2.common.plugins.dir}/tmpfix.osgi.manifest.xjc/MANIFEST.MF"
+ />
+ <selectbundle basename="${sun.tools.xjc.prefix}" directory="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux"
+ criterion="${sun.tools.xjc.criteria}" property="sun.tools.xjc.version" versiononly="true"
+ />
+ <!--END OF HOTFIX.-->
+
<selectbundle basename="${jersey.prefix}" directory="${compdeps.2.common.plugins.dir}"
criterion="${jersey.criteria}" property="jersey.version" versiononly="true"
/>
@@ -207,9 +242,13 @@
/>
<selectbundle basename="${validation.prefix}" directory="${compdeps.2.common.plugins.dir}"
criterion="${validation.criteria}" property="validation.version" versiononly="true"
- />
+ />
+ <say message=" javax.xml.bind.version = '${javax.xml.bind.version}'" if="javax.xml.bind.version"/>
+ <say message=" '{$javax.xml.bind.prefix}_{$javax.xml.bind.criteria}' not found! Generated features will be invalid." unless="javax.xml.bind.version"/>
+ <say message=" sun.tools.xjc.version = '${sun.tools.xjc.version}'" if="sun.tools.xjc.version"/>
+ <say message=" '${sun.tools.xjc.prefix}_${sun.tools.xjc.criteria}.jar' not found! Generated features will be invalid." unless="sun.tools.xjc.version"/>
<say message=" sun.xml.bind.version = '${sun.xml.bind.version}'" if="sun.xml.bind.version"/>
- <say message=" '${sun.xml.bind.prefix}_${sun.xml.bind.criteria}.jar' not found! Generated features will be invalid." unless="sun.xml.bind.version"/>
+ <say message=" '${sun.xml.bind.prefix}_${sun.xml.bind.criteria}.jar' not found! Generated features will be invalid." unless="sun.xml.bind.version"/>
<say message=" jersey.version = '${jersey.version}'" if="jersey.version"/>
<say message=" '${jersey.prefix}_${jersey.criteria}.jar' not found! Generated features will be invalid." unless="jersey.version"/>
<say message=" ejb.version = '${ejb.version}'" if="ejb.version"/>
@@ -282,7 +321,9 @@
<filter token="VERSION" value="${compdeps.version}"/>
<filter token="QUALIFIER" value="${compdeps.qualifier}"/>
<!-- Filters for dependencies in feature.xml files -->
- <filter token="SUN_XML_BIND_VERSION" value="${sun.xml.bind.version}"/>
+ <filter token="XJC_VERSION" value="${sun.tools.xjc.version}"/>
+ <filter token="JAXB_CORE_VERSION" value="${sun.xml.bind.version}"/>
+ <filter token="JAVAX_XML_BIND_VERSION" value="${javax.xml.bind.version}"/>
<filter token="JERSEY_VERSION" value="${jersey.version}"/>
<filter token="EJB_VERSION" value="${ejb.version}"/>
<filter token="JMS_VERSION" value="${jms.version}"/>
@@ -321,9 +362,7 @@
<copy todir="${p2.bundle.dir}">
<fileset
dir="${compdeps.2.common.plugins.dir}"
- includes="${sun.xml.bind.prefix}_${sun.xml.bind.version}.jar,
- ${sun.xml.bind.prefix}.source_${sun.xml.bind.version}.jar,
- ${jersey.prefix}_${jersey.version}.jar,
+ includes="${jersey.prefix}_${jersey.version}.jar,
${ejb.prefix}_${ejb.version}.jar,
${jms.prefix}_${jms.version}.jar,
${resource.prefix}_${resource.version}.jar,
@@ -334,7 +373,12 @@
${asm.prefix}_${asm.version}.jar,
${asm.prefix}.source_${asm.version}.jar,
${validation.prefix}_${validation.version}.jar"
- />
+ />
+ <fileset
+ dir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux/"
+ includes="${sun.tools.xjc.prefix}_${sun.tools.xjc.version}.jar,
+ ${sun.xml.bind.prefix}_${sun.xml.bind.version}.jar"
+ />
<fileset
dir="${compdeps.2.jpa.plugins.dir}"
includes="${persistence.prefix}_${persistence.version}.jar,
@@ -351,6 +395,15 @@
${wsdl.prefix}_${wsdl.version}.jar"
/>
</copy>
+ <!--START OF HOTFIX
+ We don't want to have the new jar files anywhere in EclipseLink
+ because of licence issues.-->
+ <delete includeemptydirs="true">
+ <fileset dir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.aux" includes="**/*"/>
+ <fileset dir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.xjc" includes="**/*"/>
+ <fileset dir="${compdeps.2.common.plugins.dir}/tmpfix.osgi.core" includes="**/*"/>
+ </delete>
+ <!--END OF HOTFIX-->
</target>
<target name="configure-tooling" if="eclipse.install.exist" depends="init">
diff --git a/buildsystem/compdeps/org.eclipse.persistence.compdeps/feature.xml b/buildsystem/compdeps/org.eclipse.persistence.compdeps/feature.xml
index 443851e..79eb937 100644
--- a/buildsystem/compdeps/org.eclipse.persistence.compdeps/feature.xml
+++ b/buildsystem/compdeps/org.eclipse.persistence.compdeps/feature.xml
@@ -17,12 +17,19 @@
%license
</license>
- <plugin
- id="com.sun.xml.bind"
- download-size="0"
- install-size="0"
- version="@SUN_XML_BIND_VERSION@"
- unpack="false"/>
+ <plugin
+ id="com.sun.xml.bind"
+ download-size="0"
+ install-size="0"
+ version="@JAXB_CORE_VERSION@"
+ unpack="false"/>
+
+ <plugin
+ id="com.sun.tools.xjc"
+ download-size="0"
+ install-size="0"
+ version="@XJC_VERSION@"
+ unpack="false"/>
<plugin
id="com.sun.jersey"
@@ -32,13 +39,6 @@
unpack="false"/>
<plugin
- id="com.sun.xml.bind.source"
- download-size="0"
- install-size="0"
- version="@SUN_XML_BIND_VERSION@"
- unpack="false"/>
-
- <plugin
id="commonj.sdo"
download-size="0"
install-size="0"
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/BeanValidationException.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/BeanValidationException.java
new file mode 100644
index 0000000..708ca69
--- /dev/null
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/BeanValidationException.java
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.exceptions;
+
+import org.eclipse.persistence.exceptions.i18n.ExceptionMessageGenerator;
+
+/**
+ * BeanValidationException should be used to represent any exception that happens during Bean Validation in MOXy.
+ *
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+public final class BeanValidationException extends EclipseLinkException {
+
+ /* 7500-7519 reserved for runtime. */
+ public static final int PROVIDER_NOT_FOUND = 7500;
+ public static final int ILLEGAL_VALIDATION_MODE = 7501;
+
+ public static final int CONSTRAINT_VIOLATION = 7510;
+
+ /* 7520-7530 reserved for Schemagen. */
+ public static final int NOT_NULL_AND_NILLABLE = 7525;
+
+
+ /**
+ * INTERNAL:
+ * EclipseLink exceptions should only be thrown by EclipseLink.
+ */
+ public BeanValidationException(String msg){
+ super(msg);
+ }
+
+ /**
+ * INTERNAL:
+ * EclipseLink exceptions should only be thrown by EclipseLink.
+ */
+ public BeanValidationException(String msg, Throwable internalException){
+ super(msg, internalException);
+ }
+
+
+ /* Runtime. */
+ public final static BeanValidationException constraintViolation(Object[] args, Throwable internalException){
+ BeanValidationException bve = new BeanValidationException(ExceptionMessageGenerator.buildMessage(BeanValidationException.class, CONSTRAINT_VIOLATION, args), internalException);
+ bve.setErrorCode(CONSTRAINT_VIOLATION);
+ return bve;
+ }
+
+ public final static BeanValidationException providerNotFound(String prefix, Throwable internalException){
+ BeanValidationException bve = new BeanValidationException(ExceptionMessageGenerator.buildMessage(BeanValidationException.class, PROVIDER_NOT_FOUND, new Object[]{prefix}), internalException);
+ bve.setErrorCode(PROVIDER_NOT_FOUND);
+ return bve;
+ }
+
+
+ public final static BeanValidationException illegalValidationMode(String prefix, String modeName){
+ BeanValidationException bve = new BeanValidationException(ExceptionMessageGenerator.buildMessage(BeanValidationException.class, ILLEGAL_VALIDATION_MODE, new Object[]{prefix, modeName}));
+ bve.setErrorCode(ILLEGAL_VALIDATION_MODE);
+ return bve;
+ }
+
+ /* SchemaGen. */
+ public final static BeanValidationException notNullAndNillable(String propertyName) {
+ BeanValidationException bve = new BeanValidationException(ExceptionMessageGenerator.buildMessage(BeanValidationException.class, NOT_NULL_AND_NILLABLE, new Object[]{propertyName}));
+ bve.setErrorCode(NOT_NULL_AND_NILLABLE);
+ return bve;
+ }
+}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/ValidationException.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/ValidationException.java
index 0838e74..9286a8b 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/ValidationException.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/ValidationException.java
@@ -458,7 +458,9 @@ public class ValidationException extends EclipseLinkException {
public static final int INVALID_MAPPING_FOR_MAP_KEY_CONVERT = 7354;
public static final int INVALID_MAPPING_FOR_CONVERT_WITH_ATTRIBUTE_NAME = 7355;
public static final int MULTIPLE_OUT_PARAMS_NOT_SUPPORTED = 7356;
-
+
+ /* Code values in range <7500;7599> reserved for {@link org.eclipse.persistence.exceptions.BeanValidationException}. */
+
/**
* INTERNAL:
* EclipseLink exceptions should only be thrown by EclipseLink.
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/BeanValidationExceptionResource.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/BeanValidationExceptionResource.java
new file mode 100644
index 0000000..d351691
--- /dev/null
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/BeanValidationExceptionResource.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.exceptions.i18n;
+
+import java.util.ListResourceBundle;
+
+/**
+ * INTERNAL:
+ * English ResourceBundle for BeanValidationException messages.
+ *
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+public final class BeanValidationExceptionResource extends ListResourceBundle {
+
+ static final Object[][] contents = {
+
+ { "7500", "Bean validation mode on {0}marshaller is set to ON, but no Bean validation provider was found." },
+ { "7501", "Bean validation mode on {0}marshaller is set to illegal value, \"{1}\"." },
+
+ { "7510", "Constraints violated on {0}marshalled bean:\n{1}{2}" },
+
+ { "7525", "Cannot parse property {0}, because it is both annotated with @NotNull and has attribute \"xs:nillable=true\"." }
+
+ };
+
+ /**
+ * Return the lookup table.
+ */
+ protected Object[][] getContents() {
+ return contents;
+ }
+
+}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java
index e148e41..1bf6e96 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XMLMarshaller.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XPathObjectBuilder.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XPathObjectBuilder.java
index a1df7a6..e674f81 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XPathObjectBuilder.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/XPathObjectBuilder.java
@@ -559,8 +559,8 @@ public class XPathObjectBuilder extends CoreObjectBuilder<CoreAbstractRecord, Co
List<XPathNode> attributeChildren = rootXPathNode.getAttributeChildren();
if (null != attributeChildren) {
ObjectMarshalContext objectMarshalContext = ObjectMarshalContext.getInstance();
- for (int x = 0, attributeChildrenSize=attributeChildren.size(); x < attributeChildrenSize; x++) {
- hasValue = attributeChildren.get(x).marshal(marshalRecord, object, session, namespaceResolver, null, objectMarshalContext, null) || hasValue;
+ for (XPathNode anAttributeChildren : attributeChildren) {
+ hasValue = anAttributeChildren.marshal(marshalRecord, object, session, namespaceResolver, null, objectMarshalContext, null) || hasValue;
}
}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/SchemaModelProject.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/SchemaModelProject.java
index c66717f..36a57d8 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/SchemaModelProject.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/SchemaModelProject.java
@@ -217,20 +217,20 @@ public class SchemaModelProject extends Project {
allMapping.setAttributeName("all");
allMapping.setSetMethodName("setAll");
allMapping.setGetMethodName("getAll");
- allMapping.setXPath(Constants.SCHEMA_PREFIX + ":" + "all");
- descriptor.addMapping(allMapping);
-
- XMLCompositeObjectMapping complextContentMapping = new XMLCompositeObjectMapping();
-
- complextContentMapping.setReferenceClass(ComplexContent.class);
- complextContentMapping.setAttributeName("complexContent");
- complextContentMapping.setGetMethodName("getComplexContent");
- complextContentMapping.setSetMethodName("setComplexContent");
- complextContentMapping.setXPath(Constants.SCHEMA_PREFIX + ":complexContent");
- descriptor.addMapping(complextContentMapping);
-
- XMLCompositeObjectMapping simpleContentMapping = new XMLCompositeObjectMapping();
- simpleContentMapping.setReferenceClass(SimpleContent.class);
+ allMapping.setXPath(Constants.SCHEMA_PREFIX + ":" + "all");
+ descriptor.addMapping(allMapping);
+
+ XMLCompositeObjectMapping complexContentMapping = new XMLCompositeObjectMapping();
+
+ complexContentMapping.setReferenceClass(ComplexContent.class);
+ complexContentMapping.setAttributeName("complexContent");
+ complexContentMapping.setGetMethodName("getComplexContent");
+ complexContentMapping.setSetMethodName("setComplexContent");
+ complexContentMapping.setXPath(Constants.SCHEMA_PREFIX + ":complexContent");
+ descriptor.addMapping(complexContentMapping);
+
+ XMLCompositeObjectMapping simpleContentMapping = new XMLCompositeObjectMapping();
+ simpleContentMapping.setReferenceClass(SimpleContent.class);
simpleContentMapping.setAttributeName("simpleContent");
simpleContentMapping.setGetMethodName("getSimpleContent");
simpleContentMapping.setSetMethodName("setSimpleContent");
@@ -470,12 +470,60 @@ public class SchemaModelProject extends Project {
maxExclusiveMapping.setAttributeName("maxExclusive");
maxExclusiveMapping.setSetMethodName("setMaxExclusive");
maxExclusiveMapping.setGetMethodName("getMaxExclusive");
- maxExclusiveMapping.setXPath(Constants.SCHEMA_PREFIX + ":maxExclusive/@value");
- descriptor.addMapping(maxExclusiveMapping);
-
- XMLCompositeDirectCollectionMapping enumerationFacetsMapping = new XMLCompositeDirectCollectionMapping();
- enumerationFacetsMapping.setAttributeName("enumerationFacets");
- enumerationFacetsMapping.useCollectionClass(java.util.ArrayList.class);
+ maxExclusiveMapping.setXPath(Constants.SCHEMA_PREFIX + ":maxExclusive/@value");
+ descriptor.addMapping(maxExclusiveMapping);
+
+ XMLDirectMapping totalDigitsMapping = new XMLDirectMapping();
+ totalDigitsMapping.setAttributeName("totalDigits");
+ totalDigitsMapping.setSetMethodName("setTotalDigits");
+ totalDigitsMapping.setGetMethodName("getTotalDigits");
+ totalDigitsMapping.setXPath(Constants.SCHEMA_PREFIX + ":totalDigits/@value");
+ descriptor.addMapping(totalDigitsMapping);
+
+ XMLDirectMapping fractionDigitsMapping = new XMLDirectMapping();
+ fractionDigitsMapping.setAttributeName("fractionDigits");
+ fractionDigitsMapping.setSetMethodName("setFractionDigits");
+ fractionDigitsMapping.setGetMethodName("getFractionDigits");
+ fractionDigitsMapping.setXPath(Constants.SCHEMA_PREFIX + ":fractionDigits/@value");
+ descriptor.addMapping(fractionDigitsMapping);
+
+ XMLDirectMapping patternMapping = new XMLDirectMapping();
+ patternMapping.setAttributeName("pattern");
+ patternMapping.setSetMethodName("setPattern");
+ patternMapping.setGetMethodName("getPattern");
+ patternMapping.setXPath(Constants.SCHEMA_PREFIX + ":pattern/@value");
+ descriptor.addMapping(patternMapping);
+
+ XMLCompositeDirectCollectionMapping patternListMapping = new XMLCompositeDirectCollectionMapping();
+ patternListMapping.setAttributeName("patterns");
+ patternListMapping.useCollectionClass(java.util.ArrayList.class);
+ patternListMapping.setXPath(Constants.SCHEMA_PREFIX + ":pattern/@value");
+ descriptor.addMapping(patternListMapping);
+
+ XMLDirectMapping lengthMapping = new XMLDirectMapping();
+ lengthMapping.setAttributeName("length");
+ lengthMapping.setSetMethodName("setLength");
+ lengthMapping.setGetMethodName("getLength");
+ lengthMapping.setXPath(Constants.SCHEMA_PREFIX + ":length/@value");
+ descriptor.addMapping(lengthMapping);
+
+ XMLDirectMapping minLengthMapping = new XMLDirectMapping();
+ minLengthMapping.setAttributeName("minLength");
+ minLengthMapping.setSetMethodName("setMinLength");
+ minLengthMapping.setGetMethodName("getMinLength");
+ minLengthMapping.setXPath(Constants.SCHEMA_PREFIX + ":minLength/@value");
+ descriptor.addMapping(minLengthMapping);
+
+ XMLDirectMapping maxLengthMapping = new XMLDirectMapping();
+ maxLengthMapping.setAttributeName("maxLength");
+ maxLengthMapping.setSetMethodName("setMaxLength");
+ maxLengthMapping.setGetMethodName("getMaxLength");
+ maxLengthMapping.setXPath(Constants.SCHEMA_PREFIX + ":maxLength/@value");
+ descriptor.addMapping(maxLengthMapping);
+
+ XMLCompositeDirectCollectionMapping enumerationFacetsMapping = new XMLCompositeDirectCollectionMapping();
+ enumerationFacetsMapping.setAttributeName("enumerationFacets");
+ enumerationFacetsMapping.useCollectionClass(java.util.ArrayList.class);
enumerationFacetsMapping.setXPath(Constants.SCHEMA_PREFIX + ":enumeration/@value");
descriptor.addMapping(enumerationFacetsMapping);
return descriptor;
@@ -616,12 +664,14 @@ public class SchemaModelProject extends Project {
XMLAnyAttributeMapping attributesMapMapping = new XMLAnyAttributeMapping();
attributesMapMapping.setAttributeName("attributesMap");
attributesMapMapping.setGetMethodName("getAttributesMap");
- attributesMapMapping.setSetMethodName("setAttributesMap");
- descriptor.addMapping(attributesMapMapping);
-
- return descriptor;
- }
-
+ attributesMapMapping.setSetMethodName("setAttributesMap");
+ descriptor.addMapping(attributesMapMapping);
+
+
+
+ return descriptor;
+ }
+
private XMLDescriptor buildChoiceDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(Choice.class);
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/ComplexType.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/ComplexType.java
index 5ac41ac..c46a118 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/ComplexType.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/ComplexType.java
@@ -13,13 +13,16 @@
package org.eclipse.persistence.internal.oxm.schema.model;
import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-public class ComplexType implements TypeDefParticleOwner {
- private String name;
- private boolean mixed;
- private boolean abstractValue;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A Value Object class representing XML Schema's complexType.
+ */
+public final class ComplexType implements TypeDefParticleOwner {
+ private String name;
+ private boolean mixed;
+ private boolean abstractValue;
private AnyAttribute anyAttribute;
private TypeDefParticle typeDefParticle;
private Choice choice;
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Element.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Element.java
index 6323bf1..7dd9d7f 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Element.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Element.java
@@ -1,27 +1,44 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
- ******************************************************************************/
-package org.eclipse.persistence.internal.oxm.schema.model;
-
-public class Element extends SimpleComponent {
- private ComplexType complexType;
- private String minOccurs;
- private String maxOccurs;
- private boolean nillable;
- private boolean abstractValue;
- private String substitutionGroup;
-
- public Element() {
- }
+ ******************************************************************************/
+package org.eclipse.persistence.internal.oxm.schema.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A Value Object class representing XML Schema's Element.
+ */
+public final class Element extends SimpleComponent {
+ private ComplexType complexType;
+ private String minOccurs;
+ private String maxOccurs;
+ private boolean nillable;
+ private boolean abstractValue;
+ private String substitutionGroup;
+ private String maxInclusive;
+ private String minInclusive;
+ private String maxExclusive;
+ private String minExclusive;
+ private int totalDigits;
+ private int fractionDigits;
+ private String pattern;
+ private List<String> patterns = new ArrayList<String>();
+ private int length;
+ private int minLength;
+ private int maxLength;
+
+ public Element() {
+ }
public void setComplexType(ComplexType complexType) {
if (complexType != null) {
@@ -63,15 +80,102 @@ public class Element extends SimpleComponent {
}
public String getMaxOccurs() {
- return maxOccurs;
- }
-
-
- public String getSubstitutionGroup() {
- return substitutionGroup;
- }
+ return maxOccurs;
+ }
+
+ public String getSubstitutionGroup() {
+ return substitutionGroup;
+ }
- public void setSubstitutionGroup(String group) {
- this.substitutionGroup = group;
- }
-}
+ public void setSubstitutionGroup(String group) {
+ this.substitutionGroup = group;
+ }
+
+ public String getMaxInclusive() {
+ return maxInclusive;
+ }
+
+ public void setMaxInclusive(String maxInclusive) {
+ this.maxInclusive = maxInclusive;
+ }
+
+ public String getMinInclusive() {
+ return minInclusive;
+ }
+
+ public void setMinInclusive(String minInclusive) {
+ this.minInclusive = minInclusive;
+ }
+
+ public String getMaxExclusive() {
+ return maxExclusive;
+ }
+
+ public void setMaxExclusive(String maxExclusive) {
+ this.maxExclusive = maxExclusive;
+ }
+
+ public String getMinExclusive() {
+ return minExclusive;
+ }
+
+ public void setMinExclusive(String minExclusive) {
+ this.minExclusive = minExclusive;
+ }
+
+ public int getTotalDigits() {
+ return totalDigits;
+ }
+
+ public void setTotalDigits(int totalDigits) {
+ this.totalDigits = totalDigits;
+ }
+
+ public int getFractionDigits() {
+ return fractionDigits;
+ }
+
+ public void setFractionDigits(int fractionDigits) {
+ this.fractionDigits = fractionDigits;
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String pattern) {
+ this.pattern = pattern;
+ }
+
+ public List<String> getPatterns() {
+ return patterns;
+ }
+
+ public void addPattern(String pattern) {
+ this.patterns.add(pattern);
+ }
+
+ public int getLength() {
+ return length;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+
+ public int getMinLength() {
+ return minLength;
+ }
+
+ public void setMinLength(int minLength) {
+ this.minLength = minLength;
+ }
+
+ public int getMaxLength() {
+ return maxLength;
+ }
+
+ public void setMaxLength(int maxLength) {
+ this.maxLength = maxLength;
+ }
+}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Restriction.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Restriction.java
index 39122b7..8918c00 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Restriction.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/Restriction.java
@@ -1,20 +1,23 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
- ******************************************************************************/
-package org.eclipse.persistence.internal.oxm.schema.model;
-
-public class Restriction implements SimpleDerivation {
- private String baseType;//QName lateR??
-
+ ******************************************************************************/
+package org.eclipse.persistence.internal.oxm.schema.model;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Restriction implements SimpleDerivation {
+ private String baseType;//QName lateR??
+
//can have a typeDefParticle (seq choice all if in complexContent) OR simplerestmodel (facets
private TypeDefParticle typeDefParticle;
private Choice choice;
@@ -24,20 +27,31 @@ public class Restriction implements SimpleDerivation {
private java.util.ArrayList enumerationFacets;
private AnyAttribute anyAttribute;
private String minInclusive;
- private String maxInclusive;
- private String minExclusive;
- private String maxExclusive;
-
- //private List facets
- private java.util.List attributes;
+ private String maxInclusive;
+ private String minExclusive;
+ private String maxExclusive;
+ private String totalDigits;
+ private String fractionDigits;
+ private String pattern;
+ private java.util.List<String> patterns = new ArrayList<String>();
+ private String length;
+ private String minLength;
+ private String maxLength;
+
+ //private List facets
+ private java.util.List attributes;
private Restrictable owner;
- public Restriction() {
- }
-
- public void setMinInclusive(String minInclusive) {
- this.minInclusive = minInclusive;
- }
+ public Restriction() {
+ }
+
+ public Restriction(String baseType) {
+ this.baseType = baseType;
+ }
+
+ public void setMinInclusive(String minInclusive) {
+ this.minInclusive = minInclusive;
+ }
public String getMinInclusive() {
return minInclusive;
@@ -162,7 +176,116 @@ public class Restriction implements SimpleDerivation {
return anyAttribute;
}
- public void setAnyAttribute(AnyAttribute any) {
- anyAttribute = any;
- }
-}
+ public void setAnyAttribute(AnyAttribute any) {
+ anyAttribute = any;
+ }
+
+ public String getTotalDigits() {
+ return totalDigits;
+ }
+
+ public void setTotalDigits(String totalDigits) {
+ this.totalDigits = totalDigits;
+ }
+
+ public void setTotalDigits(int totalDigits) {
+ this.totalDigits = String.valueOf(totalDigits);
+ }
+
+ public String getFractionDigits() {
+ return fractionDigits;
+ }
+
+ public void setFractionDigits(String fractionDigits) {
+ this.fractionDigits = fractionDigits;
+ }
+
+ public void setFractionDigits(int fractionDigits) {
+ this.fractionDigits = String.valueOf(fractionDigits);
+ }
+
+ public String getPattern() {
+ return pattern;
+ }
+
+ public void setPattern(String pattern) {
+ this.pattern = pattern;
+ }
+
+ public List<String> getPatterns() {
+ return patterns;
+ }
+
+ public void setPatterns(List<String> patterns) {
+ this.patterns = patterns;
+ }
+
+ public void addPattern(String regexp) {
+ this.patterns.add(regexp);
+ }
+
+ public String getLength() {
+ return length;
+ }
+
+ public void setLength(String length) {
+ this.length = length;
+ }
+
+ public void setLength(int length) {
+ this.length = String.valueOf(length);
+ }
+
+ public String getMinLength() {
+ return minLength;
+ }
+
+ public void setMinLength(String minLength) {
+ this.minLength = minLength;
+ }
+
+ public void setMinLength(int minLength) {
+ this.minLength = String.valueOf(minLength);
+ }
+
+ public String getMaxLength() {
+ return maxLength;
+ }
+
+ public void setMaxLength(String maxLength) {
+ this.maxLength = maxLength;
+ }
+
+ public void setMaxLength(int maxLength) {
+ this.maxLength = String.valueOf(maxLength);
+ }
+
+ /**
+ * Overwrites attributes of this restriction with attributes of the argument,
+ * if they are not null.
+ *
+ * @param restriction
+ */
+ public void mergeWith(Restriction restriction) {
+ if (restriction.getAll() != null) this.setAll(restriction.getAll());
+ if (restriction.getAnyAttribute() != null) this.setAnyAttribute(restriction.getAnyAttribute());
+ // if (restriction.getBaseType()) // this one doesn't make sense to do
+ // if (restriction.getSimpleType()) // this one doesn't make sense to do
+ if (restriction.getTypeDefParticle() != null) this.setTypeDefParticle(restriction.getTypeDefParticle()); // not sure if this one makes sense
+ if (restriction.getSequence() != null) this.setSequence(restriction.getSequence());
+ if (restriction.getChoice() != null) this.setChoice(restriction.getChoice());
+ if (restriction.getEnumerationFacets() != null) this.setEnumerationFacets(restriction.getEnumerationFacets());
+
+ if (restriction.getPatterns() != null) this.setPatterns(restriction.getPatterns());
+ if (restriction.getPattern() != null) this.setPattern(restriction.getPattern());
+ if (restriction.getMaxInclusive() != null) this.setMaxInclusive(restriction.getMaxInclusive());
+ if (restriction.getMinInclusive() != null) this.setMinInclusive(restriction.getMinInclusive());
+ if (restriction.getMaxExclusive() != null) this.setMaxExclusive(restriction.getMaxExclusive());
+ if (restriction.getMinExclusive() != null) this.setMinExclusive(restriction.getMinExclusive());
+ if (restriction.getTotalDigits() != null) this.setFractionDigits(restriction.getTotalDigits());
+ if (restriction.getFractionDigits() != null) this.setFractionDigits(restriction.getFractionDigits());
+ if (restriction.getLength() != null) this.setLength(restriction.getLength());
+ if (restriction.getMinLength() != null) this.setMinLength(restriction.getMinLength());
+ if (restriction.getMaxLength() != null) this.setMaxLength(restriction.getMaxLength());
+ }
+}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/SimpleType.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/SimpleType.java
index fa840dc..4200733 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/SimpleType.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/schema/model/SimpleType.java
@@ -33,18 +33,22 @@ public class SimpleType implements Restrictable {
public String getName() {
return name;
- }
-
- public void setRestriction(Restriction restriction) {
- this.restriction = restriction;
- if (restriction != null) {
- restriction.setOwner(this);
- }
-
- //set Owner
- }
-
- public Restriction getRestriction() {
+ }
+
+ public void setRestriction(Restriction restriction) {
+ if (restriction == null)
+ return;
+
+ restriction.setOwner(this);
+ if (this.restriction == null) {
+ this.restriction = restriction;
+ } else {
+ this.restriction.mergeWith(restriction);
+ }
+
+ }
+
+ public Restriction getRestriction() {
return restriction;
}
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java
index aeaf959..1a5b685 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/oxm/XMLMarshaller.java
@@ -1,8 +1,8 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
diff --git a/jpa/eclipselink.jpa.test/antbuild.properties b/jpa/eclipselink.jpa.test/antbuild.properties
index 7cfdfcb..2d34fd6 100644
--- a/jpa/eclipselink.jpa.test/antbuild.properties
+++ b/jpa/eclipselink.jpa.test/antbuild.properties
@@ -41,7 +41,6 @@ transaction.jar=javax.transaction_1.1.0.v201002051055.jar
restfulws.jar=javax.ws.rs_1.1.1.v20101004-1200.jar
jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
commonj.sdo.jar=commonj.sdo_2.1.1.v201112051852.jar
-beanvalidation.jar=javax.validation_1.1.0.v201304101302.jar
persistence21.jar=javax.persistence_2.1.0.v201304241213.jar
persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
@@ -144,10 +143,9 @@ eclipselink.jpa.spring.test=../eclipselink.jpa.spring.test
# BeanValidationJUnitTest Dependency Definitions
----------------------------------------------
-validation.impl.jar=validationImpl-4.1.0.Beta1.jar
-slf4j.api.jar=slf4j-api-1.5.11.jar
-slf4j.jdk.jar=slf4j-jdk14-1.5.11.jar
-validation.api.jar=validation-api-1.0.0.GA.jar
-
-
-
+beanvalidation.jar=javax.validation_1.1.0.v201304101302.jar
+validation.impl.jar=hibernate-validator-5.1.0.Final.jar
+jboss-logging.jar=jboss-logging-3.1.4.GA.jar
+javax.el-api.jar=javax.el-api-2.2.jar
+javax.el.jar=javax.el-2.2.2.jar
+classmate.jar=classmate-1.0.0.jar \ No newline at end of file
diff --git a/jpa/eclipselink.jpa.test/antbuild.xml b/jpa/eclipselink.jpa.test/antbuild.xml
index 7acb7e4..b680e20 100644
--- a/jpa/eclipselink.jpa.test/antbuild.xml
+++ b/jpa/eclipselink.jpa.test/antbuild.xml
@@ -70,20 +70,20 @@
<!-- Allows a user to overide certain user specific properties. -->
<!-- local property overrides -->
<condition property="custom.bld.properties.message" value="Loading user-defined overrides from '${user.home}/build.properties'..."
- else="No user-defined overrides found to load ('${user.home}/build.properties' non-existant).">
+ else="No user-defined overrides found to load ('${user.home}/build.properties' non-existant).">
<available file="${user.home}/build.properties"/>
</condition>
<echo message="${custom.bld.properties.message}"/>
<property file="${user.home}/build.properties"/>
<condition property="custom.tst.properties.message" value="Loading user-defined test overrides from '${user.home}/test.properties'..."
- else="No user-defined test overrides found to load ('${user.home}/test.properties' non-existant).">
+ else="No user-defined test overrides found to load ('${user.home}/test.properties' non-existant).">
<available file="${user.home}/test.properties"/>
</condition>
<echo message="${custom.tst.properties.message}"/>
<property file="${user.home}/test.properties"/>
<!-- Allows overriding defaults where access to user.home isn't allowed -->
<condition property="custom.local.properties.message" value="Loading local overrides from '${basedir}/local.build.properties'..."
- else="No Local overrides found to load. ('${basedir}/local.build.properties' non-existant).">
+ else="No Local overrides found to load. ('${basedir}/local.build.properties' non-existant).">
<available file="${basedir}/local.build.properties"/>
</condition>
<echo message="${custom.local.properties.message}"/>
@@ -394,8 +394,8 @@
<echo message=" '${jpatest.2.coretest.dir}/${coretest.jar}'"/>
<echo message=" '${jpatest.2.coretest.dir}/${coretest.framework.jar}'"/>
<echo message=" '${jpatest.2.jpa.plugins.dir}/${persistence20.jar}'"/>
- <echo message=" '${jpatest.2.base.dir}/${eclipselink.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${beanvalidation.jar}'"/>
+ <echo message=" '${jpatest.2.base.dir}/${eclipselink.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${ejb.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${transaction.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${restfulws.jar}'"/>
@@ -409,8 +409,8 @@
<pathelement path="${jpatest.2.coretest.dir}/${coretest.jar}"/>
<pathelement path="${jpatest.2.coretest.dir}/${coretest.framework.jar}"/>
<pathelement path="${jpatest.2.jpa.plugins.dir}/${persistence20.jar}"/>
- <pathelement path="${jpatest.2.base.dir}/${eclipselink.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${beanvalidation.jar}"/>
+ <pathelement path="${jpatest.2.base.dir}/${eclipselink.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${ejb.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${transaction.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${restfulws.jar}"/>
@@ -432,8 +432,8 @@
<echo message=" '${jpatest.2.coretest.dir}/${coretest.jar}'"/>
<echo message=" '${jpatest.2.coretest.dir}/${coretest.framework.jar}'"/>
<echo message=" '${jpatest.2.jpa.plugins.dir}/${persistence21.jar}'"/>
- <echo message=" '${jpatest.2.base.dir}/${eclipselink.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${beanvalidation.jar}'"/>
+ <echo message=" '${jpatest.2.base.dir}/${eclipselink.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${ejb.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${transaction.jar}'"/>
<echo message=" '${jpatest.2.common.plugins.dir}/${restfulws.jar}'"/>
@@ -446,8 +446,8 @@
<pathelement path="${jpatest.2.coretest.dir}/${coretest.jar}"/>
<pathelement path="${jpatest.2.coretest.dir}/${coretest.framework.jar}"/>
<pathelement path="${jpatest.2.jpa.plugins.dir}/${persistence21.jar}"/>
- <pathelement path="${jpatest.2.base.dir}/${eclipselink.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${beanvalidation.jar}"/>
+ <pathelement path="${jpatest.2.base.dir}/${eclipselink.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${ejb.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${transaction.jar}"/>
<pathelement path="${jpatest.2.common.plugins.dir}/${restfulws.jar}"/>
@@ -3320,12 +3320,12 @@
failonerror="false"
dir="${run.dir}">
<jvmarg value="${jvmarg.performance.baseline.version}"/>
- <jvmarg value="-Declipselink.logging.level=${logging.level}"/>
- <jvmarg value="-Ddb.driver=${db.driver}"/>
- <jvmarg value="-Ddb.url=${db.url}"/>
- <jvmarg value="-Ddb.user=${db.user}"/>
- <jvmarg value="-Ddb.pwd=${db.pwd}"/>
- <jvmarg value="-Ddb.platform=${db.platform}"/>
+ <jvmarg value="-Declipselink.logging.level=${logging.level}"/>
+ <jvmarg value="-Ddb.driver=${db.driver}"/>
+ <jvmarg value="-Ddb.url=${db.url}"/>
+ <jvmarg value="-Ddb.user=${db.user}"/>
+ <jvmarg value="-Ddb.pwd=${db.pwd}"/>
+ <jvmarg value="-Ddb.platform=${db.platform}"/>
<jvmarg value="-Dserver.platform=${server.platform}"/>
<jvmarg value="-Dserver.user=${server.user}"/>
<jvmarg value="-Dserver.password=${server.pwd}"/>
diff --git a/jpa/eclipselink.jpars.test/antbuild.properties b/jpa/eclipselink.jpars.test/antbuild.properties
index b657060..452b950 100644
--- a/jpa/eclipselink.jpars.test/antbuild.properties
+++ b/jpa/eclipselink.jpars.test/antbuild.properties
@@ -37,4 +37,3 @@ asm=org.eclipse.persistence.asm
hermes.version.string=2.0.0.qualifier
antlr=org.eclipse.persistence.antlr
-eclipselink.jar=eclipselink.jar
diff --git a/jpa/org.eclipse.persistence.jpa/antbuild.properties b/jpa/org.eclipse.persistence.jpa/antbuild.properties
index 1d2ecea..3f65686 100644
--- a/jpa/org.eclipse.persistence.jpa/antbuild.properties
+++ b/jpa/org.eclipse.persistence.jpa/antbuild.properties
@@ -16,13 +16,13 @@ javac.deprecation=false
# Do not edit the variables below
# They may, however, be overridden in parent scripts
asm=org.eclipse.persistence.asm
-antlr=org.eclipse.persistence.antlr
-persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
-
-beanvalidation.jar=javax.validation_1.1.0.v201304101302.jar
-stax_api.jar=javax.xml.stream_1.0.1.v200903100845.jar
-activation.jar=javax.xml.stream_1.0.1.v201004272200.jar
-mail.jar=javax.mail_1.4.0.v201005080615.jar
+antlr=org.eclipse.persistence.antlr
+persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
+
+validation.jar=javax.validation_1.1.0.v201304101302.jar
+stax_api.jar=javax.xml.stream_1.0.1.v200903100845.jar
+activation.jar=javax.xml.stream_1.0.1.v201004272200.jar
+mail.jar=javax.mail_1.4.0.v201005080615.jar
resource.jar=javax.resource_1.6.0.v201204270900.jar
ejb.jar=javax.ejb_3.0.0.v200906010428.jar
jms.jar=javax.jms_1.1.0.v200906010428.jar
@@ -31,13 +31,13 @@ transaction.jar=javax.transaction_1.1.0.v201002051055.jar
eclipselink.core=../org.eclipse.persistence.core
eclipselink.core.trunk=../../foundation/org.eclipse.persistence.core
-eclipselink.core.depend=${activation.jar},${resource.jar},${ejb.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar}
-
-eclipselink.jpa=../org.eclipse.persistence.jpa
-eclipselink.jpa.depend=${persistence20.jar}, ${beanvalidation.jar}
-
-persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
-
+eclipselink.core.depend=${activation.jar},${resource.jar},${ejb.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar}
+
+eclipselink.jpa=../org.eclipse.persistence.jpa
+eclipselink.jpa.depend=${persistence20.jar}, ${validation.jar}
+
+persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
+
plugins.dir=plugins
classes.dir=classes
resource.dir=resource
diff --git a/moxy/bin/jaxb-compiler.cmd b/moxy/bin/jaxb-compiler.cmd
index 8cbe435..75f20ed 100755
--- a/moxy/bin/jaxb-compiler.cmd
+++ b/moxy/bin/jaxb-compiler.cmd
@@ -15,12 +15,13 @@ call :fixpath "%~dp0"
set THIS=%_FIXPATH:~1%
set CLASSPATH=%THIS%..\jlib\moxy\javax.xml.stream_1.0.1.v201004272200.jar
set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\javax.xml.bind_2.2.0.v201105210648.jar
-set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\javax.activation_1.1.0.v201108011116.jar
-set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\com.sun.xml.bind_2.2.0.v201004141950.jar
-set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\com.sun.tools.xjc_2.2.0.jar
-set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\eclipselink.jar
-set JAVA_ARGS=%*
-
+set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\javax.activation_1.1.0.v201108011116.jar
+set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\com.sun.xml.bind_2.2.0.v201004141950.jar
+set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\com.sun.tools.xjc_2.2.0.jar
+set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\moxy\javax.validation_1.1.0.v201304101302.jar
+set CLASSPATH=%CLASSPATH%;%THIS%..\jlib\eclipselink.jar
+set JAVA_ARGS=%*
+
%JAVA_HOME%\bin\java.exe %JVM_ARGS% -cp %CLASSPATH% -Djava.endorsed.dirs=..\jlib\moxy org.eclipse.persistence.jaxb.xjc.MOXyXJC %JAVA_ARGS%
@endlocal
diff --git a/moxy/bin/jaxb-compiler.sh b/moxy/bin/jaxb-compiler.sh
index 7f1b200..92a2ed7 100755
--- a/moxy/bin/jaxb-compiler.sh
+++ b/moxy/bin/jaxb-compiler.sh
@@ -13,6 +13,7 @@ CLASSPATH=`dirname $0`/../jlib/moxy/javax.xml.stream_1.0.1.v201004272200.jar:\
`dirname $0`/../jlib/moxy/javax.activation_1.1.0.v201108011116.jar:\
`dirname $0`/../jlib/moxy/com.sun.xml.bind_2.2.0.v201004141950.jar:\
`dirname $0`/../jlib/moxy/com.sun.tools.xjc_2.2.0.jar:\
+`dirname $0`/../jlib/moxy/javax.validation_1.1.0.v201304101302.jar:\
`dirname $0`/../jlib/eclipselink.jar
JAVA_ARGS="$@"
diff --git a/moxy/eclipselink.moxy.test/antbuild.properties b/moxy/eclipselink.moxy.test/antbuild.properties
index a92a817..fbc0fc1 100644
--- a/moxy/eclipselink.moxy.test/antbuild.properties
+++ b/moxy/eclipselink.moxy.test/antbuild.properties
@@ -13,8 +13,17 @@ javac.version=1.6
# Do not edit the variables below
# They may, however, be overridden in parent scripts
jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
-jaxb-xjc.jar=com.sun.tools.xjc_2.2.0.jar
-jaxb-impl.jar=com.sun.xml.bind_2.2.0.v201004141950.jar
+jaxb-xjc.jar=jaxb-xjc_2.2.11.v201406210428.jar
+jaxb-core.jar=jaxb-core_2.2.11.v201406210428.jar
+jaxb-impl.jar=com.sun.xml.bind_2.2.11.v201406210428.jar
+
+javax.validation.jar=javax.validation_1.1.0.v201304101302.jar
+hibernate-validator.jar=hibernate-validator-5.1.0.Final.jar
+# Required by the hibernate-validator.
+jboss-logging.jar=jboss-logging-3.1.4.GA.jar
+javax.el-api.jar=javax.el-api-2.2.jar
+javax.el.jar=javax.el-2.2.2.jar
+classmate.jar=classmate-1.0.0.jar
json.jar=javax.json-1.0.jar
stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
@@ -26,7 +35,7 @@ ejb.jar=javax.ejb_3.0.0.v200906010428.jar
jms.jar=javax.jms_1.1.0.v200906010428.jar
transaction.jar=javax.transaction_1.1.0.v201002051055.jar
-eclipselink.core.depend=${activation.jar},${resource.jar},${ejb.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar}
+eclipselink.core.depend=${activation.jar},${resource.jar},${ejb.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar},${javax.validation.jar}
eclipselink.jar=eclipselink.jar
eclipselink.core=../../foundation/org.eclipse.persistence.core
diff --git a/moxy/eclipselink.moxy.test/antbuild.xml b/moxy/eclipselink.moxy.test/antbuild.xml
index e7233bc..be341c7 100644
--- a/moxy/eclipselink.moxy.test/antbuild.xml
+++ b/moxy/eclipselink.moxy.test/antbuild.xml
@@ -35,7 +35,8 @@
* rbarkhouse - 06 Apr 2011 - Separate JavadocAnnotationExamples from JAXBTestSuite
* dmahar - Jan 2012 - remove update-package-names targets
* bdoughan - Sep 2012 - Added RESTful tests and necessary dependencies
-* mvalovy - Mar 2014 - Added JAXBPerformanceTestSuite
+* mvalovy - Mar-Jul 2014 - Added Bean Validation support, JAXBTestSuite5
+ and JAXBPerformanceTestSuite
#******************************************************************************/-->
<project name="eclipselink.moxy.test" default="test" basedir=".">
@@ -61,31 +62,39 @@
<!-- Temporary until eclipselink.jar property is globally renamed -->
<property name="eclipselink.jar" value="eclipselink.jar"/>
- <!-- Allows a user to overide certain user specific properties. -->
+ <!-- Allows a user to override certain user specific properties. -->
<property file="${user.home}/build.properties"/>
<property file="${moxytest.build.location}/antbuild.properties"/>
<propertyset id="parser.properties">
<propertyref prefix="javax.xml"/>
</propertyset>
- <property name="custom.tasks.lib" value="${moxytest.2.buildsys.dir}/ant_customizations.jar"/>
- <property name="custom.selectbundle.task.class" value="org.eclipse.persistence.buildtools.ant.taskdefs.SelectBundle"/>
- <taskdef name="selectbundle" classname="${custom.selectbundle.task.class}" classpath="${custom.tasks.lib}"/>
+ <property name="custom.tasks.lib" value="${moxytest.2.buildsys.dir}/ant_customizations.jar"/>
+ <property name="custom.selectbundle.task.class" value="org.eclipse.persistence.buildtools.ant.taskdefs.SelectBundle"/>
+ <taskdef name="selectbundle" classname="${custom.selectbundle.task.class}" classpath="${custom.tasks.lib}"/>
- <selectbundle basename="org.eclipse.persistence.nosql" directory="${moxytest.build.location}/${moxytest.2.common.plugins.dir}" separator="_"
- criterion="[2.0.0,9.0.0)" property="oep.nosql.lib" includepath="true"
- />
- <echo message="oep.nosql.lib ='${oep.nosql.lib}'"/>
+ <selectbundle basename="org.eclipse.persistence.nosql" directory="${moxytest.build.location}/${moxytest.2.common.plugins.dir}" separator="_"
+ criterion="[2.0.0,9.0.0)" property="oep.nosql.lib" includepath="true"
+ />
+ <echo message="oep.nosql.lib ='${oep.nosql.lib}'"/>
<property name="eclipselink.lib" value="${moxytest.2.trunk.dir}/${eclipselink.jar}"/>
+ <property name="xjc-beanval.lib" value="${moxytest.2.trunk.dir}/beanval/target/${xjc-beanval.jar}"/>
<property name="jaxb-xjc.lib" value="${moxytest.2.common.plugins.dir}/${jaxb-xjc.jar}"/>
<property name="jaxb-api.lib" value="${moxytest.2.common.plugins.dir}/${jaxb-api.jar}"/>
<property name="jaxb-impl.lib" value="${moxytest.2.common.plugins.dir}/${jaxb-impl.jar}"/>
+ <property name="jaxb-core.lib" value="${moxytest.2.common.plugins.dir}/${jaxb-core.jar}"/>
+ <property name="javax.validation.lib" value="${moxytest.2.common.plugins.dir}/${javax.validation.jar}"/>
+ <property name="hibernate-validator.lib" value="${moxytest.2.common.plugins.dir}/${hibernate-validator.jar}"/>
+ <property name="jboss-logging.lib" value="${moxytest.2.common.plugins.dir}/${jboss-logging.jar}"/>
+ <property name="javax.el-api.lib" value="${moxytest.2.common.plugins.dir}/${javax.el-api.jar}"/>
+ <property name="javax.el.lib" value="${moxytest.2.common.plugins.dir}/${javax.el.jar}"/>
+ <property name="classmate.lib" value="${moxytest.2.common.plugins.dir}/${classmate.jar}"/>
<path id="xml.parser.path">
<fileset
- dir="${xml.parser.jar.dir}"
- includes="${xml.parser.jar}"/>
+ dir="${xml.parser.jar.dir}"
+ includes="${xml.parser.jar}"/>
</path>
<!-- Compile/run paths -->
<path id="jaxb.compile.path">
@@ -106,6 +115,8 @@
<pathelement path="${moxytest.2.core.dir}/${classes.dir}"/>
<pathelement path="${jaxb-xjc.lib}"/>
<pathelement path="${jaxb-impl.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
+ <pathelement path="${javax.validation.lib}"/>
</path>
<path id="jaxb.run.path">
<path refid="xml.parser.path"/>
@@ -120,8 +131,15 @@
<pathelement path="${moxytest.2.core.dir}/${classes.dir}"/>
<pathelement path="${moxytest.2.core.dir}/${resource.dir}"/>
<pathelement path="${moxytest.2.common.plugins.dir}/org.eclipse.persistence.asm"/>
+ <pathelement path="${xjc-beanval.lib}"/>
<pathelement path="${jaxb-xjc.lib}"/>
<pathelement path="${jaxb-impl.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
+ <pathelement path="${hibernate-validator.lib}"/>
+ <pathelement path="${jboss-logging.lib}"/>
+ <pathelement path="${javax.el-api.lib}"/>
+ <pathelement path="${javax.el.lib}"/>
+ <pathelement path="${classmate.lib}"/>
</path>
<path id="oxm.compile.path">
<path refid="xml.parser.path"/>
@@ -171,6 +189,8 @@
<pathelement path="${eclipselink.lib}"/>
<pathelement path="${jaxb-xjc.lib}"/>
<pathelement path="${jaxb-impl.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
+ <pathelement path="${javax.validation.lib}"/>
</path>
<path id="jaxb.run.against.jar.path">
<path refid="xml.parser.path"/>
@@ -185,8 +205,16 @@
<pathelement path="${classes.dir}"/>
<pathelement path="${resource.dir}"/>
<pathelement path="${eclipselink.lib}"/>
+ <pathelement path="${xjc-beanval.lib}"/>
<pathelement path="${jaxb-xjc.lib}"/>
<pathelement path="${jaxb-impl.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
+ <pathelement path="${javax.validation.lib}"/>
+ <pathelement path="${hibernate-validator.lib}"/>
+ <pathelement path="${jboss-logging.lib}"/>
+ <pathelement path="${javax.el-api.lib}"/>
+ <pathelement path="${javax.el.lib}"/>
+ <pathelement path="${classmate.lib}"/>
</path>
<path id="oxm.compile.against.jar.path">
<path refid="xml.parser.path"/>
@@ -372,6 +400,7 @@
<include name="org/eclipse/persistence/testing/jaxb/JAXBTestSuite2.java"/>
<include name="org/eclipse/persistence/testing/jaxb/JAXBTestSuite3.java"/>
<include name="org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java"/>
+ <include name="org/eclipse/persistence/testing/jaxb/JAXBTestSuite5.java"/>
<!--<include name="org/eclipse/persistence/testing/jaxb/JAXBPerformanceTestSuite.java"/>-->
<include name="org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsSuite.java"/>
<include name="org/eclipse/persistence/testing/jaxb/annotations/AnnotationsTestSuite.java"/>
@@ -400,6 +429,7 @@
<mkdir dir="${report.dir}/srg/jaxb"/>
<mkdir dir="${resource.dir}/${tmp.dir}"/>
<junit printsummary="yes" fork="true" dir="${resource.dir}" showoutput="yes" maxmemory="512m">
+ <jvmarg value="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"/>
<env key="T_WORK" value="${tmp.dir}"/>
<sysproperty key="platformType" value="SAX"/>
<sysproperty key="metadataType" value="JAVA"/>
@@ -436,7 +466,7 @@
<formatter type="xml"/>
</batchtest>
<classpath>
- <path refid="@{runpathref}"/>
+ <path refid="@{runpathref}"/>
</classpath>
</junit>
</sequential>
@@ -477,7 +507,7 @@
<formatter type="xml"/>
</batchtest>
<classpath>
- <path refid="@{runpathref}"/>
+ <path refid="@{runpathref}"/>
</classpath>
</junit>
</sequential>
@@ -680,15 +710,15 @@
<sequential>
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}"
- destdir="${classes.dir}"
- debug="${javac.debug}"
- debuglevel="${javac.debuglevel}"
- encoding="UTF-8"
- optimize="${javac.optimize}"
- source="${javac.version}"
- deprecation="${javac.deprecation}"
- failonerror="false"
- includes="org/eclipse/persistence/testing/@{subcomponent}/**/*.java">
+ destdir="${classes.dir}"
+ debug="${javac.debug}"
+ debuglevel="${javac.debuglevel}"
+ encoding="UTF-8"
+ optimize="${javac.optimize}"
+ source="${javac.version}"
+ deprecation="${javac.deprecation}"
+ failonerror="false"
+ includes="org/eclipse/persistence/testing/@{subcomponent}/**/*.java">
<classpath>
<path refid="@{compilepathref}"/>
</classpath>
diff --git a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/customized_schema.xsd b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/customized_schema.xsd
new file mode 100644
index 0000000..7cd297b
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/customized_schema.xsd
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
+ xmlns:bv="http://jaxb.dev.java.net/plugin/bean-validation"
+ targetNamespace="cs" elementFormDefault="qualified"
+ jxb:extensionBindingPrefixes="bv"
+ jxb:version="2.1">
+
+ <xs:annotation>
+ <xs:appinfo>
+ <jxb:bindings node="/xs:schema/xs:complexType/xs:sequence/xs:element[@name='generic']">
+ <bv:facet type="maxLength" message="Hello, world!" groups="org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.Binding Team , org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.Rocket Team"/>
+ <bv:facet type="pattern" message="Hello." groups="Object"/>
+ <bv:facet type="future" message="Welcome to the Future!" groups="org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.BindingTeam"/>
+ <bv:facet type="past" message="Farewell from the ancestors." groups="org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.Ancestors"/>
+ <bv:facet type="assertTrue" message="True fan of the team!" groups="org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.BindingTeam"/>
+ <bv:facet type="assertFalse" message="false" groups="Object"/>
+ <bv:facet type="org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase.CustomAnnotation" value="I am a custom annotation and this is my value."/>
+ </jxb:bindings>
+ </xs:appinfo>
+ </xs:annotation>
+ <xs:complexType name="Custom">
+ <xs:sequence>
+ <xs:element name="generic">
+ <xs:simpleType>
+ <xs:restriction base="xs:string">
+ <xs:pattern value="10"/>
+ <xs:pattern value="7"/>
+ <xs:maxLength value="4"/>
+ </xs:restriction>
+ </xs:simpleType>
+ </xs:element>
+ </xs:sequence>
+ </xs:complexType>
+</xs:schema>
diff --git a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/golden_file.xsd b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/golden_file.xsd
new file mode 100644
index 0000000..cc64b9b
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/golden_file.xsd
@@ -0,0 +1,119 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsd:schema xmlns:ns0="gf" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="gf" elementFormDefault="qualified">
+ <xsd:complexType name="Strings">
+ <xsd:sequence>
+ <xsd:element name="regexShorthands">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:string">
+ <xsd:pattern value="\i"/>
+ <xsd:pattern value="\I"/>
+ <xsd:pattern value="\c"/>
+ <xsd:pattern value="\C"/>
+ <xsd:pattern value="\d"/>
+ <xsd:pattern value="\D"/>
+ <xsd:pattern value="\s"/>
+ <xsd:pattern value="\S"/>
+ <xsd:pattern value="\h"/>
+ <xsd:pattern value="\H"/>
+ <xsd:pattern value="\V"/>
+ <xsd:pattern value="\R"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="idType">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:ID">
+ <xsd:maxLength value="100"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="genericString">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:string">
+ <xsd:maxLength value="1024"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="maxLength">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:string">
+ <xsd:maxLength value="1024"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="minLength" type="xsd:string"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ <xsd:complexType name="Main">
+ <xsd:sequence>
+ <xsd:element name="numbers" type="ns0:Numbers"/>
+ <xsd:element name="strings" type="ns0:Strings" maxOccurs="2"/>
+ <xsd:element name="unsignedByte" nillable="true">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:short">
+ <xsd:minInclusive value="0"/>
+ <xsd:maxInclusive value="255"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="byteArray">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:string">
+ <xsd:maxLength value="18"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="someCollection" type="xsd:anyType" maxOccurs="unbounded"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ <xsd:complexType name="Numbers">
+ <xsd:sequence>
+ <xsd:element name="minInclusive">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:long">
+ <xsd:minInclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="maxInclusive">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:long">
+ <xsd:maxInclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="minExclusive">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:long">
+ <xsd:minExclusive value="0"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="maxExclusive">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:long">
+ <xsd:maxExclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="minMaxExclusive">
+ <xsd:simpleType>
+ <xsd:restriction base="xsd:int">
+ <xsd:minExclusive value="0"/>
+ <xsd:maxExclusive value="9223372"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+ </xsd:element>
+ <xsd:element name="NumberWithHiddenValueAttribute" type="ns0:NumberWithHiddenValueAttribute"/>
+ </xsd:sequence>
+ </xsd:complexType>
+ <xsd:complexType name="NumberWithHiddenValueAttribute">
+ <xsd:simpleContent>
+ <xsd:extension base="xsd:string">
+ <xsd:attribute name="code" type="xsd:string" use="required"/>
+ <xsd:attribute name="whatNumber" type="xsd:long" use="required"/>
+ </xsd:extension>
+ </xsd:simpleContent>
+ </xsd:complexType>
+ <xsd:element name="main" type="ns0:Main"/>
+</xsd:schema>
diff --git a/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/rich_schema.xsd b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/rich_schema.xsd
new file mode 100644
index 0000000..b2bace0
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/resource/org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc/rich_schema.xsd
@@ -0,0 +1,154 @@
+<xsd:schema
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="rs"
+ xmlns:rs="rs"
+ elementFormDefault="qualified">
+
+ <xsd:element name="main" type="rs:Main"/>
+
+ <xsd:complexType name="Main">
+ <xsd:sequence>
+ <xsd:element name="numbers" type="rs:Numbers"/>
+ <xsd:element maxOccurs="2" minOccurs="1" name="strings" type="rs:Strings"/>
+ <xsd:element nillable="true" name="unsignedByte" type="rs:unsignedByte"/>
+ <xsd:element nillable="false" name="byteArray" type="rs:byteArray"/>
+ <xsd:element name="someCollection" minOccurs="1" maxOccurs="unbounded"/>
+ </xsd:sequence>
+ </xsd:complexType>
+
+ <xsd:complexType name="Numbers">
+ <xsd:sequence>
+ <xsd:element name="minInclusive" type="rs:minInclusive"/>
+ <xsd:element name="maxInclusive" type="rs:maxInclusive"/>
+ <xsd:element name="minExclusive" type="rs:minExclusive"/>
+ <xsd:element name="maxExclusive" type="rs:maxExclusive"/>
+ <xsd:element name="minMaxExclusive" type="rs:minMaxExclusive"/>
+ <xsd:element maxOccurs="1" minOccurs="1" name="NumberWithHiddenValueAttribute" type="rs:NumberWithHiddenValueAttribute"/>
+ </xsd:sequence>
+ </xsd:complexType>
+
+
+ <xsd:simpleType name="Number">
+ <xsd:restriction base="xsd:string">
+ <xsd:minLength value="1"/>
+ <xsd:maxLength value="5"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:complexType name="NumberWithHiddenValueAttribute">
+ <xsd:simpleContent>
+ <xsd:extension base="rs:Number">
+ <xsd:attribute name="code" type="xsd:string" use="required"/>
+ <xsd:attribute name = "whatNumber" type="xsd:long" use="required"/>
+ </xsd:extension>
+ </xsd:simpleContent>
+ </xsd:complexType>
+
+
+ <xsd:complexType name="Strings">
+ <xsd:sequence>
+ <xsd:element name="regexShorthands" type="rs:regexShorthands"/>
+ <xsd:element name="idType" type="rs:idType"/>
+ <xsd:element name="genericString" type="rs:minMaxLength"/>
+ <xsd:element name="maxLength" type="rs:maxLength"/>
+ <xsd:element name="minLength" type="rs:minLength"/>
+ </xsd:sequence>
+ </xsd:complexType>
+
+ <xsd:simpleType name="regexShorthands">
+ <xsd:restriction base="xsd:string">
+ <xsd:pattern value="\i"/>
+ <xsd:pattern value="\I"/>
+ <xsd:pattern value="\c"/>
+ <xsd:pattern value="\C"/>
+ <xsd:pattern value="\d"/>
+ <xsd:pattern value="\D"/>
+ <!--'This shorthand translates to a pattern with ampersand characters, which causes the Java Matcher behave non-deterministically and malfunction from time to time!'-->
+ <!--<xsd:pattern value="\w"/>-->
+ <!--'This shorthand translates to a pattern with ampersand characters, which causes the Java Matcher behave non-deterministically and malfunction from time to time!'-->
+ <!--<xsd:pattern value="\W"/>-->
+ <xsd:pattern value="\s"/>
+ <xsd:pattern value="\S"/>
+ <!--'This expression is not supported in the current option setting.'-->
+ <!--<xsd:pattern value="\b"/>-->
+ <!--'This expression is not supported in the current option setting.'-->
+ <!--<xsd:pattern value="\B"/>-->
+ <xsd:pattern value="\h"/>
+ <xsd:pattern value="\H"/>
+ <!--'This expression is not supported in the current option setting.'-->
+ <!--<xsd:pattern value="\v"/>-->
+ <xsd:pattern value="\V"/>
+ <!--'This expression is not supported in the current option setting.'-->
+ <!--<xsd:pattern value="\X"/>-->
+ <xsd:pattern value="\R"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="minMaxLength">
+ <xsd:restriction base="xsd:string">
+ <xsd:minLength value="0"/>
+ <xsd:maxLength value="1024"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="maxLength">
+ <xsd:restriction base="xsd:string">
+ <xsd:maxLength value="1024"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="minLength">
+ <xsd:restriction base="xsd:string">
+ <xsd:minLength value="0"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="unsignedByte">
+ <xsd:restriction base="xsd:unsignedByte">
+ <xsd:pattern value="[0-9]"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="maxInclusive">
+ <xsd:restriction base="xsd:long">
+ <xsd:maxInclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="minInclusive">
+ <xsd:restriction base="xsd:long">
+ <xsd:minInclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="maxExclusive">
+ <xsd:restriction base="xsd:long">
+ <xsd:maxExclusive value="1000"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="minExclusive">
+ <xsd:restriction base="xsd:long">
+ <xsd:minExclusive value="0"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="minMaxExclusive">
+ <xsd:restriction base="xsd:long">
+ <xsd:minExclusive value="0"/>
+ <xsd:maxExclusive value="9223372"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="byteArray">
+ <xsd:restriction base="xsd:hexBinary">
+ <xsd:maxLength value="18" />
+ </xsd:restriction>
+ </xsd:simpleType>
+
+ <xsd:simpleType name="idType">
+ <xsd:restriction base="xsd:ID">
+ <xsd:maxLength value="100"/>
+ </xsd:restriction>
+ </xsd:simpleType>
+</xsd:schema> \ No newline at end of file
diff --git a/moxy/eclipselink.moxy.test/resource/schema1.xsd b/moxy/eclipselink.moxy.test/resource/schema1.xsd
new file mode 100644
index 0000000..a085ee3
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/resource/schema1.xsd
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:y="addressNamespace" xmlns:x="employeeNamespace" targetNamespace="employeeNamespace">
+ <xsd:import schemaLocation="someExistingSchema.xsd" namespace="addressNamespace"/>
+ <xsd:complexType name="employee-type">
+ <xsd:sequence>
+ <xsd:element name="firstName" type="xsd:string"/>
+ <xsd:element name="birthday" type="xsd:date" minOccurs="0"/>
+ <xsd:element name="age" type="xsd:int"/>
+ <xsd:element name="lastName" type="xsd:string" minOccurs="0"/>
+ <xsd:element name="address" type="y:address-type" minOccurs="0"/>
+ <xsd:element name="startTime" type="xsd:time" minOccurs="0"/>
+ <xsd:element name="responsibilities" minOccurs="0">
+ <xsd:simpleType>
+ <xsd:list itemType="xsd:string"/>
+ </xsd:simpleType>
+ </xsd:element>
+ </xsd:sequence>
+ <xsd:attribute name="id" type="xsd:int" use="required"/>
+ </xsd:complexType>
+ <xsd:element name="employee-data" type="x:employee-type"/>
+</xsd:schema>
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBSRGTestSuite.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBSRGTestSuite.java
index bb5bf6f..9931d8a 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBSRGTestSuite.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBSRGTestSuite.java
@@ -13,20 +13,20 @@
package org.eclipse.persistence.testing.jaxb;
import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-import org.eclipse.persistence.testing.jaxb.schemagen.SchemaGenTestSuite;
-import org.eclipse.persistence.testing.jaxb.xmlmarshaller.JAXBDOMTestSuite;
-import org.eclipse.persistence.testing.jaxb.xmlmarshaller.JAXBSAXTestSuite;
-
-public class JAXBSRGTestSuite extends TestCase {
- public static Test suite() {
- TestSuite suite = new TestSuite("JAXB SRG Test Suite");
- suite.addTest(SchemaGenTestSuite.suite());
- suite.addTest(JAXBSAXTestSuite.suite());
- suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlrootelement.XmlRootElementNamespaceTestCases.class);
- suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlrootelement.XmlRootElementNoNamespaceTestCases.class);
- suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlelement.XmlElementNamespaceTestCases.class);
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.eclipse.persistence.testing.jaxb.schemagen.SchemaGenTestSuite;
+import org.eclipse.persistence.testing.jaxb.xmlmarshaller.JAXBSAXTestSuite;
+
+public class JAXBSRGTestSuite extends TestCase {
+ public static Test suite() {
+ TestSuite suite = new TestSuite("JAXB SRG Test Suite");
+
+ suite.addTest(SchemaGenTestSuite.suite());
+ suite.addTest(JAXBSAXTestSuite.suite());
+ suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlrootelement.XmlRootElementNamespaceTestCases.class);
+ suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlrootelement.XmlRootElementNoNamespaceTestCases.class);
+ suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlelement.XmlElementNamespaceTestCases.class);
suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlelement.XmlElementCollectionTestCases.class);
suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlattribute.XmlAttributeNamespaceTestCases.class);
suite.addTestSuite(org.eclipse.persistence.testing.jaxb.xmlattribute.XmlAttributeNoNamespaceTestCases.class);
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java
index 8d1664c..e8cafe7 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite4.java
@@ -12,7 +12,6 @@
******************************************************************************/
package org.eclipse.persistence.testing.jaxb;
-import org.eclipse.persistence.testing.jaxb.casesensitivity.JAXBCaseInsensitivityTestCase;
import org.eclipse.persistence.testing.jaxb.collections.CollectionsTestSuite;
import org.eclipse.persistence.testing.jaxb.defaultvalue.DefaultValueTestSuite;
import org.eclipse.persistence.testing.jaxb.employee.JAXBEmployeeNSTestCases;
@@ -82,8 +81,6 @@ public class JAXBTestSuite4 {
suite.addTestSuite(TypeAttributeInheritanceTestCases.class);
suite.addTestSuite(OtherRootTestCases.class);
suite.addTest(TypeVariableTestSuite.suite());
-
- suite.addTestSuite(JAXBCaseInsensitivityTestCase.class);
return suite;
}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite5.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite5.java
new file mode 100644
index 0000000..7b5486d
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/JAXBTestSuite5.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationBindingsTestCase;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.BeanValidationRuntimeTestCase;
+import org.eclipse.persistence.testing.jaxb.casesensitivity.JAXBCaseInsensitivityTestCase;
+
+/**
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+public class JAXBTestSuite5 {
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("JAXB20 Compiler Test Suite5");
+
+ suite.addTestSuite(JAXBCaseInsensitivityTestCase.class);
+ suite.addTestSuite(BeanValidationRuntimeTestCase.class);
+ suite.addTestSuite(BeanValidationBindingsTestCase.class);
+
+ return suite;
+ }
+
+
+ public static void main(String[] args) {
+ String[] arguments = { "-c", "org.eclipse.persistence.testing.jaxb.JAXBTestSuite5" };
+ junit.textui.TestRunner.main(arguments);
+ }
+
+}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/PropertyTypeTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/PropertyTypeTestCases.java
index fdfbdb8..3bab055 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/PropertyTypeTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/annotations/PropertyTypeTestCases.java
@@ -27,7 +27,6 @@ import org.eclipse.persistence.jaxb.compiler.TypeInfo;
import org.eclipse.persistence.jaxb.javamodel.JavaClass;
import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl;
import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl;
-import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases;
public class PropertyTypeTestCases extends JAXBWithJSONTestCases {
@@ -71,7 +70,7 @@ public class PropertyTypeTestCases extends JAXBWithJSONTestCases {
Generator generator = new Generator(new JavaModelInputImpl(new Class[] { TestObject.class }, new JavaModelImpl(this.classLoader)));
CoreProject proj = generator.generateProject();
- TypeInfo info = generator.getAnnotationsProcessor().getTypeInfo().get("org.eclipse.persistence.testing.jaxb.annotations.TestObject");
+ TypeInfo info = generator.getAnnotationsProcessor().getTypeInfos().get("org.eclipse.persistence.testing.jaxb.annotations.TestObject");
Property booleanProp = info.getProperties().get("booleanTest");
JavaClass type = booleanProp.getType();
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationBindingsTestCase.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationBindingsTestCase.java
new file mode 100644
index 0000000..f1afc9e
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationBindingsTestCase.java
@@ -0,0 +1,401 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation;
+
+import com.sun.tools.xjc.Driver;
+import junit.framework.Assert;
+import org.eclipse.persistence.jaxb.compiler.Generator;
+
+import javax.tools.Diagnostic;
+import javax.validation.Valid;
+import javax.validation.constraints.AssertFalse;
+import javax.validation.constraints.AssertTrue;
+import javax.validation.constraints.DecimalMax;
+import javax.validation.constraints.DecimalMin;
+import javax.validation.constraints.Future;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Past;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl;
+
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.ToolProvider;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlValue;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.OutputStreamWriter;
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+
+import static org.eclipse.persistence.testing.jaxb.beanvalidation.ContentComparator.equalsXML;
+
+/**
+ * Tests the generation of JAXB Facets and Bean Validation annotations during Schemagen and XJC, respectively.
+ *
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ */
+public class BeanValidationBindingsTestCase extends junit.framework.TestCase {
+
+ private static final String PATH_TO_SCHEMA_DIRECTORY = "org/eclipse/persistence/testing/jaxb/beanvalidation/sgen_xjc";
+ private static final String GOLDEN_FILE_PATH = PATH_TO_SCHEMA_DIRECTORY + "/golden_file.xsd";
+ private static final String RICH_SCHEMA_PATH = PATH_TO_SCHEMA_DIRECTORY + "/rich_schema.xsd";
+ private static final String CUSTOMIZED_SCHEMA_PATH = PATH_TO_SCHEMA_DIRECTORY + "/customized_schema.xsd";
+ private static final String GENERATED_SCHEMA_PATH = PATH_TO_SCHEMA_DIRECTORY + "/schema1.xsd";
+
+ // Handles error case where no BV annotations would be generated on class fields and would still pass the equality test.
+ boolean annotationsGenerated;
+
+ private String pkg;
+
+ @Override
+ public void tearDown() throws Exception {
+ assertTrue(deleteDir(new File(pkg)));
+ //noinspection ResultOfMethodCallIgnored
+ new File(GENERATED_SCHEMA_PATH).delete();
+ }
+
+ /**
+ * A fancy test demonstrating (and testing) that it is possible to perform
+ * a round-trip in a lucky case where the XML Schema is identical to the
+ * original golden file.
+ * In practice, the XJC/Schemagen transformations guarantee only equality
+ * of post round-trip schema with the original, not identity.
+ * This test should still pass even if changes are done to our code.
+ */
+ public void testGoldenFileIdentity() throws Exception {
+ pkg = "gf";
+
+ roundTrip(GOLDEN_FILE_PATH, pkg);
+ assertTrue(equalsXML(new File(GOLDEN_FILE_PATH), new File(GENERATED_SCHEMA_PATH)));
+ }
+
+ /**
+ * Tests equality of the original schema and schema after round-trip, with
+ * bean validation annotations and facets.
+ * Also tests equality of generated Java classes from the original schema
+ * and from the schema after round-trip.
+ */
+ public void testEqualitySchemaAndJava() throws Exception {
+ pkg = "rs";
+
+ Class<?>[] cTenured = roundTrip(RICH_SCHEMA_PATH, pkg);
+
+ xjcGenerateJavaSources(RICH_SCHEMA_PATH); // Regenerate the sources.
+ compileGeneratedSources(createCompileList(pkg));
+ Class<?>[] cYoung = loadCompiledClasses(createLoadList(pkg));
+
+ assertTrue(equalsClasses(cTenured, cYoung));
+ }
+
+ /**
+ * Tests customizations, i.e. facet customizations + custom facets, i.e.
+ * Future, Past, AssertTrue, AssertFalse.
+ */
+ public void testFacetCustomizationsAndCustomFacets() throws Exception {
+ pkg = "cs";
+
+ xjcGenerateJavaSourcesWithCustomizations(CUSTOMIZED_SCHEMA_PATH);
+ compileGeneratedSources(createCompileList(pkg));
+ Class<?> custom = loadCompiledClasses(createLoadList(pkg))[0];
+
+ Field generic = custom.getDeclaredField("generic");
+ Size s = generic.getAnnotation(Size.class);
+ assertEquals(s.message(), "Hello, world!");
+ assertEquals(s.groups()[0], BindingTeam.class);
+ assertEquals(s.groups()[1], RocketTeam.class);
+ assertEquals(s.max(), 4);
+
+ Pattern p1 = generic.getAnnotation(Pattern.List.class).value()[0];
+ Pattern p2 = generic.getAnnotation(Pattern.List.class).value()[1];
+ assertEquals(p1.message(), p2.message());
+ assertTrue(Arrays.equals(p1.groups(), p2.groups()));
+ assertEquals(p1.message(), "Hello.");
+ assertEquals(p1.groups()[0], Object.class);
+ assertEquals(p1.regexp(), "10");
+
+ Future f = generic.getAnnotation(Future.class);
+ assertEquals(f.message(), "Welcome to the Future!");
+ assertEquals(f.groups()[0], BindingTeam.class);
+
+ Past p = generic.getAnnotation(Past.class);
+ assertEquals(p.message(), "Farewell from the ancestors.");
+ assertEquals(p.groups()[0], Ancestors.class);
+
+ AssertTrue at = generic.getAnnotation(AssertTrue.class);
+ assertEquals(at.message(), "True fan of the team!");
+ assertEquals(at.groups()[0], BindingTeam.class);
+
+ AssertFalse af = generic.getAnnotation(AssertFalse.class);
+ assertEquals(af.message(), "false");
+ assertEquals(af.groups()[0], Object.class);
+
+ // To test a user custom annotation.
+ CustomAnnotation xmlKey = generic.getAnnotation(CustomAnnotation.class);
+ assertNotNull(xmlKey);
+ }
+
+ /**
+ * Tests that the XJC detects all facets and generates their respective
+ * annotations correctly.
+ */
+ @SuppressWarnings({ "UnusedAssignment", "UnusedDeclaration" })
+ public void testAllFacetsAndAnnotations() throws Exception {
+ pkg = "rs";
+
+ Class<?>[] c = roundTrip(RICH_SCHEMA_PATH, pkg);
+ Class<?> Main = c[0];
+ Class<?> Numbers = c[1];
+ Class<?> NumberWithHiddenValueAttribute = c[2];
+ Class<?> Strings = c[4];
+
+ XmlElement xmlElement;
+ Size size;
+ DecimalMax decimalMax;
+ DecimalMin decimalMin;
+ Pattern.List patternList;
+ Pattern pattern;
+
+ /* Main.class */
+ Field numbers = Main.getDeclaredField("numbers");
+ assertNotNull(numbers.getAnnotation(Valid.class));
+ assertNotNull(numbers.getAnnotation(NotNull.class));
+ xmlElement = numbers.getAnnotation(XmlElement.class);
+ assertFalse(xmlElement.nillable());
+
+ Field strings = Main.getDeclaredField("strings");
+ size = strings.getAnnotation(Size.class);
+ assertTrue(size.min() == 1 && size.max() == 2);
+ assertNotNull(strings.getAnnotation(Valid.class));
+ assertNotNull(strings.getAnnotation(NotNull.class));
+ xmlElement = strings.getAnnotation(XmlElement.class);
+ assertFalse(xmlElement.nillable());
+
+ Field unsignedByte = Main.getDeclaredField("unsignedByte");
+ decimalMax = unsignedByte.getAnnotation(DecimalMax.class);
+ assertEquals(decimalMax.value(), "255");
+ assertTrue(decimalMax.inclusive());
+ decimalMin = unsignedByte.getAnnotation(DecimalMin.class);
+ assertEquals(decimalMin.value(), "0");
+ assertTrue(decimalMin.inclusive());
+
+ Field byteArray = Main.getDeclaredField("byteArray");
+ size = byteArray.getAnnotation(Size.class);
+ assertTrue(size.max() == 18);
+
+ Field someCollection = Main.getDeclaredField("someCollection");
+ size = someCollection.getAnnotation(Size.class);
+ assertTrue(size.min() == 1);
+ assertNotNull(someCollection.getAnnotation(Valid.class));
+ assertNotNull(someCollection.getAnnotation(NotNull.class));
+
+ /* Numbers.class */
+ Field minInclusive = Numbers.getDeclaredField("minInclusive");
+ decimalMin = minInclusive.getAnnotation(DecimalMin.class);
+ assertEquals(decimalMin.value(), "1000");
+ assertTrue(decimalMin.inclusive());
+
+ Field maxInclusive = Numbers.getDeclaredField("maxInclusive");
+ decimalMax = maxInclusive.getAnnotation(DecimalMax.class);
+ assertEquals(decimalMax.value(), "1000");
+ assertTrue(decimalMax.inclusive());
+
+ Field minExclusive = Numbers.getDeclaredField("minExclusive");
+ decimalMin = minExclusive.getAnnotation(DecimalMin.class);
+ assertEquals(decimalMin.value(), "0");
+ assertFalse(decimalMin.inclusive());
+
+ Field maxExclusive = Numbers.getDeclaredField("maxExclusive");
+ decimalMax = maxExclusive.getAnnotation(DecimalMax.class);
+ assertEquals(decimalMax.value(), "1000");
+ assertFalse(decimalMax.inclusive());
+
+ Field minMaxExclusive = Numbers.getDeclaredField("minMaxExclusive");
+ decimalMax = minMaxExclusive.getAnnotation(DecimalMax.class);
+ assertEquals(decimalMax.value(), "9223372");
+ assertFalse(decimalMax.inclusive());
+ decimalMin = minMaxExclusive.getAnnotation(DecimalMin.class);
+ assertEquals(decimalMin.value(), "0");
+ assertFalse(decimalMin.inclusive());
+
+ /* NumberWithHiddenValueAttribute.class */
+ Field value = NumberWithHiddenValueAttribute.getDeclaredField("value");
+ assertNotNull(value.getAnnotation(XmlValue.class));
+ size = value.getAnnotation(Size.class);
+ assertTrue(size.min() == 1 && size.max() == 5);
+
+ Field code = NumberWithHiddenValueAttribute.getDeclaredField("code");
+ assertNotNull(code.getAnnotation(NotNull.class));
+
+ Field whatNumber = NumberWithHiddenValueAttribute.getDeclaredField("whatNumber");
+ XmlAttribute xmlAttribute = whatNumber.getAnnotation(XmlAttribute.class);
+ assertTrue(xmlAttribute.required());
+
+ /* Strings.class */
+ Field regexShorthands = Strings.getDeclaredField("regexShorthands");
+ patternList = regexShorthands.getAnnotation(Pattern.List.class);
+ Pattern[] patterns = patternList.value();
+ assertEquals("[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]", patterns[0].regexp());
+ assertEquals("[^:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]", patterns[1].regexp());
+ assertEquals("[-.0-9:A-Z_a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]", patterns[2].regexp());
+ assertEquals("[^-.0-9:A-Z_a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]", patterns[3].regexp());
+ assertEquals("\\p{Nd}", patterns[4].regexp());
+ assertEquals("\\P{Nd}", patterns[5].regexp());
+ assertEquals("[\\u0009-\\u000D\\u0020\\u0085\\u00A0\\u1680\\u180E\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]", patterns[6].regexp());
+ assertEquals("[^\\u0009-\\u000D\\u0020\\u0085\\u00A0\\u1680\\u180E\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]", patterns[7].regexp());
+ assertEquals("[\\u0009\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u200A\\u202F\\u205F\\u3000]", patterns[8].regexp());
+ assertEquals("[^\\u0009\\u0020\\u00A0\\u1680\\u180E\\u2000\\u2001-\\u200A\\u202F\\u205F\\u3000]", patterns[9].regexp());
+ assertEquals("[^\\u000A-\\u000D\\u0085\\u2028\\u2029]", patterns[10].regexp());
+ assertEquals("(?:(?>\\u000D\\u000A)|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029])", patterns[11].regexp());
+
+ Field idType = Strings.getDeclaredField("idType");
+ pattern = idType.getAnnotation(Pattern.class);
+ assertEquals(pattern.regexp(), "[[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]-[:]][[-.0-9:A-Z_a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]-[:]]*");
+ assertTrue(idType.getAnnotation(Size.class).max() == 100);
+
+ Field genericString = Strings.getDeclaredField("genericString");
+ assertTrue(genericString.getAnnotation(Size.class).min() == 0);
+ assertTrue(genericString.getAnnotation(Size.class).max() == 1024);
+
+ Field maxLength = Strings.getDeclaredField("maxLength");
+ assertTrue(maxLength.getAnnotation(Size.class).max() == 1024);
+
+ Field minLength = Strings.getDeclaredField("minLength");
+ assertTrue(minLength.getAnnotation(Size.class).min() == 0);
+ }
+
+ private Class<?>[] roundTrip(String schemaPath, String pkg) throws Exception {
+ xjcGenerateJavaSources(schemaPath);
+ compileGeneratedSources(createCompileList(pkg));
+ Class<?>[] classes = loadCompiledClasses(createLoadList(pkg));
+ generateSchema(classes); // Generates resource/PATH_TO_SCHEMA_DIRECTORY/schema1.xsd.
+ return classes;
+ }
+
+ public void xjcGenerateJavaSources(String schemaPath) throws Exception {
+ Driver.run(new String[] { schemaPath, "-XBeanVal" }, System.out, System.out);
+ }
+
+ public void xjcGenerateJavaSourcesWithCustomizations(String schemaPath) throws Exception {
+ Driver.run(new String[] { schemaPath, "-extension", "-XBeanVal" }, System.out, System.out);
+ }
+
+ private void generateSchema(Class<?>[] classes) throws FileNotFoundException {
+ JavaModelImpl javaModel = new JavaModelImpl(Thread.currentThread().getContextClassLoader());
+ JavaModelInputImpl modelInput = new JavaModelInputImpl(classes, javaModel);
+ modelInput.setFacets(true);
+ Generator gen = new Generator(modelInput);
+ gen.generateSchemaFiles(PATH_TO_SCHEMA_DIRECTORY, null);
+ }
+
+ private void compileGeneratedSources(File... compileList) {
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ DiagnosticCollector<? super JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>();
+ StandardJavaFileManager fm = compiler.getStandardFileManager(diag, null, null);
+ Iterable<? extends JavaFileObject> compilationUnits = fm.getJavaFileObjectsFromFiles(Arrays.asList(compileList));
+ JavaCompiler.CompilationTask task = compiler.getTask(new OutputStreamWriter(System.out),fm,diag, null, null, compilationUnits);
+
+ if (!task.call()) {
+ for (Diagnostic diagnostic : diag.getDiagnostics())
+ System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
+ Assert.fail("Compilation of generated classes failed. See the diagnostics output.");
+ }
+ }
+
+ private File[] createCompileList(String pkg) {
+ return "cs".equals(pkg)
+ ? new File[]{new File(pkg + "/Custom.java"),
+ new File(pkg + "/ObjectFactory.java"),
+ new File(pkg + "/package-info.java")}
+ : new File[]{new File(pkg + "/Main.java"),
+ new File(pkg + "/Numbers.java"),
+ new File(pkg + "/NumberWithHiddenValueAttribute.java"),
+ new File(pkg + "/ObjectFactory.java"),
+ new File(pkg + "/package-info.java"),
+ new File(pkg + "/Strings.java")};
+ }
+
+ private Class<?>[] loadCompiledClasses(String... loadList) throws ClassNotFoundException {
+ ClassLoader cl = this.getClass().getClassLoader();
+ Class<?>[] loadedClasses = new Class[loadList.length];
+ for (int i = 0; i < loadedClasses.length; i++)
+ loadedClasses[i] = cl.loadClass(loadList[i]);
+ return loadedClasses;
+ }
+
+ private String[] createLoadList(String pkg) throws ClassNotFoundException {
+ return "cs".equals(pkg)
+ ? new String[]{pkg + ".Custom", pkg + ".ObjectFactory" }
+ : new String[]{pkg + ".Main", pkg + ".Numbers",
+ pkg + ".NumberWithHiddenValueAttribute", pkg + ".ObjectFactory",
+ pkg + ".Strings"};
+ }
+
+ private boolean equalsClasses(Class<?>[] cTenured, Class<?>[] cYoung) {
+ if (cTenured.length != cYoung.length) return false;
+ for (int i = 0; i < cTenured.length; i++)
+ if (!equalsAnnotations(cTenured[i], cYoung[i])) return false;
+ return true;
+ }
+
+ private boolean equalsAnnotations(Class<?> c1, Class<?> c2) {
+ Field[] f1 = c1.getDeclaredFields();
+ Field[] f2 = c2.getDeclaredFields();
+ if (f1.length != f2.length) return false;
+ for (int i = 0; i<f2.length; i++) {
+ Annotation[] a1 = f1[i].getDeclaredAnnotations();
+ Annotation[] a2 = f2[i].getDeclaredAnnotations();
+ if (!Arrays.equals(a1, a2)) return false;
+ // Returns false if no BV annotations were generated.
+ if (!annotationsGenerated)
+ for (Annotation a : a1)
+ if (a.annotationType().equals(NotNull.class)) {
+ annotationsGenerated = true;
+ break;
+ }
+ }
+ return annotationsGenerated;
+ }
+
+ private static boolean deleteDir(File file) {
+ if (file.isDirectory()) {
+ String[] children = file.list();
+ for (String child : children)
+ deleteDir(new File(file, child));
+ return file.delete();
+ } else
+ // The directory is now empty so delete it
+ return file.delete();
+ }
+
+ public interface BindingTeam{}
+ public @interface RocketTeam{}
+ public abstract class Ancestors{}
+ @Target({ ElementType.FIELD})
+ @Retention(RetentionPolicy.RUNTIME)
+ public static @interface CustomAnnotation {
+ String value();
+ }
+
+}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationRuntimeTestCase.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationRuntimeTestCase.java
new file mode 100644
index 0000000..9395056
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/BeanValidationRuntimeTestCase.java
@@ -0,0 +1,240 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation;
+
+import org.eclipse.persistence.exceptions.BeanValidationException;
+import org.eclipse.persistence.jaxb.BeanValidationMode;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
+import org.eclipse.persistence.jaxb.JAXBContextProperties;
+import org.eclipse.persistence.jaxb.JAXBMarshaller;
+import org.eclipse.persistence.jaxb.JAXBUnmarshaller;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.eclipse.persistence.jaxb.UnmarshallerProperties;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom.Department;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom.Drivers;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom.DrivingLicense;
+import org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom.Employee;
+import org.junit.After;
+import org.junit.Before;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.ValidatorFactory;
+import javax.validation.groups.Default;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.PropertyException;
+import java.io.File;
+import java.util.AbstractSequentialList;
+import java.util.ArrayList;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Tests the Bean Validation for MOXy Runtime, with Target groups.
+ * Tests include:
+ * - setting properties (mode, preferred validation factory) through JAXBContext,
+ * marshaller and unmarshaller, and overriding them,
+ * - validation on valid objects before marshalling and after unmarshalling,
+ * - validation on invalid objects before marshalling and after unmarshalling,
+ * - validation with Target groups,
+ * - retrieval of correct error messages when constraint violations happen.
+ * Everything is tested with both XML and JSON marshalling and unmarshalling.
+ *
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ */
+public class BeanValidationRuntimeTestCase extends junit.framework.TestCase {
+
+ private static final File FILE_VALID = new File("org/eclipse/persistence/testing/jaxb/beanvalidation/rt/employee.xml");
+ private static final File FILE_INVALID = new File("org/eclipse/persistence/testing/jaxb/beanvalidation/rt/employeeInvalid.xml");
+ private static final File FILE_JSON_VALID = new File("org/eclipse/persistence/testing/jaxb/beanvalidation/rt/employee.json");
+ private static final File FILE_JSON_INVALID = new File("org/eclipse/persistence/testing/jaxb/beanvalidation/rt/employeeInvalid.json");
+ private static final Class[] EMPLOYEE = new Class[]{Employee.class};
+ private static final boolean DEBUG = true;
+
+ private boolean toggle = true; // Value is sensitive to the order of methods in testBeanValidation() method.
+ private ValidatorFactory preferredValidatorFactory;
+ private JAXBMarshaller marshallerValidOn;
+ private JAXBMarshaller marshallerValidOff;
+ private JAXBUnmarshaller unmarshallerValidOn;
+ private JAXBUnmarshaller unmarshallerValidOff;
+ private Employee employeeValid = new Employee()
+ .withId(0xCAFEBABE)
+ .withAge(15)
+ .withPersonalName("Richard")
+ .withPhoneNumber("(420)287-4422")
+ .withDepartment(Department.JavaEE)
+ .withDrivingLicense(new DrivingLicense(3326, new GregorianCalendar(2029, 12, 31).getTime()));
+ private Employee employeeInvalid = new Employee()
+ .withAge(15)
+ .withPersonalName("Wo")
+ .withPhoneNumber("287-4422")
+ .withDrivingLicense(new DrivingLicense(1234567, new GregorianCalendar(2010, 5, 20).getTime()));
+ private AbstractSequentialList<String> violationMessages = new LinkedList<String>(){ // Order is good just for debug. The CVs themselves aren't ordered.
+ {
+ add("may not be null"); // id
+ add("must be greater than or equal to 18"); // age
+ add("size must be between 3 and 15"); // personalName
+ add("must match \"\\(\\d{3}\\)\\d{3}-\\d{4}\""); // phoneNumber
+ add("may not be null"); // department
+ add("must be in the future"); // drivingLicense.validThrough
+ add("numeric value out of bounds (<6 digits>.<0 digits> expected)"); // drivingLicense.id
+ }};
+ private AbstractSequentialList<String> violationMessagesWithoutGroup = new LinkedList<String>(){
+ {
+ add("may not be null"); // id
+ add("size must be between 3 and 15"); // personalName
+ add("must match \"\\(\\d{3}\\)\\d{3}-\\d{4}\""); // phoneNumber
+ add("may not be null"); // department
+ }};
+
+
+ public void testBeanValidation() throws Exception{
+ validEmployee(FILE_VALID);
+ invalidEmployee(FILE_INVALID);
+ switchToJson();
+ validEmployee(FILE_JSON_VALID);
+ invalidEmployee(FILE_JSON_INVALID);
+ }
+
+ private void validEmployee(File file) throws Exception {
+
+ toggleDriversGroupOnOff();
+
+ marshallerValidOn.marshal(employeeValid, file);
+ assertTrue(marshallerValidOn.getConstraintViolations().isEmpty());
+
+ Employee employeeUnm = (Employee) unmarshallerValidOn.unmarshal(file);
+ assertTrue(unmarshallerValidOn.getConstraintViolations().isEmpty());
+
+ assertEquals(employeeValid, employeeUnm);
+ }
+
+ private void invalidEmployee(File fileInvalid) throws Exception {
+
+ JAXBException exception = null;
+ toggleDriversGroupOnOff();
+
+ /* Marshal w/ validation - doesn't pass (we want to check that). */
+ try {
+ marshallerValidOn.marshal(employeeInvalid, fileInvalid);
+ } catch (JAXBException e) {
+ exception = e;
+ }
+ assertNotNull(exception);
+ assertEquals(String.valueOf(BeanValidationException.CONSTRAINT_VIOLATION), exception.getErrorCode());
+ if (DEBUG) System.out.println(exception.getMessage());
+ checkValidationMessages(marshallerValidOn.getConstraintViolations(), violationMessages);
+
+ /* Marshal w/o validation - creates file for the next part of the test. */
+ marshallerValidOff.marshal(employeeInvalid, fileInvalid);
+ Set<? extends ConstraintViolation<?>> marshalCV = marshallerValidOff.getConstraintViolations();
+ assertTrue(marshalCV.isEmpty());
+
+ /* Unmarshal w/ validation - doesn't pass (we want to check that). */
+ exception = null;
+ try { unmarshallerValidOn.unmarshal(fileInvalid); }
+ catch (JAXBException e) { exception = e; }
+ assertNotNull(exception);
+ assertEquals(String.valueOf(BeanValidationException.CONSTRAINT_VIOLATION), exception.getErrorCode());
+ if (DEBUG) System.out.println(exception.getMessage());
+ checkValidationMessages(unmarshallerValidOn.getConstraintViolations(), violationMessages);
+
+ /* Unmarshal w/ validation AND no groups - doesn't pass (we want to check that). */
+ toggleDriversGroupOnOff();
+ exception = null;
+
+ try { unmarshallerValidOn.unmarshal(fileInvalid); }
+ catch (JAXBException e) { exception = e; }
+ assertNotNull(exception);
+ assertEquals(String.valueOf(BeanValidationException.CONSTRAINT_VIOLATION), exception.getErrorCode());
+ if (DEBUG) System.out.println(exception.getMessage());
+ checkValidationMessages(unmarshallerValidOn.getConstraintViolations(), violationMessagesWithoutGroup);
+ toggleDriversGroupOnOff();
+
+ /* Unmarshal w/o validation - testing that invalid objects are correctly unmarshalled when validation is NONE. */
+ Employee employeeUnm = (Employee) unmarshallerValidOff.unmarshal(fileInvalid);
+ assertTrue(unmarshallerValidOff.getConstraintViolations().isEmpty());
+
+ /* Final check that the validation feature did not affect original behavior of JAXB. */
+ assertEquals(employeeInvalid, employeeUnm);
+ }
+
+ private void checkValidationMessages(Set<? extends ConstraintViolation<?>> constraintViolations, List<String> expectedMessages) {
+ List<String> violationMessages = new ArrayList<String>();
+ for (ConstraintViolation<?> cv : constraintViolations)
+ violationMessages.add(cv.getMessage());
+ assertSame(expectedMessages.size(), violationMessages.size());
+ assertTrue(violationMessages.containsAll(expectedMessages));
+ }
+
+ private void toggleDriversGroupOnOff() throws PropertyException {
+ if (toggle ^= true) {
+ marshallerValidOn.setProperty(MarshallerProperties.BEAN_VALIDATION_GROUPS, new Class[]{Default.class, Drivers.class});
+ unmarshallerValidOn.setProperty(MarshallerProperties.BEAN_VALIDATION_GROUPS, new Class[] { Default.class, Drivers.class });
+ } else {
+ marshallerValidOn.setProperty(MarshallerProperties.BEAN_VALIDATION_GROUPS, new Class[0]);
+ unmarshallerValidOn.setProperty(MarshallerProperties.BEAN_VALIDATION_GROUPS, new Class[0]);
+ }
+ }
+
+ private void switchToJson() throws PropertyException {
+ marshallerValidOn.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
+ marshallerValidOn.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true);
+ unmarshallerValidOn.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
+ unmarshallerValidOn.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true);
+ marshallerValidOff.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
+ marshallerValidOff.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true);
+ unmarshallerValidOff.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
+ unmarshallerValidOff.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ preferredValidatorFactory = Validation.buildDefaultValidatorFactory();
+
+ JAXBContext ctx = JAXBContextFactory.createContext(EMPLOYEE, null);
+ marshallerValidOn = (JAXBMarshaller) ctx.createMarshaller();
+ marshallerValidOn.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ marshallerValidOff = (JAXBMarshaller) ctx.createMarshaller();
+ marshallerValidOff.setProperty(UnmarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE); // tests setting the property through mar
+ marshallerValidOff.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+
+ JAXBContext ctxValidationOff = JAXBContextFactory.createContext(EMPLOYEE,
+ new HashMap<String, Object>(){{
+ put(JAXBContextProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
+ put(JAXBContextProperties.BEAN_VALIDATION_FACTORY, preferredValidatorFactory);}});
+ unmarshallerValidOn = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
+ unmarshallerValidOn.setProperty(UnmarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.CALLBACK); // tests setting the property through unm
+ unmarshallerValidOff = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ assertTrue(FILE_VALID.delete());
+ assertTrue(FILE_INVALID.delete());
+ assertTrue(FILE_JSON_VALID.delete());
+ assertTrue(FILE_JSON_INVALID.delete());
+ marshallerValidOn = marshallerValidOff = null;
+ unmarshallerValidOn = unmarshallerValidOff = null;
+ employeeValid = employeeInvalid = null;
+ violationMessages = null;
+ preferredValidatorFactory = null;
+ }
+
+
+}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/ContentComparator.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/ContentComparator.java
new file mode 100644
index 0000000..a56a5c0
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/ContentComparator.java
@@ -0,0 +1,157 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author jungi
+ */
+public final class ContentComparator {
+
+ private static final Logger LOGGER = Logger.getLogger(ContentComparator.class.getName());
+
+ /** Creates a new instance of ContentComparator */
+ private ContentComparator() {
+ }
+
+ /**
+ * Compares the content of two xml files. Ignores whitespaces.
+ *
+ *@param f1 usually golden file
+ *@param f2 other file which we want to compare against golden file (or any other file)
+ *@return true iff both files have the same content except of whitespaces
+ */
+ public static boolean equalsXML(File f1, File f2) {
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document d1 = db.parse(f1);
+ Document d2 = db.parse(f2);
+ return compare(d1.getDocumentElement(), d2.getDocumentElement());
+ } catch (ParserConfigurationException e) {
+ LOGGER.log(Level.WARNING, "Exception from test - comparing XML files", e); //NOI18N
+ } catch (SAXException e) {
+ LOGGER.log(Level.WARNING, "Exception from test - comparing XML files", e); //NOI18N
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Exception from test - comparing XML files", e); //NOI18N
+ }
+ return false;
+ }
+
+ private static boolean compare(Node n1, Node n2) {
+ List<Node> l1 = new LinkedList<Node>();
+ List<Node> l2 = new LinkedList<Node>();
+ l1.add(n1);
+ l2.add(n2);
+ while (!l1.isEmpty() && !l2.isEmpty()) {
+ Node m1 = l1.remove(0);
+ Node m2 = l2.remove(0);
+ //check basic things - node name, value, attributes - if they're OK, we can continue
+ if (sameNode(m1, m2)) {
+ //now compare children
+ NodeList nl = m1.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node e = nl.item(i);
+ if (e.getNodeType() == Node.TEXT_NODE) {
+ //ignore empty places
+ if (e.getNodeValue().trim().equals("")) {
+ continue;
+ }
+ }
+ l1.add(nl.item(i));
+ }
+ nl = m2.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node e = nl.item(i);
+ if (e.getNodeType() == Node.TEXT_NODE) {
+ //ignore empty places
+ if (e.getNodeValue().trim().equals("")) {
+ continue;
+ }
+ }
+ l2.add(nl.item(i));
+ }
+ } else {
+ //nodes are not equals - print some info
+ LOGGER.warning("================================================"); //NOI18N
+ LOGGER.warning("m1: " + m1.getNodeName() + "; \'" + m1.getNodeValue() + "\'"); //NOI18N
+ LOGGER.warning("m2: " + m2.getNodeName() + "; \'" + m2.getNodeValue() + "\'"); //NOI18N
+ LOGGER.warning("================================================"); //NOI18N
+ return false;
+ }
+ }
+ return true;
+ }
+
+ //attrs, name, value
+ private static boolean sameNode(Node n1, Node n2) {
+ //check node name
+ if (!n1.getNodeName().equals(n2.getNodeName())) {
+ LOGGER.warning("================================================"); //NOI18N
+ LOGGER.warning("Expected node: " + n1.getNodeName() + ", got: " + n2.getNodeName()); //NOI18N
+ LOGGER.warning("================================================"); //NOI18N
+ return false;
+ }
+ //check node value
+ if (!((n1.getNodeValue() != null)
+ ? n1.getNodeValue().equals(n2.getNodeValue())
+ : (n2.getNodeValue() == null))) {
+ LOGGER.warning("================================================"); //NOI18N
+ LOGGER.warning("Expected node value: " + n1.getNodeValue() + ", got: " + n2.getNodeValue()); //NOI18N
+ LOGGER.warning("================================================"); //NOI18N
+ return false;
+ }
+ //check node attributes
+ NamedNodeMap nnm1 = n1.getAttributes();
+ NamedNodeMap nnm2 = n2.getAttributes();
+ if ((nnm1 == null && nnm2 != null)
+ || (nnm1 != null && nnm2 == null)) {
+ return false;
+ }
+ if (nnm1 == null) {
+ return true;
+ }
+ for (int i = 0; i < nnm1.getLength(); i++) {
+ Node x = nnm1.item(i);
+ Node y = nnm2.item(i);
+ if (!(x.getNodeName().equals(y.getNodeName())
+ && x.getNodeValue().equals(y.getNodeValue()))) {
+ //nodes are not equals - print some info
+ LOGGER.warning("================================================"); //NOI18N
+ LOGGER.warning("Expected attribute: " + x.getNodeName() + "=\'" + x.getNodeValue() + "\'," //NOI18N
+ + " got: " + y.getNodeName() + "=\'" + y.getNodeValue() + "\'"); //NOI18N
+ LOGGER.warning("================================================"); //NOI18N
+ return false;
+ }
+ }
+ return true;
+ }
+
+} \ No newline at end of file
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Department.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Department.java
new file mode 100644
index 0000000..5b88bfc
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Department.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+@XmlRootElement
+public enum Department {
+ RDBMS, JavaSE, JavaEE, Sales, Support
+} \ No newline at end of file
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Drivers.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Drivers.java
new file mode 100644
index 0000000..df23867
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Drivers.java
@@ -0,0 +1,21 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom;
+
+/**
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+public interface Drivers {
+
+}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/DrivingLicense.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/DrivingLicense.java
new file mode 100644
index 0000000..f1cd9a1
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/DrivingLicense.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom;
+
+import javax.validation.constraints.Digits;
+import javax.validation.constraints.Future;
+import javax.xml.bind.annotation.XmlAttribute;
+import java.util.Date;
+
+/**
+* @author Marcel Valovy - marcel.valovy@oracle.com
+* @since 2.6
+*/
+public class DrivingLicense {
+
+ @Digits(integer = 6, fraction = 0, groups = Drivers.class)
+ @XmlAttribute
+ int id;
+
+ @Future(groups = Drivers.class)
+ @XmlAttribute
+ Date validThrough;
+
+ public DrivingLicense(){
+ }
+
+ public DrivingLicense(int id, Date validThrough){
+ this.id = id;
+ this.validThrough = validThrough;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ DrivingLicense that = (DrivingLicense) o;
+
+ if (id != that.id) {
+ return false;
+ }
+ if (validThrough != null ? !validThrough.equals(that.validThrough) : that.validThrough != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id;
+ result = 31 * result + (validThrough != null ? validThrough.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "DrivingLicense{" +
+ "id=" + id +
+ ", validThrough=" + validThrough +
+ '}';
+ }
+}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Employee.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Employee.java
new file mode 100644
index 0000000..87a36ef
--- /dev/null
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/beanvalidation/rt_dom/Employee.java
@@ -0,0 +1,146 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6.0 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.beanvalidation.rt_dom;
+
+import javax.validation.Valid;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+@XmlRootElement
+public class Employee {
+
+ @NotNull
+ @XmlAttribute
+ private Integer id;
+
+ @Min(value=18, groups=Drivers.class)
+ @XmlAttribute
+ @NotNull
+ private int age;
+
+ @NotNull
+ @Size(min = 3, max = 15)
+ @XmlElement
+ private String personalName;
+
+ @Pattern(regexp="\\(\\d{3}\\)\\d{3}-\\d{4}")
+ @XmlElement
+ private String phoneNumber;
+
+ @NotNull
+ @XmlElement
+ private Department department;
+
+ @NotNull(groups=Drivers.class)
+ @Valid
+ @XmlElement
+ private DrivingLicense drivingLicense;
+
+ public Employee(){
+ }
+
+ public Employee withId(int id){
+ this.id = id;
+ return this;
+ }
+
+ public Employee withAge(int age){
+ this.age = age;
+ return this;
+ }
+
+ public Employee withPersonalName(String personalName){
+ this.personalName = personalName;
+ return this;
+ }
+
+ public Employee withPhoneNumber(String phoneNumber){
+ this.phoneNumber = phoneNumber;
+ return this;
+ }
+
+ public Employee withDepartment(Department department){
+ this.department = department;
+ return this;
+ }
+
+ public Employee withDrivingLicense(DrivingLicense drivingLicense){
+ this.drivingLicense = drivingLicense;
+ return this;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ Employee employee = (Employee) o;
+
+ if (age != employee.age) {
+ return false;
+ }
+ if (department != employee.department) {
+ return false;
+ }
+ if (drivingLicense != null ? !drivingLicense.equals(employee.drivingLicense) : employee.drivingLicense != null) {
+ return false;
+ }
+ if (id != null ? !id.equals(employee.id) : employee.id != null) {
+ return false;
+ }
+ if (personalName != null ? !personalName.equals(employee.personalName) : employee.personalName != null) {
+ return false;
+ }
+ if (phoneNumber != null ? !phoneNumber.equals(employee.phoneNumber) : employee.phoneNumber != null) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = age;
+ result = 31 * result + (id == null ? 0 : id);
+ result = 31 * result + (personalName != null ? personalName.hashCode() : 0);
+ result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
+ result = 31 * result + (department != null ? department.hashCode() : 0);
+ result = 31 * result + (drivingLicense != null ? drivingLicense.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "Employee{" +
+ "id=" + id +
+ ", age=" + age +
+ ", personalName='" + personalName + '\'' +
+ ", phoneNumber='" + phoneNumber + '\'' +
+ ", department=" + department +
+ ", drivingLicense=" + drivingLicense +
+ '}';
+ }
+} \ No newline at end of file
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/casesensitivity/Customer.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/casesensitivity/Customer.java
index e950eb8..8730b0e 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/casesensitivity/Customer.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/casesensitivity/Customer.java
@@ -52,8 +52,8 @@ public abstract class Customer {
* Bridge for {@link org.eclipse.persistence.testing.jaxb.casesensitivity.correctCase.CustomerImpl#equals(Object)} and
* {@link org.eclipse.persistence.testing.jaxb.casesensitivity.otherCase.CustomerImpl#equals(Object)}
*
- * @param o CustomerImpl object.
- * @return true if the CustomerImpl classes' attributes match the same values.
+ * @param o Employee object.
+ * @return true if the Employee classes' attributes match the same values.
*/
public boolean equals(Object o) {
if (this == o) return true;
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmlnametransformer/NameTransformerExceptionTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmlnametransformer/NameTransformerExceptionTestCases.java
index d929e75..9b1b835 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmlnametransformer/NameTransformerExceptionTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmlnametransformer/NameTransformerExceptionTestCases.java
@@ -57,13 +57,13 @@ public class NameTransformerExceptionTestCases extends OXTestCase{
public void testExceptionDuringTransform(){
Type[] types = new Type[1];
types[0] = Employee.class;
- try{
- JAXBContext jaxbContext = JAXBContextFactory.createContext(types, getPropertiesWithException(), Thread.currentThread().getContextClassLoader());
- } catch (javax.xml.bind.JAXBException e) {
- e.printStackTrace();
-
- Exception linkedException = (Exception) e.getLinkedException();
- Exception nestedExcpetion = (Exception) e.getCause();
+ try{
+ JAXBContext jaxbContext = JAXBContextFactory.createContext(types, getPropertiesWithException(), Thread.currentThread().getContextClassLoader());
+ } catch (javax.xml.bind.JAXBException e) {
+// e.printStackTrace();
+
+ Exception linkedException = (Exception) e.getLinkedException();
+ Exception nestedExcpetion = (Exception) e.getCause();
assertTrue(nestedExcpetion instanceof JAXBException);
assertEquals(JAXBException.EXCEPTION_DURING_NAME_TRANSFORMATION,((JAXBException)nestedExcpetion).getErrorCode());
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/emptyroot/EmptyNullMarshalUnmarshalTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/emptyroot/EmptyNullMarshalUnmarshalTestCases.java
index b19e5d1..4516832 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/emptyroot/EmptyNullMarshalUnmarshalTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/emptyroot/EmptyNullMarshalUnmarshalTestCases.java
@@ -14,24 +14,24 @@ package org.eclipse.persistence.testing.jaxb.json.emptyroot;
import java.io.StringReader;
import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.Marshaller;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
-import javax.xml.namespace.QName;
-import javax.xml.transform.stream.StreamSource;
-
-import org.eclipse.persistence.jaxb.JAXBContext;
-import org.eclipse.persistence.jaxb.JAXBContextFactory;
-import org.eclipse.persistence.jaxb.JAXBContextProperties;
-import org.eclipse.persistence.jaxb.JAXBMarshaller;
-import org.eclipse.persistence.jaxb.JAXBUnmarshaller;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.eclipse.persistence.jaxb.UnmarshallerProperties;
-import org.eclipse.persistence.oxm.XMLConstants;
+import javax.xml.namespace.QName;
+import javax.xml.transform.stream.StreamSource;
+
+import org.eclipse.persistence.jaxb.BeanValidationMode;
+import org.eclipse.persistence.jaxb.JAXBContext;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
+import org.eclipse.persistence.jaxb.JAXBContextProperties;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.eclipse.persistence.jaxb.UnmarshallerProperties;
+import org.eclipse.persistence.oxm.XMLConstants;
import org.eclipse.persistence.testing.oxm.OXTestCase;
public class EmptyNullMarshalUnmarshalTestCases extends OXTestCase{
@@ -43,111 +43,112 @@ public class EmptyNullMarshalUnmarshalTestCases extends OXTestCase{
public EmptyNullMarshalUnmarshalTestCases(String name) throws Exception {
super(name);
}
-
- public void setUp() throws Exception{
- super.setUp();
- HashMap props = new HashMap();
- props.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
-
- ctx = (JAXBContext) JAXBContextFactory.createContext(new Class[]{Root.class}, props);
- ctxNoRoot = (JAXBContext) JAXBContextFactory.createContext(new Class[]{RootNoXmlRootElement.class}, props);
- }
-
- public void testJAXBElementNullValueIncludeRootTrue() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, null );
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- m.marshal(obj, sw);
+
+ public void setUp() throws Exception{
+ super.setUp();
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
+ props.put(JAXBContextProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
+
+ ctx = (JAXBContext) JAXBContextFactory.createContext(new Class[]{Root.class}, props);
+ ctxNoRoot = (JAXBContext) JAXBContextFactory.createContext(new Class[]{RootNoXmlRootElement.class}, props);
+ }
+
+ public void testJAXBElementNullValueIncludeRootTrue() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, null );
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
+ m.marshal(obj, sw);
compareStrings("testJAXBElementNullValueIncludeRootTrue", EMPTY_JSON, sw.getBuffer().toString());
}
-
- public void testJAXBElementNullValueIncludeRootFalse() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, null );
-
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
+
+ public void testJAXBElementNullValueIncludeRootFalse() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, null );
+
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(obj, sw);
compareStrings("testJAXBElementNullValueIncludeRootFalse", EMPTY_JSON, sw.getBuffer().toString());
}
-
- public void testJAXBElementEmptyValueIncludeRootTrue() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new Root() );
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- m.marshal(obj, sw);
+
+ public void testJAXBElementEmptyValueIncludeRootTrue() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new Root() );
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
+ m.marshal(obj, sw);
String expectedString = "{\"type\":\"root\"}";
compareStrings("testJAXBElementEmptyValueIncludeRootTrue", expectedString, sw.getBuffer().toString());
}
-
- public void testJAXBElementEmptyValueIncludeRootFalse() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new Root() );
-
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
+
+ public void testJAXBElementEmptyValueIncludeRootFalse() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new Root() );
+
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(obj, sw);
String expectedString = "{\"type\":\"root\"}";
compareStrings("testJAXBElementEmptyValueIncludeRootFalse", expectedString, sw.getBuffer().toString());
}
-
- public void testJAXBElementEmptyValueNoRootIncludeRootTrue() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new RootNoXmlRootElement() );
- Marshaller m = ctxNoRoot.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- m.marshal(obj, sw);
+
+ public void testJAXBElementEmptyValueNoRootIncludeRootTrue() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new RootNoXmlRootElement() );
+ Marshaller m = ctxNoRoot.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
+ m.marshal(obj, sw);
String expectedString = "{\"type\":\"rootNoXmlRootElement\"}";
compareStrings("testJAXBElementEmptyValueNoRootIncludeRootTrue", expectedString, sw.getBuffer().toString());
}
-
- public void testJAXBElementEmptyValueNoRootIncludeRootFalse() throws Exception{
- StringWriter sw = new StringWriter();
- JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new RootNoXmlRootElement() );
-
- Marshaller m = ctxNoRoot.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
+
+ public void testJAXBElementEmptyValueNoRootIncludeRootFalse() throws Exception{
+ StringWriter sw = new StringWriter();
+ JAXBElement obj = new JAXBElement<Object>(new QName(XMLConstants.EMPTY_STRING),Object.class, new RootNoXmlRootElement() );
+
+ Marshaller m = ctxNoRoot.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(obj, sw);
String expectedString = "{\"type\":\"rootNoXmlRootElement\"}";
compareStrings("testJAXBElementEmptyValueNoRootIncludeRootFalse", expectedString, sw.getBuffer().toString());
}
-
- public void testEmptyIncludeRootTrue() throws Exception{
- StringWriter sw = new StringWriter();
- Object obj = new Root();
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- m.marshal(obj, sw);
+
+ public void testEmptyIncludeRootTrue() throws Exception{
+ StringWriter sw = new StringWriter();
+ Object obj = new Root();
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
+ m.marshal(obj, sw);
String expected = "{\"root\":{}}";
compareStrings("testEmptyIncludeRootTrue", expected, sw.getBuffer().toString());
}
-
- public void testEmptyIncludeRootFalse() throws Exception{
- StringWriter sw = new StringWriter();
- Object obj = new Root();
- Marshaller m = ctx.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
- m.marshal(obj, sw);
+
+ public void testEmptyIncludeRootFalse() throws Exception{
+ StringWriter sw = new StringWriter();
+ Object obj = new Root();
+ Marshaller m = ctx.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
+ m.marshal(obj, sw);
compareStrings("testEmptyIncludeRootFalse", EMPTY_JSON, sw.getBuffer().toString());
}
-
- public void testEmptyNoRootIncludeRootTrue() throws Exception{
- StringWriter sw = new StringWriter();
- Object obj = new RootNoXmlRootElement();
- Marshaller m = ctxNoRoot.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
- m.marshal(obj, sw);
+
+ public void testEmptyNoRootIncludeRootTrue() throws Exception{
+ StringWriter sw = new StringWriter();
+ Object obj = new RootNoXmlRootElement();
+ Marshaller m = ctxNoRoot.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
+ m.marshal(obj, sw);
compareStrings("testEmptyNoRootIncludeRootTrue", EMPTY_JSON, sw.getBuffer().toString());
}
-
- public void testEmptyNoRootIncludeRootFalse() throws Exception{
- StringWriter sw = new StringWriter();
- Object obj = new RootNoXmlRootElement();
- Marshaller m = ctxNoRoot.createMarshaller();
- m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
- m.marshal(obj, sw);
+
+ public void testEmptyNoRootIncludeRootFalse() throws Exception{
+ StringWriter sw = new StringWriter();
+ Object obj = new RootNoXmlRootElement();
+ Marshaller m = ctxNoRoot.createMarshaller();
+ m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
+ m.marshal(obj, sw);
compareStrings("testEmptyNoRootIncludeRootFalse", EMPTY_JSON, sw.getBuffer().toString());
}
@@ -200,24 +201,24 @@ public class EmptyNullMarshalUnmarshalTestCases extends OXTestCase{
Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, true);
StringReader reader = new StringReader("{}");
- Object o = unmarshaller.unmarshal(new StreamSource(reader), Root.class);
- assertTrue (o instanceof JAXBElement);
- JAXBElement controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, null );
- compareJAXBElementObjects(controlObj, (JAXBElement)o);
- }
-
- public void testUnmarshalClassIncludeRootFalse() throws Exception{
+ Object o = unmarshaller.unmarshal(new StreamSource(reader), Root.class);
+ assertTrue (o instanceof JAXBElement);
+ JAXBElement controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, null );
+ compareJAXBElementObjects(controlObj, (JAXBElement)o);
+ }
+
+ public void testUnmarshalClassIncludeRootFalse() throws Exception{
Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
StringReader reader = new StringReader("{}");
Object o = unmarshaller.unmarshal(new StreamSource(reader), Root.class);
-
- assertTrue (o instanceof JAXBElement);
- JAXBElement controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, new Root() );
- compareJAXBElementObjects(controlObj, (JAXBElement)o);
- }
-
-
+
+ assertTrue (o instanceof JAXBElement);
+ JAXBElement controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, new Root() );
+ compareJAXBElementObjects(controlObj, (JAXBElement)o);
+ }
+
+
public void testUnmarshalNoRootTypeAttrIncludeRootFalse() throws Exception{
Unmarshaller unmarshaller = ctxNoRoot.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
@@ -245,13 +246,13 @@ public class EmptyNullMarshalUnmarshalTestCases extends OXTestCase{
JAXBElement controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, new Root() );
compareJAXBElementObjects(controlObj, (JAXBElement)o);
- Object o2 = unmarshaller.unmarshal(new StreamSource(reader2));
- assertTrue (o instanceof JAXBElement);
- controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, new Root() );
- compareJAXBElementObjects(controlObj, (JAXBElement)o);
-
- }
-
+ Object o2 = unmarshaller.unmarshal(new StreamSource(reader2));
+ assertTrue (o instanceof JAXBElement);
+ controlObj = new JAXBElement(new QName(XMLConstants.EMPTY_STRING),Root.class, new Root() );
+ compareJAXBElementObjects(controlObj, (JAXBElement)o);
+
+ }
+
public void testUnmarshalEmptyListIncludeRootTrue() throws Exception{
Unmarshaller unmarshaller = ctx.createUnmarshaller();
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsNonRootTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsNonRootTestCases.java
index dc56a8f..6208c4b 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsNonRootTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/JAXBListOfObjectsNonRootTestCases.java
@@ -1,8 +1,8 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
@@ -18,12 +18,13 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Stack;
-import java.util.TreeSet;
-import java.util.Vector;
+import java.util.Hashtable;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.TreeSet;
+import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.bind.JAXBElement;
@@ -210,12 +211,12 @@ public class JAXBListOfObjectsNonRootTestCases extends JAXBListOfObjectsNoJSONTe
protected String getNoXsiTypeControlResourceName() {
return XML_RESOURCE_NO_XSI_TYPE;
}
-
-
- public void testTypeToSchemaTypeMap(){
- HashMap<Type, javax.xml.namespace.QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
- int mapSize = typesMap.size();
- assertEquals(2, mapSize);
- }
+
+
+ public void testTypeToSchemaTypeMap(){
+ Map<Type, QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
+ int mapSize = typesMap.size();
+ assertEquals(2, mapSize);
+ }
}
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsNamespaceTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsNamespaceTestCases.java
index 9c49b1e..932ce9e 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsNamespaceTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsNamespaceTestCases.java
@@ -153,13 +153,13 @@ public class JAXBMultipleMapsNamespaceTestCases extends JAXBListOfObjectsNoJSONT
fail("An error occurred during getProperties");
}
return null;
- }
-
- public void testTypeToSchemaTypeMap(){
- HashMap<Type, javax.xml.namespace.QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
- int mapSize = typesMap.size();
- assertEquals(7, mapSize);
-
+ }
+
+ public void testTypeToSchemaTypeMap(){
+ Map<Type, javax.xml.namespace.QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
+ int mapSize = typesMap.size();
+ assertEquals(7, mapSize);
+
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[0]));
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[1]));
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[2]));
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsTestCases.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsTestCases.java
index 147caa1..034c56d 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsTestCases.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/listofobjects/externalizedmetadata/JAXBMultipleMapsTestCases.java
@@ -124,13 +124,13 @@ public class JAXBMultipleMapsTestCases extends JAXBListOfObjectsTestCases {
protected String getNoXsiTypeControlResourceName() {
return XML_RESOURCE;
- }
-
- public void testTypeToSchemaTypeMap(){
- HashMap<Type, javax.xml.namespace.QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
- int mapSize = typesMap.size();
- assertEquals(7, mapSize);
-
+ }
+
+ public void testTypeToSchemaTypeMap(){
+ Map<Type, javax.xml.namespace.QName> typesMap = ((org.eclipse.persistence.jaxb.JAXBContext)jaxbContext).getTypeToSchemaType();
+ int mapSize = typesMap.size();
+ assertEquals(7, mapSize);
+
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[0]));
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[1]));
assertNotNull("Type was not found in TypeToSchemaType map.", typesMap.get(types[2]));
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/SchemaGenTestSuite.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/SchemaGenTestSuite.java
index 489ccf3..87ebdd9 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/SchemaGenTestSuite.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/SchemaGenTestSuite.java
@@ -37,12 +37,13 @@ import junit.framework.Test;
import junit.framework.TestSuite;
public class SchemaGenTestSuite extends TestSuite {
- public static Test suite() {
- TestSuite suite = new TestSuite("JAXB 2.0 Schema Generation Test Suite");
- suite.addTestSuite(SchemaGenEmployeeTestCases.class);
- suite.addTestSuite(SchemaGenXMLTypeTestCases.class);
- suite.addTestSuite(SchemaGenXMLRootElementTestCases.class);
- suite.addTestSuite(DeploymentXMLSchemaGenTestCases.class);
+ public static Test suite() {
+ TestSuite suite = new TestSuite("JAXB 2.0 Schema Generation Test Suite");
+ suite.addTestSuite(SchemaGenEmployeeTestCases.class);
+ suite.addTestSuite(SchemaGenXmlPathTestCases.class); // added twice, delete this one, should be at the end
+ suite.addTestSuite(SchemaGenXMLTypeTestCases.class);
+ suite.addTestSuite(SchemaGenXMLRootElementTestCases.class);
+ suite.addTestSuite(DeploymentXMLSchemaGenTestCases.class);
suite.addTestSuite(SchemaGenXmlElementWrapperTestCases.class);
suite.addTestSuite(SchemaGenXmlElementRefByteArrayTestCases.class);
suite.addTestSuite(SchemaGenXmlElementRefTestCases.class);
diff --git a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/Employee.java b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/Employee.java
index 5d799b9..c2e2165 100644
--- a/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/Employee.java
+++ b/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/Employee.java
@@ -9,28 +9,34 @@
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
- ******************************************************************************/
-package org.eclipse.persistence.testing.jaxb.schemagen.employee;
-
-import javax.xml.bind.annotation.*;
-
-@XmlRootElement(name="employee-data")
+ ******************************************************************************/
+package org.eclipse.persistence.testing.jaxb.schemagen.employee;
+
+import javax.validation.Valid;
+import javax.validation.constraints.DecimalMax;
+import javax.validation.constraints.Size;
+import javax.xml.bind.annotation.*;
+
+@XmlRootElement(name="employee-data")
@XmlType(name = "employee-type", propOrder = {"firstName", "birthday", "id", "age", "lastName", "address", "department",
"startTime", "phoneNumbers", "responsibilities", "peeps"})
-@XmlAccessorType(XmlAccessType.FIELD)
-public class Employee
-{
- @XmlAttribute(name="id", required=true)
- public int id;
-
- @XmlElement(required = true)
- public String firstName;
-
- public String lastName;
-
- @XmlMixed
- public Address address;
-
+@XmlAccessorType(XmlAccessType.FIELD)
+public class Employee
+{
+ @DecimalMax(value="10")
+ @XmlAttribute(name="id", required=true)
+ public int id;
+
+ @Size(min=2, max=10)
+ @XmlElement(required = true)
+ public String firstName;
+
+ public String lastName;
+
+ @Valid
+ @XmlMixed
+ public Address address;
+
@XmlAttribute
public Department department;
diff --git a/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.properties b/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.properties
index b509397..a951df0 100644
--- a/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.properties
+++ b/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.properties
@@ -23,16 +23,19 @@ asm=org.eclipse.persistence.asm
dynamic.jar.prefix=eclipselink-moxy-dynamicxjc
# for dependencies found it trunk/plugins (global plugins) dir
-persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
-persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
-unsigned.persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
-jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
-jaxb-api.src.jar=javax.xml.bind.source_2.2.0.v201005080402.jar
-jaxb-xjc.jar=com.sun.tools.xjc_2.2.0.jar
-jaxb-impl.jar=com.sun.xml.bind_2.2.0.v201004141950.jar
-stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
-activation.jar=javax.activation_1.1.0.v201108011116.jar
-mail.jar=javax.mail_1.4.0.v201005080615.jar
+persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
+persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
+unsigned.persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
+#jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
+#jaxb-api.src.jar=javax.xml.bind.source_2.2.0.v201005080402.jar
+#jaxb-xjc.jar=com.sun.tools.xjc_2.2.0.jar
+#jaxb-impl.jar=com.sun.xml.bind_2.2.0.v201004141950.jar
+jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
+jaxb-xjc.jar=jaxb-xjc_2.2.11.v201406210428.jar
+jaxb-core.jar=jaxb-core_2.2.11.v201406210428.jar
+stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
+activation.jar=javax.activation_1.1.0.v201108011116.jar
+mail.jar=javax.mail_1.4.0.v201005080615.jar
commonj.sdo.jar=commonj.sdo_2.1.1.v201112051852.jar
commonj.sdo.src.zip=commonj.sdo.source_2.1.1.v201112051852.jar
wsdl.jar=javax.wsdl_1.6.2.v201012040545.jar
diff --git a/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.xml b/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.xml
index 80675d6..951632b 100644
--- a/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.xml
+++ b/moxy/org.eclipse.persistence.moxy.dynamicxjc/antbuild.xml
@@ -106,7 +106,7 @@
<property name="moxy.lib" value="${dynamic.2.common.plugins.dir}/org.eclipse.persistence.moxy_${version.string}.jar"/>
<property name="jaxb-api.lib" value="${dynamic.2.common.plugins.dir}/${jaxb-api.jar}"/>
<property name="jaxb-xjc.lib" value="${dynamic.2.common.plugins.dir}/${jaxb-xjc.jar}"/>
- <property name="jaxb-impl.lib" value="${dynamic.2.common.plugins.dir}/${jaxb-impl.jar}"/>
+ <property name="jaxb-core.lib" value="${dynamic.2.common.plugins.dir}/${jaxb-core.jar}"/>
<!-- dependency tests -->
<available file="${core.lib}" property="core.bundle.exist"/>
@@ -117,15 +117,15 @@
<fail message="Cannot find jaxb-api: '${jaxb-api.lib}'" unless="jaxb-api.bundle.exist"/>
<available file="${jaxb-xjc.lib}" property="jaxb-xjc.bundle.exist"/>
<fail message="Cannot find jaxb-xjc: '${jaxb-xjc.lib}'" unless="jaxb-xjc.bundle.exist"/>
- <available file="${jaxb-impl.lib}" property="jaxb-impl.bundle.exist"/>
- <fail message="Cannot find jaxb-impl: '${jaxb-impl.lib}'" unless="jaxb-impl.bundle.exist"/>
+ <available file="${jaxb-core.lib}" property="jaxb-core.bundle.exist"/>
+ <fail message="Cannot find jaxb-core: '${jaxb-core.lib}'" unless="jaxb-core.bundle.exist"/>
<!-- Set Compile Path-->
<path id="dynamic.compile.path">
<pathelement path="${jaxb-api.lib}"/>
<pathelement path="${dynamic.2.common.plugins.dir}/${asm}"/>
<pathelement path="${jaxb-xjc.lib}"/>
- <pathelement path="${jaxb-impl.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
<pathelement path="${core.lib}"/>
<pathelement path="${moxy.lib}"/>
<fileset
diff --git a/moxy/org.eclipse.persistence.moxy/META-INF/MANIFEST.MF b/moxy/org.eclipse.persistence.moxy/META-INF/MANIFEST.MF
index 3aefc91..2ffc750 100644
--- a/moxy/org.eclipse.persistence.moxy/META-INF/MANIFEST.MF
+++ b/moxy/org.eclipse.persistence.moxy/META-INF/MANIFEST.MF
@@ -15,15 +15,26 @@ Export-Package: org.eclipse.persistence.internal.jaxb;version="2.6.0",
Bundle-Name: EclipseLink MOXy
Created-By: 1.6.0_21 (Sun Microsystems Inc.)
HK2-Bundle-Name: org.eclipse.persistence:org.eclipse.persistence.moxy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: org.eclipse.persistence.core;bundle-version="2.6.0";visibility:=reexport,
org.eclipse.persistence.asm;bundle-version="5.0.1";resolution:=optional
Bundle-Vendor: Eclipse.org - EclipseLink Project
Bundle-Version: 2.6.0.qualifier
Bundle-ManifestVersion: 2
-Import-Package: com.sun.xml.bind;resolution:=optional,
- com.sun.xml.bind.annotation;resolution:=optional,
+Import-Package: com.sun.xml.bind,
+ com.sun.xml.bind.annotation,
+ com.sun.xml.bind.api,
+ com.sun.xml.bind.api.impl,
javax.activation;resolution:=optional,
+ javax.validation;resolution:=optional;version="1.1.0",
+ javax.validation.constraints;resolution:=optional;version="1.1.0",
+ javax.validation.groups;resolution:=optional;version="1.1.0",
+ com.sun.codemodel,
+ com.sun.xml.xsom,
+ com.sun.xml.xsom.impl,
+ com.sun.xml.xsom.impl.parser,
+ com.sun.tools.xjc,
+ com.sun.tools.xjc.model,
+ com.sun.tools.xjc.outline,
javax.json;resolution:=optional,
javax.json.stream;resolution:=optional,
javax.ws.rs;resolution:=optional,
diff --git a/moxy/org.eclipse.persistence.moxy/antbuild.properties b/moxy/org.eclipse.persistence.moxy/antbuild.properties
index 7b3e333..0713c9d 100644
--- a/moxy/org.eclipse.persistence.moxy/antbuild.properties
+++ b/moxy/org.eclipse.persistence.moxy/antbuild.properties
@@ -23,25 +23,27 @@ asm=org.eclipse.persistence.asm
# for dependencies found it trunk/plugins (global plugins) dir
persistence20.jar=javax.persistence_2.0.6.v201308211412.jar
-persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
-unsigned.persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
-jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
-jaxb-api.src.jar=javax.xml.bind.source_2.2.0.v201005080402.jar
-jaxb-xjc.jar=com.sun.tools.xjc_2.2.0.jar
-jaxb-impl.jar=com.sun.xml.bind_2.2.0.v201004141950.jar
-stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
-activation.jar=javax.activation_1.1.0.v201108011116.jar
-mail.jar=javax.mail_1.4.0.v201005080615.jar
-commonj.sdo.jar=commonj.sdo_2.1.1.v201112051852.jar
-commonj.sdo.src.zip=commonj.sdo.source_2.1.1.v201112051852.jar
-wsdl.jar=javax.wsdl_1.6.2.v201012040545.jar
+persistence10.jar=javax.persistence_1.0.0.v200905011740.jar
+unsigned.persistence10.jar=javax.persistence_unsigned_for_testing_1.0.0.jar
+jaxb-api.jar=javax.xml.bind_2.2.0.v201105210648.jar
+jaxb-xjc.jar=jaxb-xjc_2.2.11.v201406210428.jar
+jaxb-core.jar=jaxb-core_2.2.11.v201406210428.jar
+jaxb-impl.jar=com.sun.xml.bind_2.2.11.v201406210428.jar
+stax_api.jar=javax.xml.stream_1.0.1.v201004272200.jar
+activation.jar=javax.activation_1.1.0.v201108011116.jar
+mail.jar=javax.mail_1.4.0.v201005080615.jar
+javax.validation.jar=javax.validation_1.1.0.v201304101302.jar
+javax.validation.src.jar=javax.validation_1.1.0.Final-sources.jar
+commonj.sdo.jar=commonj.sdo_2.1.1.v201112051852.jar
+commonj.sdo.src.zip=commonj.sdo.source_2.1.1.v201112051852.jar
+wsdl.jar=javax.wsdl_1.6.2.v201012040545.jar
resource.jar=javax.resource_1.6.0.v201204270900.jar
ejb3.jar=javax.ejb_3.0.0.v200906010428.jar
-jms.jar=javax.jms_1.1.0.v200906010428.jar
-transaction.jar=javax.transaction_1.1.0.v201002051055.jar
-
-moxy.global.depend=${activation.jar},${resource.jar},${ejb3.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar},${persistence10.jar}
-
-bin.includes = .,\
- META-INF/
+jms.jar=javax.jms_1.1.0.v200906010428.jar
+transaction.jar=javax.transaction_1.1.0.v201002051055.jar
+
+eclipselink.global.depend=${activation.jar},${resource.jar},${ejb3.jar},${jms.jar},${stax_api.jar},${transaction.jar},${mail.jar},${persistence10.jar},${javax.validation.jar}
+
+bin.includes = .,\
+ META-INF/
source.. = src/
diff --git a/moxy/org.eclipse.persistence.moxy/antbuild.xml b/moxy/org.eclipse.persistence.moxy/antbuild.xml
index 0108f44..731ed41 100644
--- a/moxy/org.eclipse.persistence.moxy/antbuild.xml
+++ b/moxy/org.eclipse.persistence.moxy/antbuild.xml
@@ -86,6 +86,31 @@
<property name="specification.vendor" value="Eclipse.org - EclipseLink Project"/>
<property name="implementation.vendor" value="${specification.vendor}"/>
+ <!-- dependency properties -->
+ <property name="javax.validation.lib" value="${moxy.2.base.dir}/jpa/plugins/${javax.validation.jar}"/>
+ <property name="jaxb-api.lib" value="${moxy.2.common.plugins.dir}/${jaxb-api.jar}"/>
+ <property name="jaxb-xjc.lib" value="${moxy.2.common.plugins.dir}/${jaxb-xjc.jar}"/>
+ <property name="jaxb-core.lib" value="${moxy.2.common.plugins.dir}/${jaxb-core.jar}"/>
+
+ <!-- dependency tests -->
+ <available file="${javax.validation.lib}" property="javax.validation.bundle.exist"/>
+ <!--<fail message="Cannot find javax.validation: '${javax.validation.lib}'" unless="javax.validation.bundle.exist"/>-->
+ <available file="${jaxb-api.lib}" property="jaxb-api.bundle.exist"/>
+ <fail message="Cannot find jaxb-api: '${jaxb-api.lib}'" unless="jaxb-api.bundle.exist"/>
+ <available file="${jaxb-xjc.lib}" property="jaxb-xjc.bundle.exist"/>
+ <fail message="Cannot find jaxb-xjc: '${jaxb-xjc.lib}'" unless="jaxb-xjc.bundle.exist"/>
+
+ <!-- Set Compile Path-->
+ <path id="dynamic.compile.path">
+ <pathelement path="${javax.validation.lib}"/>
+ <pathelement path="${jaxb-api.lib}"/>
+ <pathelement path="${jaxb-xjc.lib}"/>
+ <pathelement path="${jaxb-core.lib}"/>
+ <fileset
+ dir="${moxy.2.common.plugins.dir}"
+ includes="${eclipselink.global.depend}"/>
+ </path>
+
<condition property="compiled_classes.dir" value="${classes.dir}" else="target/classes">
<available file="${classes.dir}" type="dir"/>
</condition>
@@ -120,6 +145,15 @@
<fileset dir="${resource.dir}">
<include name="org/eclipse/persistence/**/*.xsd"/>
</fileset>
+ <fileset dir="${moxy.2.common.plugins.dir}">
+ <include name="${javax.validation.lib}"/>
+ </fileset>
+ <fileset dir="${moxy.2.common.plugins.dir}">
+ <include name="${jaxb-xjc.lib}"/>
+ </fileset>
+ <fileset dir="${moxy.2.common.plugins.dir}">
+ <include name="${jaxb-core.lib}"/>
+ </fileset>
</jar>
</target>
@@ -141,17 +175,4 @@
</jar>
</target>
- <target name="bnd-deps" if="bnd.bld" depends="init" description="take existing source and classes from checked in bundles, and repackage with new manifest">
- <taskdef resource="aQute/bnd/ant/taskdef.properties" classpath="${bnd.path}"/>
- <bnd
- classpath="${moxy.2.common.plugins.dir}/${jaxb-api.jar}"
- eclipse="false"
- sourcepath="${moxy.2.common.plugins.dir}/${jaxb-api.src.jar}"
- failok="false"
- exceptions="true"
- files="./javax.xml.bind.bnd"
- output="${moxy.2.common.plugins.dir}/javax.xml.bind_2.2.0.v${build.date}${build.time}.jar"/>
- <copy file="${moxy.2.common.plugins.dir}/${jaxb-api.src.jar}" tofile="${moxy.2.common.plugins.dir}/javax.xml.bind.source_2.2.0.v${build.date}${build.time}.jar" failonerror="false"/>
- </target>
-
</project> \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/resource/META-INF/services/com.sun.tools.xjc.Plugin b/moxy/org.eclipse.persistence.moxy/resource/META-INF/services/com.sun.tools.xjc.Plugin
new file mode 100644
index 0000000..3c4a29e
--- /dev/null
+++ b/moxy/org.eclipse.persistence.moxy/resource/META-INF/services/com.sun.tools.xjc.Plugin
@@ -0,0 +1 @@
+org.eclipse.persistence.jaxb.plugins.BeanValidationPlugin
diff --git a/moxy/org.eclipse.persistence.moxy/resource/org/eclipse/persistence/jaxb/beanval.xsd b/moxy/org.eclipse.persistence.moxy/resource/org/eclipse/persistence/jaxb/beanval.xsd
new file mode 100644
index 0000000..52a89ee
--- /dev/null
+++ b/moxy/org.eclipse.persistence.moxy/resource/org/eclipse/persistence/jaxb/beanval.xsd
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+******************************************************************************
+Copyright (c) 1998, 2014 Oracle. All rights reserved.
+This program and the accompanying materials are made available under the
+terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+which accompanies this distribution.
+The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+and the Eclipse Distribution License is available at
+http://www.eclipse.org/org/documents/edl-v10.php.
+
+Contributors:
+Marcel Valovy - 2014 - 2.6 - Initial implementation.
+*****************************************************************************/
+-->
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://jaxb.dev.java.net/plugin/bean-validation"
+ elementFormDefault="qualified">
+ <xs:annotation>
+ <xs:documentation>
+ JAXB customization schema for Bean Validation Plugin.
+ </xs:documentation>
+ </xs:annotation>
+
+ <xs:element name="facet">
+ <xs:complexType>
+ <xs:attribute name="message" type="xs:string"/>
+ <xs:attribute name="groups" type="xs:string"/>
+ <xs:attribute name="type" type="xs:string" use="required"/>
+ <xs:attribute name="value" type="xs:string">
+ <xs:annotation>
+ <xs:documentation>
+ Allows setting "value", use only for user custom annotations.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
+ </xs:complexType>
+ </xs:element>
+
+</xs:schema>
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/BeanValidationMode.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/BeanValidationMode.java
new file mode 100644
index 0000000..7466794
--- /dev/null
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/BeanValidationMode.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jaxb;
+
+/**
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+public enum BeanValidationMode {
+
+ /**
+ * If a Bean Validation provider is present in the environment,
+ * the JAXB implementation provider must perform the automatic validation
+ * of entities. If no Bean Validation provider is present in the
+ * environment, no validation takes place.
+ */
+ AUTO,
+
+ /**
+ * The JAXB implementation provider must perform the validation of entities.
+ * It is an error if there is no Bean Validation provider present in the
+ * environment.
+ */
+ CALLBACK,
+
+ /**
+ * The JAXB implementation provider must not perform lifecycle event validation.
+ */
+ NONE
+}
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBBeanValidator.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBBeanValidator.java
new file mode 100644
index 0000000..2df862e
--- /dev/null
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBBeanValidator.java
@@ -0,0 +1,268 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Marcel Valovy - 2.6 - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jaxb;
+
+import org.eclipse.persistence.exceptions.BeanValidationException;
+import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.ConstraintViolationException;
+import javax.validation.Path;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.groups.Default;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Set;
+
+/**
+ * JAXB Bean Validator. Serves three purposes:
+ * 1. Determines if the validation callback should take place on the (un)marshal call.
+ * 2. Processes the validation.
+ * 3. Stores the constraintViolations from the last validation call.
+ *
+ * @author Marcel Valovy - marcel.valovy@oracle.com
+ * @since 2.6
+ */
+class JAXBBeanValidator {
+
+ public static final Class<?>[] DEFAULT_GROUP_ARRAY = new Class<?>[] { Default.class };
+ private final String prefix;
+ private Set<? extends ConstraintViolation<?>> constraintViolations = Collections.emptySet();
+ private boolean shouldValidate;
+ private Validator validator;
+ private boolean stopSearchingForValidator;
+ private BeanValidationMode beanValidationMode = BeanValidationMode.NONE; // Initial value NONE will save resources by not triggering internalStateChange() when validation is off.
+ private ValidatorFactory preferredValidatorFactory;
+
+ private JAXBBeanValidator(String prefix) {
+ this.prefix = prefix;
+ }
+
+ static JAXBBeanValidator getMarshallingBeanValidator(){
+ return new JAXBBeanValidator("");
+ }
+
+ static JAXBBeanValidator getUnmarshallingBeanValidator(){
+ return new JAXBBeanValidator("un");
+ }
+
+ /**
+ * PUBLIC:
+ *
+ * First, determines whether the validation should proceed based on the provided parameters.
+ *
+ * Second, depending on Bean Validation Mode, either returns false or tries to initialize Validator:
+ * - AUTO tries to initialize Validator:
+ * returns true if succeeds, else false.
+ * - CALLBACK tries to initialize Validator:
+ * returns true if succeeds, else throws {@link BeanValidationException#providerNotFound}.
+ * - NONE returns false;
+ *
+ * BeanValidationMode is propagated from (un)marshaller upon each call.
+ * If change of mode is detected, the internal state of the JAXBBeanValidator will be switched.
+ *
+ *
+ * @param beanValidationMode Bean validation mode - allowed values AUTO, CALLBACK, NONE.
+ * @param value Some objects should not be validated, e.g. XmlBindings.
+ * @param preferredValidatorFactory May be null. Will use this factory as the preferred provider, if null, will use javax defaults.
+ * @return True if should proceed with validation, else false.
+ * @throws BeanValidationException Either {@link BeanValidationException#illegalValidationMode} or {@link BeanValidationException#providerNotFound}.
+ * @since 2.6
+ */
+ boolean shouldValidate(Object value, BeanValidationMode beanValidationMode, ValidatorFactory preferredValidatorFactory) throws BeanValidationException {
+ if (value instanceof XmlBindings) return false; // Do not validate XmlBindings.
+
+ if (this.beanValidationMode != beanValidationMode) { // The Bean Validation mode was changed (or it's the first time this method is called on current instance).
+ this.beanValidationMode = beanValidationMode;
+ this.preferredValidatorFactory = preferredValidatorFactory;
+ changeInternalState();
+ }
+ return shouldValidate;
+ }
+
+ /**
+ * INTERNAL:
+ *
+ * Validates the value, as per BV spec.
+ * Stores the constraintViolations in instance field. The field's value is
+ * not preserved through calls and gets replaced by new constraintViolations.
+ *
+ * @param value Object to be validated.
+ * @param groups Target groups as per BV spec. Must not be null, may be empty.
+ * @throws BeanValidationException {@link BeanValidationException#constraintViolation}
+ */
+ void validate(Object value, Class<?>... groups) throws BeanValidationException {
+ constraintViolations = validator.validate(value, groups);
+ if (!constraintViolations.isEmpty())
+ throw buildConstraintViolationException();
+ }
+
+ /**
+ * @return constraintViolations from the last {@link #validate} call.
+ */
+ Set<? extends ConstraintViolation<?>> getConstraintViolations() {
+ return constraintViolations;
+ }
+
+ /**
+ * INTERNAL:
+ *
+ * Puts variables to states which conform to the internal state machine.
+ *
+ * Internal states:
+ * Mode/Field Value | NONE | AUTO | CALLBACK
+ * --------------------------|-------------|--------------|--------------
+ * shouldValidate | false | true/false | true/false
+ * stopSearchingForValidator | false | true/false | false
+ * constraintViolations | EmptySet<> | n/a | n/a
+ *
+ * n/a ... not altered.
+ *
+ * @throws BeanValidationException illegalValidationMode or providerNotFound
+ */
+ private void changeInternalState() throws BeanValidationException {
+ stopSearchingForValidator = false; // Reset the switch.
+ switch (beanValidationMode) {
+ case NONE:
+ shouldValidate = false;
+ constraintViolations = Collections.emptySet(); // Clear the reference from previous (un)marshal calls.
+ break;
+ case CALLBACK:
+ case AUTO:
+ shouldValidate = initValidator();
+ break;
+ default:
+ throw BeanValidationException.illegalValidationMode(prefix, beanValidationMode.toString());
+ }
+ }
+
+ /**
+ * PUBLIC:
+ *
+ * Initializes validator if not already initialized.
+ * If mode is BeanValidationMode.AUTO, then after an unsuccessful try to
+ * initialize a Validator, property {@code stopSearchingForValidator} will be set to true.
+ *
+ * NOTE: Property {@code stopSearchingForValidator} can be reset only by triggering
+ * {@link #changeInternalState}.
+ *
+ * @return {@code true} if validator initialization succeeded, otherwise {@code false}.
+ * @throws BeanValidationException
+ */
+ private boolean initValidator() throws BeanValidationException {
+ if (validator == null && !stopSearchingForValidator){
+ try {
+ ValidatorFactory factory = getValidatorFactory();
+ validator = factory.getValidator();
+ } catch (ValidationException ve) {
+ if (beanValidationMode == BeanValidationMode.CALLBACK){
+ /* The following line ensures that changeInternalState() will be the
+ triggered on next (un)marshalling trials if mode is still CALLBACK.
+ That will ensure searching for Validator implementation again. */
+ beanValidationMode = BeanValidationMode.AUTO;
+ throw BeanValidationException.providerNotFound(prefix, ve);
+ } else { // mode AUTO
+ stopSearchingForValidator = true; // will not try to initialize validator on next tries.
+ }
+ }
+ }
+ return validator != null;
+ }
+
+ /**
+ * INTERNAL:
+ *
+ * @return Preferred ValidatorFactory if set, else {@link Validation#buildDefaultValidatorFactory()}.
+ */
+ private ValidatorFactory getValidatorFactory() {
+ return preferredValidatorFactory != null ? preferredValidatorFactory : Validation.buildDefaultValidatorFactory();
+ }
+
+ /**
+ * INTERNAL:
+ *
+ * Builds ConstraintViolationException with constraintViolations, but no message.
+ * Builds BeanValidationException with fully descriptive message, containing
+ * the ConstraintViolationException.
+ *
+ * @return BeanValidationException, containing ConstraintViolationException.
+ */
+ private BeanValidationException buildConstraintViolationException() throws BeanValidationException {
+ ConstraintViolationException cve = new ConstraintViolationException((Set<ConstraintViolation<?>>) /* do NOT remove the cast */ constraintViolations);
+ return BeanValidationException.constraintViolation(createConstraintViolationExceptionArgs(), cve);
+ }
+
+ /**
+ * INTERNAL:
+ * Builds an Object array containing args for ConstraintViolationException constructor.
+ *
+ * @return [0] - prefix,
+ * [1] - rootBean (on what object the validation failed),
+ * [2] - linkedList of violatedConstraints, with overriden toString() for better formatting.
+ */
+ private Object[] createConstraintViolationExceptionArgs() {
+ Object[] args = new Object[3];
+ Iterator<? extends ConstraintViolation<?>> iterator = constraintViolations.iterator();
+ ConstraintViolation<?> cv = iterator.next();
+ Collection<ConstraintViolationInfo> violatedConstraints = new LinkedList<ConstraintViolationInfo>(){
+ public String toString() {
+ Iterator<ConstraintViolationInfo> it = iterator();
+ StringBuilder sb = new StringBuilder();
+ while (it.hasNext())
+ sb.append("\n-->").append(it.next().toString());
+ return sb.toString();
+ }
+ };
+ args[0] = prefix;
+ Object bean = cv.getRootBean();
+ args[1] = bean.getClass().toString().substring("class ".length()) + "@" + Integer.toHexString(System.identityHashCode(bean)); // Can't use toString because of security reasons; identityHashCode can't throw NPE.
+ args[2] = violatedConstraints;
+ for (;;) {
+ violatedConstraints.add(new ConstraintViolationInfo(cv.getMessage(), cv.getPropertyPath()));
+ if (iterator.hasNext()) cv = iterator.next();
+ else break;
+ }
+ return args;
+ }
+
+
+ /**
+ * INTERNAL:
+ *
+ * Value Object class that provides adequate toString() method which describes
+ * on which field a Validation Constraint was violated and includes it's violationDescription.
+ */
+ private static class ConstraintViolationInfo {
+ private final String violationDescription;
+ private final Path propertyPath;
+
+ private ConstraintViolationInfo(String message, Path propertyPath){
+ this.violationDescription = message;
+ this.propertyPath = propertyPath;
+ }
+
+ @Override
+ public String toString() {
+ return new StringBuilder()
+ .append("Violated constraint on property ").append(propertyPath)
+ .append(": \"").append(violationDescription).append("\".")
+ .toString();
+ }
+ }
+
+}
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContext.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContext.java
index db64504..682864d 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContext.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContext.java
@@ -75,13 +75,12 @@ import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.jaxb.compiler.Generator;
import org.eclipse.persistence.jaxb.compiler.MarshalCallback;
-import org.eclipse.persistence.jaxb.compiler.UnmarshalCallback;
-import org.eclipse.persistence.jaxb.javamodel.JavaClass;
-import org.eclipse.persistence.jaxb.javamodel.reflection.AnnotationHelper;
-import org.eclipse.persistence.jaxb.javamodel.reflection.JavaClassImpl;
-import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl;
-import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl;
-import org.eclipse.persistence.jaxb.json.JsonSchemaOutputResolver;
+import org.eclipse.persistence.jaxb.compiler.UnmarshalCallback;
+import org.eclipse.persistence.jaxb.javamodel.JavaClass;
+import org.eclipse.persistence.jaxb.javamodel.reflection.AnnotationHelper;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl;
+import org.eclipse.persistence.jaxb.json.JsonSchemaOutputResolver;
import org.eclipse.persistence.jaxb.xmlmodel.JavaType;
import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings;
import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.JavaTypes;
@@ -439,13 +438,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
}
/**
- * INTERNAL:
- * Get the map containing which Class (by name) corresponds to which generated class.
- */
- public HashMap<String, Class> getClassToGeneratedClasses() {
- return contextState.getClassToGeneratedClasses();
- }
-
+ * INTERNAL:
+ * Get the map containing which Class (by name) corresponds to which generated class.
+ */
+ public Map<String, Class> getClassToGeneratedClasses() {
+ return contextState.getClassToGeneratedClasses();
+ }
+
/**
* INTERNAL:
* Set the map containing which Class (by name) corresponds to which generated class.
@@ -463,13 +462,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
}
/**
- * INTERNAL:
- * Get the map of which QName corresponds to which declared class.
- */
- public HashMap<QName, Class> getQNamesToDeclaredClasses() {
- return contextState.getQNamesToDeclaredClasses();
- }
-
+ * INTERNAL:
+ * Get the map of which QName corresponds to which declared class.
+ */
+ public Map<QName, Class> getQNamesToDeclaredClasses() {
+ return contextState.getQNamesToDeclaredClasses();
+ }
+
/**
* INTERNAL:
* Get the map of which QName corresponds to which generated class.
@@ -534,13 +533,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
* INTERNAL:
* Get the map of which Type corresponds to which QName.
* The keys should be all the boundTypes used to create the JAXBContext.
- * If the JAXBContext was not created with the constructor that takes a Type[] then
- * this Map will be empty.
- */
- public HashMap<java.lang.reflect.Type, QName> getTypeToSchemaType() {
- return contextState.getTypeToSchemaType();
- }
-
+ * If the JAXBContext was not created with the constructor that takes a Type[] then
+ * this Map will be empty.
+ */
+ public Map<java.lang.reflect.Type, QName> getTypeToSchemaType() {
+ return contextState.getTypeToSchemaType();
+ }
+
Map<TypeMappingInfo, Class> getTypeMappingInfoToGeneratedType() {
return contextState.getTypeMappingInfoToGeneratedType();
}
@@ -857,13 +856,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
}
}
}
- if (foundMetadata) {
- Class[] classArray = new Class[classes.size()];
- for (int i = 0; i < classes.size(); i++) {
- classArray[i] = (Class) classes.get(i);
- }
- return createContextState(classArray, xmlBindingMap);
- }
+ if (foundMetadata) {
+ Class[] classArray = new Class[classes.size()];
+ for (int i = 0; i < classes.size(); i++) {
+ classArray[i] = classes.get(i);
+ }
+ return createContextState(classArray, xmlBindingMap);
+ }
Exception sessionLoadingException = null;
try {
@@ -922,12 +921,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
if (metadataComplete.size() > 0) {
jModel.setMetadataCompletePackageMap(metadataComplete);
}
-
- jModel.setHasXmlBindings(xmlBindings != null || !xmlBindings.isEmpty());
- JavaModelInputImpl inputImpl = new JavaModelInputImpl(classesToBeBound, jModel);
- try {
- Generator generator = new Generator(inputImpl, xmlBindings, loader, defaultTargetNamespace, enableXmlAccessorFactory);
- return createContextState(generator, loader, classesToBeBound, properties);
+
+ jModel.setHasXmlBindings(xmlBindings != null || !xmlBindings.isEmpty());
+ JavaModelInputImpl inputImpl = new JavaModelInputImpl(classesToBeBound, jModel);
+ if (properties != null) enableFacetsIfPropertySetTrue(inputImpl, properties);
+ try {
+ Generator generator = new Generator(inputImpl, xmlBindings, loader, defaultTargetNamespace, enableXmlAccessorFactory);
+ return createContextState(generator, loader, classesToBeBound, properties);
} catch (Exception ex) {
throw new javax.xml.bind.JAXBException(ex.getMessage(), ex);
}
@@ -1078,25 +1078,31 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
if (annotationHelper != null) {
jModel = new JavaModelImpl(loader, annotationHelper);
} else {
- jModel = new JavaModelImpl(loader);
- }
-
- jModel.setHasXmlBindings(xmlBindings != null || !xmlBindings.isEmpty());
- // create Map of package names to metadata complete indicators
- Map<String, Boolean> metadataComplete = new HashMap<String, Boolean>();
- for (String packageName : xmlBindings.keySet()) {
- if (xmlBindings.get(packageName).isXmlMappingMetadataComplete()) {
- metadataComplete.put(packageName, true);
- }
- }
- if (metadataComplete.size() > 0) {
- jModel.setMetadataCompletePackageMap(metadataComplete);
- }
-
- JavaModelInputImpl inputImpl = new JavaModelInputImpl(typesToBeBound, jModel);
- try {
- Generator generator = new Generator(inputImpl, typesToBeBound, inputImpl.getJavaClasses(), null, xmlBindings, classLoader, defaultTargetNamespace, enableXmlAccessorFactory);
- JAXBContextState contextState = createContextState(generator, loader, typesToBeBound, properties);
+ jModel = new JavaModelImpl(loader);
+ }
+
+ if (xmlBindings != null) {
+ jModel.setHasXmlBindings(!xmlBindings.isEmpty());
+ // create Map of package names to metadata complete indicators
+ Map<String, Boolean> metadataComplete = new HashMap<String, Boolean>();
+ for (String packageName : xmlBindings.keySet()) {
+ if (xmlBindings.get(packageName).isXmlMappingMetadataComplete()) {
+ metadataComplete.put(packageName, true);
+ }
+ }
+
+ if (metadataComplete.size() > 0) {
+ jModel.setMetadataCompletePackageMap(metadataComplete);
+ }
+ } else {
+ jModel.setHasXmlBindings(false);
+ }
+
+ JavaModelInputImpl inputImpl = new JavaModelInputImpl(typesToBeBound, jModel);
+ if (properties != null) enableFacetsIfPropertySetTrue(inputImpl, properties);
+ try {
+ Generator generator = new Generator(inputImpl, typesToBeBound, inputImpl.getJavaClasses(), null, xmlBindings, classLoader, defaultTargetNamespace, enableXmlAccessorFactory);
+ JAXBContextState contextState = createContextState(generator, loader, typesToBeBound, properties);
return contextState;
} catch (Exception ex) {
throw new javax.xml.bind.JAXBException(ex.getMessage(), ex);
@@ -1112,14 +1118,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
} else {
conversionManager = ConversionManager.getDefaultManager();
}
- proj.convertClassNamesToClasses(conversionManager.getLoader());
- // need to make sure that the java class is set properly on each
- // descriptor when using java classname - req'd for JOT api implementation
- for (Iterator<ClassDescriptor> descriptorIt = proj.getOrderedDescriptors().iterator(); descriptorIt.hasNext();) {
- ClassDescriptor descriptor = descriptorIt.next();
- if (descriptor.getJavaClass() == null) {
- descriptor.setJavaClass(conversionManager.convertClassNameToClass(descriptor.getJavaClassName()));
- }
+ proj.convertClassNamesToClasses(conversionManager.getLoader());
+ // need to make sure that the java class is set properly on each
+ // descriptor when using java classname - req'd for JOT api implementation
+ for (ClassDescriptor descriptor : (Iterable<ClassDescriptor>) proj.getOrderedDescriptors()) {
+ if (descriptor.getJavaClass() == null) {
+ descriptor.setJavaClass(conversionManager.convertClassNameToClass(descriptor.getJavaClassName()));
+ }
}
XMLPlatform platform = new SAXPlatform();
@@ -1195,15 +1200,15 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
protected static class JAXBContextState {
- private XMLContext xmlContext;
- private org.eclipse.persistence.jaxb.compiler.Generator generator;
- private Map<QName, Class> qNameToGeneratedClasses;
- private HashMap<String, Class> classToGeneratedClasses;
- private HashMap<QName, Class> qNamesToDeclaredClasses;
- private HashMap<Type, QName> typeToSchemaType;
- private TypeMappingInfo[] boundTypes;
- private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedType;
- private Map<Type, TypeMappingInfo> typeToTypeMappingInfo;
+ private XMLContext xmlContext;
+ private org.eclipse.persistence.jaxb.compiler.Generator generator;
+ private Map<QName, Class> qNameToGeneratedClasses;
+ private Map<String, Class> classToGeneratedClasses;
+ private Map<QName, Class> qNamesToDeclaredClasses;
+ private Map<Type, QName> typeToSchemaType;
+ private TypeMappingInfo[] boundTypes;
+ private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedType;
+ private Map<Type, TypeMappingInfo> typeToTypeMappingInfo;
private Map<TypeMappingInfo, JAXBContext.RootLevelXmlAdapter> typeMappingInfoToJavaTypeAdapters;
private Map properties;
@@ -1235,13 +1240,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
protected JAXBContextState(XMLContext context, Generator generator, TypeMappingInfo[] boundTypes, Map properties) {
this(context);
this.generator = generator;
- this.qNameToGeneratedClasses = generator.getMappingsGenerator().getQNamesToGeneratedClasses();
- this.classToGeneratedClasses = generator.getMappingsGenerator().getClassToGeneratedClasses();
- this.qNamesToDeclaredClasses = generator.getMappingsGenerator().getQNamesToDeclaredClasses();
- this.typeMappingInfoToGeneratedType = generator.getAnnotationsProcessor().getTypeMappingInfoToGeneratedClasses();
- this.setTypeMappingInfoToJavaTypeAdapaters(createAdaptersForAdapterClasses(generator.getAnnotationsProcessor().getTypeMappingInfoToAdapterClasses()));
- this.boundTypes = boundTypes;
- if (properties != null) {
+ this.qNameToGeneratedClasses = generator.getMappingsGenerator().getQNamesToGeneratedClasses();
+ this.classToGeneratedClasses = generator.getMappingsGenerator().getClassToGeneratedClasses();
+ this.qNamesToDeclaredClasses = generator.getMappingsGenerator().getQNamesToDeclaredClasses();
+ this.typeMappingInfoToGeneratedType = generator.getAnnotationsProcessor().getTypeMappingInfosToGeneratedClasses();
+ this.setTypeMappingInfoToJavaTypeAdapaters(createAdaptersForAdapterClasses(generator.getAnnotationsProcessor().getTypeMappingInfoToAdapterClasses()));
+ this.boundTypes = boundTypes;
+ if (properties != null) {
this.properties = new HashMap(properties);
}
}
@@ -1307,17 +1312,17 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
return;
}
processed.add(desc);
-
- Vector mappings = desc.getMappings();
-
- for (int i = 0; i < mappings.size(); i++) {
- DatabaseMapping nextMapping = (DatabaseMapping) mappings.get(i);
- Vector fields = nextMapping.getFields();
- updateResolverForFields(fields, nr);
- Descriptor refDesc = (Descriptor) ((DatabaseMapping) nextMapping).getReferenceDescriptor();
- if (refDesc != null && !processed.contains(refDesc)) {
- processXMLDescriptor(processed, refDesc, nr);
- }
+
+ Vector mappings = desc.getMappings();
+
+ for (Object mapping : mappings) {
+ DatabaseMapping nextMapping = (DatabaseMapping) mapping;
+ Vector fields = nextMapping.getFields();
+ updateResolverForFields(fields, nr);
+ Descriptor refDesc = (Descriptor) nextMapping.getReferenceDescriptor();
+ if (refDesc != null && !processed.contains(refDesc)) {
+ processXMLDescriptor(processed, refDesc, nr);
+ }
if (nextMapping instanceof ChoiceObjectMapping) {
Set refClasses = ((ChoiceObjectMapping) nextMapping).getClassToFieldMappings().keySet();
@@ -1327,15 +1332,14 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
processRefClasses(processed, refClasses, nr);
}
}
- }
-
- private void updateResolverForFields(Collection fields, org.eclipse.persistence.internal.oxm.NamespaceResolver nr) {
- Iterator fieldIter = fields.iterator();
- while (fieldIter.hasNext()) {
- Field field = (XMLField) fieldIter.next();
- XPathFragment currentFragment = field.getXPathFragment();
-
- while (currentFragment != null) {
+ }
+
+ private void updateResolverForFields(Collection fields, org.eclipse.persistence.internal.oxm.NamespaceResolver nr) {
+ for (Object field1 : fields) {
+ Field field = (XMLField) field1;
+ XPathFragment currentFragment = field.getXPathFragment();
+
+ while (currentFragment != null) {
String uri = currentFragment.getNamespaceURI();
if (uri != null && nr.resolveNamespaceURI(uri) == null && !uri.equals(nr.getDefaultNamespaceURI())) {
String prefix = currentFragment.getPrefix();
@@ -1346,25 +1350,25 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
}
currentFragment = currentFragment.getNextFragment();
}
- }
- }
-
- private HashMap<String, Class> getClassToGeneratedClasses() {
- return classToGeneratedClasses;
- }
-
+ }
+ }
+
+ private Map<String, Class> getClassToGeneratedClasses() {
+ return classToGeneratedClasses;
+ }
+
private Generator getGenerator() {
return generator;
}
private XMLContext getXMLContext() {
- return this.xmlContext;
- }
-
- private HashMap<java.lang.reflect.Type, QName> getTypeToSchemaType() {
- if (typeToSchemaType == null) {
- initTypeToSchemaType();
- }
+ return this.xmlContext;
+ }
+
+ private Map<java.lang.reflect.Type, QName> getTypeToSchemaType() {
+ if (typeToSchemaType == null) {
+ initTypeToSchemaType();
+ }
return typeToSchemaType;
}
@@ -1381,16 +1385,16 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
}
private Map<TypeMappingInfo, QName> getTypeMappingInfoToSchemaType() {
- if (typeToTypeMappingInfo != null && typeToTypeMappingInfo.size() > 0) {
- return new HashMap<TypeMappingInfo, QName>();
- }
- return generator.getAnnotationsProcessor().getTypeMappingInfoToSchemaType();
- }
-
- private HashMap<QName, Class> getQNamesToDeclaredClasses() {
- return qNamesToDeclaredClasses;
- }
-
+ if (typeToTypeMappingInfo != null && typeToTypeMappingInfo.size() > 0) {
+ return new HashMap<TypeMappingInfo, QName>();
+ }
+ return generator.getAnnotationsProcessor().getTypeMappingInfosToSchemaTypes();
+ }
+
+ private Map<QName, Class> getQNamesToDeclaredClasses() {
+ return qNamesToDeclaredClasses;
+ }
+
/**
* INTERNAL:
* Get the QName which the given Type corresponds to.
@@ -1443,13 +1447,13 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
Type type = null;
if (generator != null) {
- type = generator.getAnnotationsProcessor().getGeneratedClassesToCollectionClasses().get(javaClass);
-
- if (type == null) {
- JavaClass arrayClass = (JavaClass) generator.getAnnotationsProcessor().getGeneratedClassesToArrayClasses().get(javaClass);
- if (arrayClass != null) {
- String arrayClassName = arrayClass.getName();
- try {
+ type = generator.getAnnotationsProcessor().getGeneratedClassesToCollectionClasses().get(javaClass);
+
+ if (type == null) {
+ JavaClass arrayClass = generator.getAnnotationsProcessor().getGeneratedClassesToArrayClasses().get(javaClass);
+ if (arrayClass != null) {
+ String arrayClassName = arrayClass.getName();
+ try {
type = PrivilegedAccessHelper.getClassForName(arrayClassName);
} catch (Exception ex) {
}
@@ -1537,12 +1541,15 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
setPropertyOnMarshaller(JAXBContextProperties.NAMESPACE_PREFIX_MAPPER, marshaller);
setPropertyOnMarshaller(JAXBContextProperties.JSON_INCLUDE_ROOT, marshaller);
setPropertyOnMarshaller(JAXBContextProperties.JSON_VALUE_WRAPPER, marshaller);
- setPropertyOnMarshaller(JAXBContextProperties.JSON_NAMESPACE_SEPARATOR, marshaller);
- setPropertyOnMarshaller(JAXBContextProperties.OBJECT_GRAPH, marshaller);
- setPropertyOnMarshaller(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, marshaller);
- }
-
- return marshaller;
+ setPropertyOnMarshaller(JAXBContextProperties.JSON_NAMESPACE_SEPARATOR, marshaller);
+ setPropertyOnMarshaller(JAXBContextProperties.OBJECT_GRAPH, marshaller);
+ setPropertyOnMarshaller(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, marshaller);
+ setPropertyOnMarshaller(JAXBContextProperties.BEAN_VALIDATION_MODE, marshaller);
+ setPropertyOnMarshaller(JAXBContextProperties.BEAN_VALIDATION_FACTORY, marshaller);
+ setPropertyOnMarshaller(JAXBContextProperties.BEAN_VALIDATION_GROUPS, marshaller);
+ }
+
+ return marshaller;
}
public JAXBUnmarshaller createUnmarshaller(JAXBContext jaxbContext) throws javax.xml.bind.JAXBException {
@@ -1568,6 +1575,9 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
setPropertyOnUnmarshaller(JAXBContextProperties.OBJECT_GRAPH, unmarshaller);
setPropertyOnUnmarshaller(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, unmarshaller);
setPropertyOnUnmarshaller(JAXBContextProperties.UNMARSHALLING_CASE_INSENSITIVE, unmarshaller);
+ setPropertyOnUnmarshaller(JAXBContextProperties.BEAN_VALIDATION_MODE, unmarshaller);
+ setPropertyOnUnmarshaller(JAXBContextProperties.BEAN_VALIDATION_FACTORY, unmarshaller);
+ setPropertyOnUnmarshaller(JAXBContextProperties.BEAN_VALIDATION_GROUPS, unmarshaller);
}
return unmarshaller;
}
@@ -1599,7 +1609,12 @@ public class JAXBContext extends javax.xml.bind.JAXBContext {
if (propertyValue != null) {
unmarshaller.setProperty(propertyName, propertyValue);
}
- }
-
- }
+ }
+
+ }
+
+ private static void enableFacetsIfPropertySetTrue(JavaModelInputImpl inputImpl, Map properties) {
+ Object propertyValue = properties.get(JAXBContextProperties.GENERATE_FACETS);
+ if (propertyValue != null) inputImpl.setFacets((Boolean) propertyValue);
+ }
} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextFactory.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextFactory.java
index e44b0c2..e183ecf 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextFactory.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextFactory.java
@@ -1,8 +1,8 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
@@ -138,21 +138,21 @@ public class JAXBContextFactory {
* also be aware of classes reachable from the types in the array. The
* preferred means of creating a Type aware JAXBContext is to create the
* JAXBContext with an array of TypeMappingInfo objects.
- */
- public static javax.xml.bind.JAXBContext createContext(Type[] typesToBeBound, Map properties, ClassLoader classLoader) throws JAXBException {
- Map<Type, TypeMappingInfo> typeToTypeMappingInfo = new HashMap<Type, TypeMappingInfo>();
- TypeMappingInfo[] typeMappingInfo = new TypeMappingInfo[typesToBeBound.length];
- for(int i = 0; i < typesToBeBound.length; i++) {
- TypeMappingInfo tmi = new TypeMappingInfo();
- tmi.setType(typesToBeBound[i]);
- typeToTypeMappingInfo.put(typesToBeBound[i], tmi);
- typeMappingInfo[i] = tmi;
- }
-
- JAXBContext context = (JAXBContext)createContext(typeMappingInfo, properties, classLoader);
- context.setTypeToTypeMappingInfo(typeToTypeMappingInfo);
-
- return context;
+ */
+ public static javax.xml.bind.JAXBContext createContext(Type[] typesToBeBound, Map properties, ClassLoader classLoader) throws JAXBException {
+ Map<Type, TypeMappingInfo> typeToTypeMappingInfo = new HashMap<Type, TypeMappingInfo>();
+ TypeMappingInfo[] typeMappingInfos = new TypeMappingInfo[typesToBeBound.length];
+ for(int i = 0; i < typesToBeBound.length; i++) {
+ TypeMappingInfo tmi = new TypeMappingInfo();
+ tmi.setType(typesToBeBound[i]);
+ typeToTypeMappingInfo.put(typesToBeBound[i], tmi);
+ typeMappingInfos[i] = tmi;
+ }
+
+ JAXBContext context = (JAXBContext)createContext(typeMappingInfos, properties, classLoader);
+ context.setTypeToTypeMappingInfo(typeToTypeMappingInfo);
+
+ return context;
}
/**
@@ -213,47 +213,45 @@ public class JAXBContextFactory {
Map<String, Object> metadataFiles = null;
try {
metadataFiles = (Map<String, Object>) value;
- } catch (ClassCastException x) {
- throw org.eclipse.persistence.exceptions.JAXBException.incorrectValueParameterTypeForOxmXmlKey();
- }
- if (metadataFiles != null) {
- for(Entry<String, Object> entry : metadataFiles.entrySet()) {
- String key = null;
- List<XmlBindings> xmlBindings = new ArrayList<XmlBindings>();
- try {
- key = entry.getKey();
- if (key == null) {
- throw org.eclipse.persistence.exceptions.JAXBException.nullMapKey();
- }
- } catch (ClassCastException cce) {
- throw org.eclipse.persistence.exceptions.JAXBException.incorrectKeyParameterType();
- }
- Object metadataSource = entry.getValue();
- if (metadataSource == null) {
- throw org.eclipse.persistence.exceptions.JAXBException.nullMetadataSource(key);
- }
- if(metadataSource instanceof List) {
- for(Object next: (List)metadataSource) {
- XmlBindings binding = getXmlBindings(next, classLoader, properties);
- if(binding != null) {
- xmlBindings.add(binding);
- }
- }
- } else {
- XmlBindings binding = getXmlBindings(metadataSource, classLoader, properties);
- if(binding != null) {
- xmlBindings.add(binding);
- }
- }
- if (xmlBindings != null) {
- bindings.put(key, xmlBindings);
- }
- }
- }
- // handle List<Object>
- } else if (value instanceof List) {
- for (Object metadataSource : (List) value) {
- if (metadataSource == null) {
+ } catch (ClassCastException x) {
+ throw org.eclipse.persistence.exceptions.JAXBException.incorrectValueParameterTypeForOxmXmlKey();
+ }
+ for(Entry<String, Object> entry : metadataFiles.entrySet()) {
+ String key = null;
+ List<XmlBindings> xmlBindings = new ArrayList<XmlBindings>();
+ try {
+ key = entry.getKey();
+ if (key == null) {
+ throw org.eclipse.persistence.exceptions.JAXBException.nullMapKey();
+ }
+ } catch (ClassCastException cce) {
+ throw org.eclipse.persistence.exceptions.JAXBException.incorrectKeyParameterType();
+ }
+ Object metadataSource = entry.getValue();
+ if (metadataSource == null) {
+ throw org.eclipse.persistence.exceptions.JAXBException.nullMetadataSource(key);
+ }
+ if(metadataSource instanceof List) {
+ for(Object next: (List)metadataSource) {
+ XmlBindings binding = getXmlBindings(next, classLoader, properties);
+ if(binding != null) {
+ xmlBindings.add(binding);
+ }
+ }
+ } else {
+ XmlBindings binding = getXmlBindings(metadataSource, classLoader, properties);
+ if(binding != null) {
+ xmlBindings.add(binding);
+ }
+ }
+ if (xmlBindings != null) {
+ bindings.put(key, xmlBindings);
+ }
+ }
+ // handle List<Object>
+ } else if (value instanceof List) {
+ for (Object metadataSource : (List) value) {
+ if (metadataSource == null) {
throw org.eclipse.persistence.exceptions.JAXBException.nullMetadataSource();
}
bindings = processBindingFile(bindings, metadataSource, classLoader, properties);
@@ -277,29 +275,28 @@ public class JAXBContextFactory {
* @param originalBindings Map of bindings to be updated
* @param bindingHandle handle to bindings file
* @param classLoader
- * @return
- */
- private static Map<String, List<XmlBindings>> processBindingFile(Map<String, List<XmlBindings>> originalBindings, Object bindingHandle, ClassLoader classLoader, Map<String, Object> properties) {
- Map<String, List<XmlBindings>> bindingMap = originalBindings;
- XmlBindings binding = getXmlBindings(bindingHandle, classLoader, properties);
- if (binding != null) {
- String key = binding.getPackageName();
- if (key.equals(XMLProcessor.DEFAULT)) {
- throw org.eclipse.persistence.exceptions.JAXBException.packageNotSetForBindingException();
- }
- List<XmlBindings> existingBindings = bindingMap.get(key);
- if(existingBindings != null) {
- existingBindings.add(binding);
- } else {
- existingBindings = new ArrayList<XmlBindings>();
- existingBindings.add(binding);
- bindingMap.put(key, existingBindings);
- }
- }
- return bindingMap;
- }
-
- /**
+ * @return
+ */
+ private static Map<String, List<XmlBindings>> processBindingFile(Map<String, List<XmlBindings>> originalBindings, Object bindingHandle, ClassLoader classLoader, Map<String, Object> properties) {
+ XmlBindings binding = getXmlBindings(bindingHandle, classLoader, properties);
+ if (binding != null) {
+ String key = binding.getPackageName();
+ if (key.equals(XMLProcessor.DEFAULT)) {
+ throw org.eclipse.persistence.exceptions.JAXBException.packageNotSetForBindingException();
+ }
+ List<XmlBindings> existingBindings = originalBindings.get(key);
+ if(existingBindings != null) {
+ existingBindings.add(binding);
+ } else {
+ existingBindings = new ArrayList<XmlBindings>();
+ existingBindings.add(binding);
+ originalBindings.put(key, existingBindings);
+ }
+ }
+ return originalBindings;
+ }
+
+ /**
* Convenience method for creating an XmlBindings object based on a given Object. The method
* will load the eclipselink metadata model and unmarshal the Object. This assumes that the
* Object represents the eclipselink-oxm.xml metadata file to be unmarshalled.
@@ -307,14 +304,13 @@ public class JAXBContextFactory {
* @param metadata assumed to be one of: File, InputSource, InputStream, Reader, Source
*/
private static XmlBindings getXmlBindings(Object metadata, ClassLoader classLoader, Map<String, Object> properties) {
- JAXBContext jaxbContext = CompilerHelper.getXmlBindingsModelContext();
- InputStream openedStream = null;
-
- try{
-
- Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
- unmarshaller.setProperty(UnmarshallerProperties.AUTO_DETECT_MEDIA_TYPE, true);
+ JAXBContext jaxbContext = CompilerHelper.getXmlBindingsModelContext();
+ InputStream openedStream = null;
+
+ try {
+ Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
+ unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
+ unmarshaller.setProperty(UnmarshallerProperties.AUTO_DETECT_MEDIA_TYPE, true);
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
unmarshaller.setEventHandler(new DefaultValidationEventHandler());
if (metadata instanceof MetadataSource){
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextProperties.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextProperties.java
index 870e19a..3259acc 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextProperties.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBContextProperties.java
@@ -9,7 +9,8 @@
*
* Contributors:
* Blaise Doughan - 2.4.0 - initial implementation
- * Marcel Valovy - 2.6.0 - added case insensitive unmarshalling property
+ * Marcel Valovy - 2.6 - added case insensitive unmarshalling property
+ * - added bean validation related properties
******************************************************************************/
package org.eclipse.persistence.jaxb;
@@ -253,10 +254,52 @@ public class JAXBContextProperties {
* <p>The property must be passed to the {@link org.eclipse.persistence.jaxb.JAXBContextFactory}, when creating
* {@link org.eclipse.persistence.jaxb.JAXBContext}. It will affect only unmarshaller created from that context.</p>
*
+ * <p>Specifying this flag may impose a slight performance penalty.</p>
+ *
* @since 2.6.0
* @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=331241">EclipseLink Forum, Bug 331241.</a>
* @see org.eclipse.persistence.jaxb.UnmarshallerProperties#UNMARSHALLING_CASE_INSENSITIVE
*/
public static final String UNMARSHALLING_CASE_INSENSITIVE = "eclipselink.unmarshalling.case-insensitive";
+ /**
+ * Property for setting bean validation mode.
+ * Valid values {@link BeanValidationMode#AUTO} (default),{@link BeanValidationMode#CALLBACK}, {@link BeanValidationMode#NONE}.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_MODE
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_MODE
+ */
+ public static final String BEAN_VALIDATION_MODE = "eclipselink.beanvalidation.mode";
+
+ /**
+ * Property for setting preferred or custom validator factory.
+ * The mapped value must implement javax.validation.ValidatorFactory.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_FACTORY
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_FACTORY
+ */
+ public static final String BEAN_VALIDATION_FACTORY = "eclipselink.beanvalidation.factory";
+
+ /**
+ * Property for setting bean validation target groups.
+ * The mapped value must be of type Class<?>[].
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_GROUPS
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_GROUPS
+ */
+ public static final String BEAN_VALIDATION_GROUPS = "eclipselink.beanvalidation.groups";
+
+ /**
+ * Property for disabling/enabling generation of XML Facets during schemagen.
+ * The mapped value must be of type Boolean.
+ * If it's true, then facets will be generated, based on the BV annotations.
+ * If false, the BV annotations processing will be skipped during schemagen
+ * and no facets will be generated.
+ *
+ * @since 2.6
+ */
+ public static final String GENERATE_FACETS = "eclipselink.generate.facets";
} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBMarshaller.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBMarshaller.java
index f59e2d1..9c154ac 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBMarshaller.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBMarshaller.java
@@ -1,30 +1,29 @@
-/*******************************************************************************
- * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
+/*******************************************************************************
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
- * Oracle - initial API and implementation from Oracle TopLink
- ******************************************************************************/
-package org.eclipse.persistence.jaxb;
-
+ *
+ * Contributors:
+ * Oracle - initial API and implementation from Oracle TopLink
+ * Marcel Valovy - 2.6.0 - added case insensitive unmarshalling property,
+ * added Bean Validation support.
+ ******************************************************************************/
+package org.eclipse.persistence.jaxb;
+
import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.MarshalException;
+import java.io.OutputStream;
+import java.io.Writer;
+import java.io.File;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.ValidatorFactory;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.ValidationEventHandler;
@@ -35,13 +34,21 @@ import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.validation.Schema;
-
-import java.lang.reflect.Array;
-import java.lang.reflect.Type;
-
-import org.w3c.dom.Node;
-import org.xml.sax.ContentHandler;
-import org.eclipse.persistence.oxm.CharacterEscapeHandler;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.persistence.exceptions.BeanValidationException;
+import org.eclipse.persistence.jaxb.attachment.AttachmentMarshallerAdapter;
+import org.w3c.dom.Node;
+import org.xml.sax.ContentHandler;
+import org.eclipse.persistence.oxm.CharacterEscapeHandler;
import org.eclipse.persistence.oxm.JSONWithPadding;
import org.eclipse.persistence.oxm.MediaType;
import org.eclipse.persistence.oxm.NamespacePrefixMapper;
@@ -60,13 +67,12 @@ import org.eclipse.persistence.internal.jaxb.ObjectGraphImpl;
import org.eclipse.persistence.internal.jaxb.WrappedValue;
import org.eclipse.persistence.internal.oxm.Constants;
import org.eclipse.persistence.internal.oxm.Root;
-import org.eclipse.persistence.internal.oxm.record.namespaces.MapNamespacePrefixMapper;
-import org.eclipse.persistence.internal.oxm.record.namespaces.NamespacePrefixMapperWrapper;
-import org.eclipse.persistence.jaxb.JAXBContext.RootLevelXmlAdapter;
-import org.eclipse.persistence.jaxb.attachment.*;
-
-/**
- * INTERNAL:
+import org.eclipse.persistence.internal.oxm.record.namespaces.MapNamespacePrefixMapper;
+import org.eclipse.persistence.internal.oxm.record.namespaces.NamespacePrefixMapperWrapper;
+import org.eclipse.persistence.jaxb.JAXBContext.RootLevelXmlAdapter;
+
+/**
+ * INTERNAL:
* <p>
* <b>Purpose:</b>To Provide an implementation of the JAXB 2.0 Marshaller
* Interface
@@ -86,12 +92,18 @@ import org.eclipse.persistence.jaxb.attachment.*;
* @see org.eclipse.persistence.jaxb.MarshallerProperties
* @see org.eclipse.persistence.oxm.XMLMarshaller
*/
-
-public class JAXBMarshaller implements javax.xml.bind.Marshaller {
-
- private ValidationEventHandler validationEventHandler;
- private XMLMarshaller xmlMarshaller;
- private JAXBContext jaxbContext;
+
+public class JAXBMarshaller implements javax.xml.bind.Marshaller {
+
+ private final JAXBBeanValidator beanValidator;
+
+ private BeanValidationMode beanValidationMode;
+ private ValidatorFactory preferredValidatorFactory;
+ private Class<?>[] beanValidationGroups = JAXBBeanValidator.DEFAULT_GROUP_ARRAY;
+
+ private ValidationEventHandler validationEventHandler;
+ private XMLMarshaller xmlMarshaller;
+ private JAXBContext jaxbContext;
public static final String XML_JAVATYPE_ADAPTERS = "xml-javatype-adapters";
@@ -122,12 +134,14 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
* @param newXMLMarshaller
* @param newIntrospector
*/
- public JAXBMarshaller(XMLMarshaller newXMLMarshaller, JAXBIntrospector newIntrospector) {
- super();
- validationEventHandler = JAXBContext.DEFAULT_VALIDATION_EVENT_HANDER;
- xmlMarshaller = newXMLMarshaller;
- xmlMarshaller.setErrorHandler(new JAXBErrorHandler(validationEventHandler));
- xmlMarshaller.setEncoding("UTF-8");
+ public JAXBMarshaller(XMLMarshaller newXMLMarshaller, JAXBIntrospector newIntrospector) {
+ super();
+ validationEventHandler = JAXBContext.DEFAULT_VALIDATION_EVENT_HANDER;
+ beanValidationMode = BeanValidationMode.AUTO;
+ beanValidator = JAXBBeanValidator.getMarshallingBeanValidator();
+ xmlMarshaller = newXMLMarshaller;
+ xmlMarshaller.setErrorHandler(new JAXBErrorHandler(validationEventHandler));
+ xmlMarshaller.setEncoding("UTF-8");
xmlMarshaller.setFormattedOutput(false);
xmlMarshaller.getProperties().put(Constants.JAXB_MARSHALLER, this);
}
@@ -307,12 +321,18 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
} else if (MarshallerProperties.OBJECT_GRAPH.equals(key)) {
Object graph = xmlMarshaller.getMarshalAttributeGroup();
if(graph instanceof CoreAttributeGroup) {
- return new ObjectGraphImpl((CoreAttributeGroup)graph);
- }
- return graph;
- }
- throw new PropertyException(key);
- }
+ return new ObjectGraphImpl((CoreAttributeGroup)graph);
+ }
+ return graph;
+ } else if (MarshallerProperties.BEAN_VALIDATION_MODE.equals(key)) {
+ return this.beanValidationMode;
+ } else if (MarshallerProperties.BEAN_VALIDATION_FACTORY.equals(key)) {
+ return this.preferredValidatorFactory;
+ } else if (MarshallerProperties.BEAN_VALIDATION_GROUPS.equals(key)) {
+ return this.beanValidationGroups;
+ }
+ throw new PropertyException(key);
+ }
public Schema getSchema() {
return xmlMarshaller.getSchema();
@@ -327,15 +347,17 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- xmlMarshaller.marshal(oxmObject, contentHandler);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ xmlMarshaller.marshal(oxmObject, contentHandler);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
@@ -364,17 +386,19 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- XMLEventWriterRecord record = new XMLEventWriterRecord(eventWriter);
- record.setMarshaller(this.xmlMarshaller);
- this.xmlMarshaller.marshal(oxmObject, record);
- } catch (Exception ex) {
- throw new MarshalException(ex);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ XMLEventWriterRecord record = new XMLEventWriterRecord(eventWriter);
+ record.setMarshaller(this.xmlMarshaller);
+ this.xmlMarshaller.marshal(oxmObject, record);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception ex) {
+ throw new MarshalException(ex);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
@@ -418,15 +442,17 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- xmlMarshaller.marshal(oxmObject, node);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ xmlMarshaller.marshal(oxmObject, node);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
@@ -444,15 +470,17 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- xmlMarshaller.marshal(oxmObject, outputStream);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ xmlMarshaller.marshal(oxmObject, outputStream);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
@@ -462,29 +490,33 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
}
public void marshal(Object object, File file) throws JAXBException {
- try {
- FileOutputStream outputStream = new FileOutputStream(file);
- try {
- marshal(object, outputStream);
- } finally {
- outputStream.close();
- }
- } catch (Exception ex) {
- throw new MarshalException(ex);
- }
+ try {
+ FileOutputStream outputStream = new FileOutputStream(file);
+ try {
+ marshal(object, outputStream); // link to the other one
+ } finally {
+ outputStream.close();
+ }
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception ex) {
+ throw new MarshalException(ex);
+ }
}
public void marshal(Object object, Result result) throws JAXBException {
- if (object == null || result == null) {
- throw new IllegalArgumentException();
- }
- object = modifyObjectIfNeeded(object);
-
- try {
- xmlMarshaller.marshal(object, result);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ if (object == null || result == null) {
+ throw new IllegalArgumentException();
+ }
+ object = validateAndTransformIfNeeded(object); // xml bindings + json object
+
+ try {
+ xmlMarshaller.marshal(object, result);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
}
public void marshal(Object object, Result result, TypeMappingInfo type) throws JAXBException {
@@ -524,48 +556,56 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- XMLStreamWriterRecord record = new XMLStreamWriterRecord(streamWriter);
- record.setMarshaller(this.xmlMarshaller);
- this.xmlMarshaller.marshal(oxmObject, record);
- } catch (Exception ex) {
- throw new MarshalException(ex);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ XMLStreamWriterRecord record = new XMLStreamWriterRecord(streamWriter);
+ record.setMarshaller(this.xmlMarshaller);
+ this.xmlMarshaller.marshal(oxmObject, record);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception ex) {
+ throw new MarshalException(ex);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
listener.afterMarshal(object);
}
- }
- }
-
- private Object modifyObjectIfNeeded(Object obj){
- if(obj instanceof Collection){
- Collection objectList = (Collection)obj;
- List newList = new ArrayList(objectList.size());
- for(Object o:objectList){
- newList.add(modifySingleObjectIfNeeded(o));
- }
- return newList;
- }else if(obj.getClass().isArray()){
- int arraySize = Array.getLength(obj);
- List newList = new ArrayList(arraySize);
- for(int x=0; x<arraySize; x++) {
- newList.add(modifySingleObjectIfNeeded(Array.get(obj, x)));
- }
- return newList;
- }else{
- return modifySingleObjectIfNeeded(obj);
- }
- }
-
- private Object modifySingleObjectIfNeeded(Object obj){
- // let the JAXBIntrospector determine if the object is a JAXBElement
- if (obj instanceof JAXBElement) {
+ }
+ }
+
+ private Object validateAndTransformIfNeeded(Object obj) throws BeanValidationException {
+ Object result = modifyObjectIfNeeded(obj);
+ if (beanValidator.shouldValidate(obj, beanValidationMode, preferredValidatorFactory)) beanValidator.validate(result, beanValidationGroups);
+ return result;
+ }
+
+ private Object modifyObjectIfNeeded(Object obj) {
+ if (obj instanceof Collection) {
+ Collection objectList = (Collection) obj;
+ List newList = new ArrayList(objectList.size());
+ for (Object o : objectList) {
+ newList.add(modifySingleObjectIfNeeded(o));
+ }
+ return newList;
+ } else if (obj.getClass().isArray()) {
+ int arraySize = Array.getLength(obj);
+ List newList = new ArrayList(arraySize);
+ for (int x = 0; x < arraySize; x++) {
+ newList.add(modifySingleObjectIfNeeded(Array.get(obj, x)));
+ }
+ return newList;
+ } else {
+ return modifySingleObjectIfNeeded(obj);
+ }
+ }
+
+ private Object modifySingleObjectIfNeeded(Object obj){
+ // let the JAXBIntrospector determine if the object is a JAXBElement
+ if (obj instanceof JAXBElement) {
// use the JAXBElement's properties to populate an XMLRoot
return createXMLRootFromJAXBElement((JAXBElement) obj);
} else if(obj != null && obj.getClass().isEnum()) {
@@ -673,15 +713,17 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(listener != null) {
if(object instanceof JAXBElement) {
listener.beforeMarshal(object);
- }
- }
-
- Object oxmObject = modifyObjectIfNeeded(object);
- try {
- xmlMarshaller.marshal(oxmObject, writer);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ }
+ }
+
+ Object oxmObject = validateAndTransformIfNeeded(object); // xml bindings + object
+ try {
+ xmlMarshaller.marshal(oxmObject, writer);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
if(listener != null) {
if(object instanceof JAXBElement) {
@@ -691,17 +733,19 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
}
public void marshal(Object object, MarshalRecord record) throws JAXBException {
- if (object == null || record == null) {
- throw new IllegalArgumentException();
- }
- object = modifyObjectIfNeeded(object);
-
- try {
- record.setMarshaller(xmlMarshaller);
- xmlMarshaller.marshal(object, record);
- } catch (Exception e) {
- throw new MarshalException(e);
- }
+ if (object == null || record == null) {
+ throw new IllegalArgumentException();
+ }
+ object = validateAndTransformIfNeeded(object); // xml bindings + object
+
+ try {
+ record.setMarshaller(xmlMarshaller);
+ xmlMarshaller.marshal(object, record);
+ } catch (BeanValidationException bve) {
+ throw new MarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception e) {
+ throw new MarshalException(e);
+ }
}
public void marshal(Object object, MarshalRecord record, TypeMappingInfo type) throws JAXBException {
@@ -762,13 +806,13 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
if(xmlMarshaller.getMarshalListener() == null) {
xmlMarshaller.setMarshalListener(new JAXBMarshalListener(jaxbContext, this));
}
- ((JAXBMarshalListener) xmlMarshaller.getMarshalListener()).setListener(listener);
- }
-
- public void setMarshalCallbacks(java.util.HashMap callbacks) {
- if(callbacks == null || callbacks.isEmpty()) {
- return;
- }
+ ((JAXBMarshalListener) xmlMarshaller.getMarshalListener()).setListener(listener);
+ }
+
+ public void setMarshalCallbacks(Map callbacks) {
+ if(callbacks == null || callbacks.isEmpty()) {
+ return;
+ }
if(xmlMarshaller.getMarshalListener() == null) {
xmlMarshaller.setMarshalListener(new JAXBMarshalListener(jaxbContext, this));
}
@@ -860,18 +904,18 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
} else if (MarshallerProperties.JSON_ATTRIBUTE_PREFIX.equals(key)) {
xmlMarshaller.setAttributePrefix((String)value);
} else if (MarshallerProperties.JSON_INCLUDE_ROOT.equals(key)) {
- if(value == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
- }
- xmlMarshaller.setIncludeRoot((Boolean)value);
- } else if(MarshallerProperties.JSON_VALUE_WRAPPER.equals(key)){
- if(value == null || (((String)value).length() == 0)){
- throw new PropertyException(key, Constants.EMPTY_STRING);
- }
- xmlMarshaller.setValueWrapper((String)value);
- } else if(MarshallerProperties.JSON_NAMESPACE_SEPARATOR.equals(key)){
- if(value == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ xmlMarshaller.setIncludeRoot((Boolean)value);
+ } else if(MarshallerProperties.JSON_VALUE_WRAPPER.equals(key)){
+ if(value == null || (((String)value).length() == 0)){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ xmlMarshaller.setValueWrapper((String)value);
+ } else if(MarshallerProperties.JSON_NAMESPACE_SEPARATOR.equals(key)){
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
}
xmlMarshaller.setNamespaceSeparator((Character)value);
} else if(MarshallerProperties.OBJECT_GRAPH.equals(key)) {
@@ -881,25 +925,40 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
xmlMarshaller.setMarshalAttributeGroup(((ObjectGraphImpl)value).getAttributeGroup());
} else if(value.getClass() == ClassConstants.STRING){
xmlMarshaller.setMarshalAttributeGroup(value);
- } else {
- throw org.eclipse.persistence.exceptions.JAXBException.invalidValueForObjectGraph(value);
- }
- } else {
- throw new PropertyException(key, value);
- }
+ } else {
+ throw org.eclipse.persistence.exceptions.JAXBException.invalidValueForObjectGraph(value);
+ }
+ } else if (MarshallerProperties.BEAN_VALIDATION_MODE.equals(key)) {
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ this.beanValidationMode = ((BeanValidationMode)value);
+ } else if (MarshallerProperties.BEAN_VALIDATION_FACTORY.equals(key)) {
+ if(value == null){
+ // Allow null value for preferred validation factory.
+ }
+ this.preferredValidatorFactory = ((ValidatorFactory)value);
+ } else if (MarshallerProperties.BEAN_VALIDATION_GROUPS.equals(key)) {
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ this.beanValidationGroups = ((Class<?>[]) value);
+ } else {
+ throw new PropertyException(key, value);
+ }
} catch (ClassCastException exception) {
throw new PropertyException(key, exception);
}
}
public void setSchema(Schema schema) {
- this.xmlMarshaller.setSchema(schema);
- }
-
- private HashMap<String, Class> getClassToGeneratedClasses() {
- return jaxbContext.getClassToGeneratedClasses();
- }
-
+ this.xmlMarshaller.setSchema(schema);
+ }
+
+ private Map<String, Class> getClassToGeneratedClasses() {
+ return jaxbContext.getClassToGeneratedClasses();
+ }
+
public JAXBContext getJaxbContext() {
return jaxbContext;
}
@@ -909,12 +968,16 @@ public class JAXBMarshaller implements javax.xml.bind.Marshaller {
}
public XMLMarshaller getXMLMarshaller() {
- return this.xmlMarshaller;
- }
-
- private static class CharacterEscapeHandlerWrapper extends org.eclipse.persistence.internal.oxm.record.CharacterEscapeHandlerWrapper implements CharacterEscapeHandler {
-
- public CharacterEscapeHandlerWrapper(Object sunHandler) {
+ return this.xmlMarshaller;
+ }
+
+ public Set<? extends ConstraintViolation<?>> getConstraintViolations() {
+ return beanValidator.getConstraintViolations();
+ }
+
+ private static class CharacterEscapeHandlerWrapper extends org.eclipse.persistence.internal.oxm.record.CharacterEscapeHandlerWrapper implements CharacterEscapeHandler {
+
+ public CharacterEscapeHandlerWrapper(Object sunHandler) {
super(sunHandler);
}
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBUnmarshaller.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBUnmarshaller.java
index c270b3b..07e709c 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBUnmarshaller.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBUnmarshaller.java
@@ -9,7 +9,8 @@
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
- * Marcel Valovy - 2.6.0 - added case insensitive unmarshalling property
+ * Marcel Valovy - 2.6.0 - added case insensitive unmarshalling property,
+ * added Bean Validation support.
******************************************************************************/
package org.eclipse.persistence.jaxb;
@@ -21,14 +22,17 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.StringTokenizer;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.PropertyException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.ValidatorFactory;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.PropertyException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.UnmarshallerHandler;
@@ -38,12 +42,13 @@ import javax.xml.bind.attachment.AttachmentUnmarshaller;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.Source;
-import javax.xml.validation.Schema;
-
-import org.w3c.dom.Node;
-import org.xml.sax.Attributes;
-import org.xml.sax.InputSource;
+import javax.xml.transform.Source;
+import javax.xml.validation.Schema;
+
+import org.eclipse.persistence.exceptions.BeanValidationException;
+import org.w3c.dom.Node;
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
@@ -65,14 +70,12 @@ import org.eclipse.persistence.internal.oxm.mappings.DirectCollectionMapping;
import org.eclipse.persistence.internal.oxm.record.namespaces.PrefixMapperNamespaceResolver;
import org.eclipse.persistence.internal.oxm.record.XMLEventReaderInputSource;
import org.eclipse.persistence.internal.oxm.record.XMLEventReaderReader;
-import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderInputSource;
-import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader;
-import org.eclipse.persistence.internal.sessions.AbstractSession;
-import org.eclipse.persistence.jaxb.JAXBErrorHandler;
-import org.eclipse.persistence.jaxb.JAXBUnmarshallerHandler;
-import org.eclipse.persistence.jaxb.JAXBContext.RootLevelXmlAdapter;
-import org.eclipse.persistence.jaxb.attachment.AttachmentUnmarshallerAdapter;
-import org.eclipse.persistence.internal.core.helper.CoreClassConstants;
+import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderInputSource;
+import org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader;
+import org.eclipse.persistence.internal.sessions.AbstractSession;
+import org.eclipse.persistence.jaxb.JAXBContext.RootLevelXmlAdapter;
+import org.eclipse.persistence.jaxb.attachment.AttachmentUnmarshallerAdapter;
+import org.eclipse.persistence.internal.core.helper.CoreClassConstants;
import org.eclipse.persistence.internal.jaxb.IDResolverWrapper;
import org.eclipse.persistence.internal.jaxb.ObjectGraphImpl;
import org.eclipse.persistence.internal.jaxb.WrappedValue;
@@ -94,117 +97,145 @@ import org.eclipse.persistence.internal.jaxb.many.ManyValue;
* @see javax.xml.bind.Unmarshaller
* @see org.eclipse.persistence.jaxb.UnmarshallerProperties
* @see org.eclipse.persistence.oxm.XMLUnmarshaller
- */
-public class JAXBUnmarshaller implements Unmarshaller {
-
- private ValidationEventHandler validationEventHandler;
- private XMLUnmarshaller xmlUnmarshaller;
- private JAXBContext jaxbContext;
- public static final String XML_JAVATYPE_ADAPTERS = "xml-javatype-adapters";
- public static final String STAX_SOURCE_CLASS_NAME = "javax.xml.transform.stax.StAXSource";
-
- private static final String SUN_ID_RESOLVER = "com.sun.xml.bind.IDResolver";
- private static final String SUN_JSE_ID_RESOLVER = "com.sun.xml.internal.bind.IDResolver";
-
- public JAXBUnmarshaller(XMLUnmarshaller newXMLUnmarshaller) {
- super();
- validationEventHandler = JAXBContext.DEFAULT_VALIDATION_EVENT_HANDER;
- xmlUnmarshaller = newXMLUnmarshaller;
- xmlUnmarshaller.setValidationMode(XMLUnmarshaller.NONVALIDATING);
- xmlUnmarshaller.setUnmarshalListener(new JAXBUnmarshalListener(this));
+ */
+public class JAXBUnmarshaller implements Unmarshaller {
+
+ private final JAXBBeanValidator beanValidator;
+
+ private BeanValidationMode beanValidationMode;
+ private ValidatorFactory preferredValidatorFactory;
+ private Class<?>[] beanValidationGroups = JAXBBeanValidator.DEFAULT_GROUP_ARRAY;
+
+ private ValidationEventHandler validationEventHandler;
+ private XMLUnmarshaller xmlUnmarshaller;
+ private JAXBContext jaxbContext;
+
+ public static final String XML_JAVATYPE_ADAPTERS = "xml-javatype-adapters";
+ public static final String STAX_SOURCE_CLASS_NAME = "javax.xml.transform.stax.StAXSource";
+
+ private static final String SUN_ID_RESOLVER = "com.sun.xml.bind.IDResolver";
+ private static final String SUN_JSE_ID_RESOLVER = "com.sun.xml.internal.bind.IDResolver";
+
+ public JAXBUnmarshaller(XMLUnmarshaller newXMLUnmarshaller) {
+ super();
+ validationEventHandler = JAXBContext.DEFAULT_VALIDATION_EVENT_HANDER;
+ beanValidationMode = BeanValidationMode.AUTO;
+ beanValidator = JAXBBeanValidator.getUnmarshallingBeanValidator();
+ xmlUnmarshaller = newXMLUnmarshaller;
+ xmlUnmarshaller.setValidationMode(XMLUnmarshaller.NONVALIDATING);
+ xmlUnmarshaller.setUnmarshalListener(new JAXBUnmarshalListener(this));
xmlUnmarshaller.setErrorHandler(new JAXBErrorHandler(validationEventHandler));
}
public XMLUnmarshaller getXMLUnmarshaller() {
return xmlUnmarshaller;
- }
-
- public Object unmarshal(File file) throws JAXBException {
- try {
- Object value = xmlUnmarshaller.unmarshal(file);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
- public Object unmarshal(InputStream inputStream) throws JAXBException {
- try {
- if (xmlUnmarshaller.isAutoDetectMediaType() || xmlUnmarshaller.getMediaType() == MediaType.APPLICATION_JSON || null == jaxbContext.getXMLInputFactory() || XMLUnmarshaller.NONVALIDATING != xmlUnmarshaller.getValidationMode()) {
- return createJAXBElementOrUnwrapIfRequired(xmlUnmarshaller.unmarshal(inputStream));
- } else {
- if (null == inputStream) {
- throw XMLMarshalException.nullArgumentException();
+ }
+
+ public Object unmarshal(File file) throws JAXBException {
+ try {
+ Object value = xmlUnmarshaller.unmarshal(file);
+ return validateAndTransformIfRequired(value); // xml object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
+
+
+ public Object unmarshal(InputStream inputStream) throws JAXBException {
+ try {
+ if (xmlUnmarshaller.isAutoDetectMediaType() || xmlUnmarshaller.getMediaType() == MediaType.APPLICATION_JSON || null == jaxbContext.getXMLInputFactory() || XMLUnmarshaller.NONVALIDATING != xmlUnmarshaller.getValidationMode()) {
+ return validateAndTransformIfRequired(xmlUnmarshaller.unmarshal(inputStream)); // xml bindings + object inside inputStream
+ } else {
+ if (null == inputStream) {
+ throw XMLMarshalException.nullArgumentException();
}
XMLStreamReader xmlStreamReader;
xmlStreamReader = jaxbContext.getXMLInputFactory().createXMLStreamReader(inputStream);
Object value = unmarshal(xmlStreamReader);
xmlStreamReader.close();
return value;
- }
- } catch(JAXBException jaxbException) {
- throw jaxbException;
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- } catch (Exception exception) {
+ }
+ } catch(JAXBException jaxbException) {
+ throw jaxbException;
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (Exception exception) {
throw new UnmarshalException(exception);
}
}
- public Object unmarshal(URL url) throws JAXBException {
- try {
- Object value = xmlUnmarshaller.unmarshal(url);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
- public Object unmarshal(InputSource inputSource) throws JAXBException {
- try {
- Object value = xmlUnmarshaller.unmarshal(inputSource);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
- public Object unmarshal(Reader reader) throws JAXBException {
-
- try {
- if (xmlUnmarshaller.isAutoDetectMediaType() || xmlUnmarshaller.getMediaType() == MediaType.APPLICATION_JSON || null == jaxbContext.getXMLInputFactory() || XMLUnmarshaller.NONVALIDATING != xmlUnmarshaller.getValidationMode()) {
-
- return createJAXBElementOrUnwrapIfRequired(xmlUnmarshaller.unmarshal(reader));
- } else {
- if (null == reader) {
- throw XMLMarshalException.nullArgumentException();
- }
+ public Object unmarshal(URL url) throws JAXBException {
+ try {
+ Object value = xmlUnmarshaller.unmarshal(url);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
+ public Object unmarshal(InputSource inputSource) throws JAXBException {
+ try {
+ Object value = xmlUnmarshaller.unmarshal(inputSource);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
+ public Object unmarshal(Reader reader) throws JAXBException {
+
+ try {
+ if (xmlUnmarshaller.isAutoDetectMediaType() || xmlUnmarshaller.getMediaType() == MediaType.APPLICATION_JSON || null == jaxbContext.getXMLInputFactory() || XMLUnmarshaller.NONVALIDATING != xmlUnmarshaller.getValidationMode()) {
+
+ return validateAndTransformIfRequired(xmlUnmarshaller.unmarshal(reader)); // xml bindings + object inside reader
+ } else {
+ if (null == reader) {
+ throw XMLMarshalException.nullArgumentException();
+ }
XMLStreamReader xmlStreamReader = jaxbContext.getXMLInputFactory().createXMLStreamReader(reader);
Object value = unmarshal(xmlStreamReader);
xmlStreamReader.close();
return value;
}
} catch(JAXBException jaxbException) {
- throw jaxbException;
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- } catch (Exception exception) {
- throw new UnmarshalException(exception);
- }
+ throw jaxbException;
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ } catch (Exception exception) {
+ throw new UnmarshalException(exception);
+ }
}
- public Object unmarshal(Node node) throws JAXBException {
- try {
- Object value = xmlUnmarshaller.unmarshal(node);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
- /**
- * Create a JAXBElement instance. If the object is an instance
- * of XMLRoot, we will use its field values to create the
+ public Object unmarshal(Node node) throws JAXBException {
+ try {
+ Object value = xmlUnmarshaller.unmarshal(node);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
+ private JAXBElement validateAndBuildJAXBElement(Object obj, Class declaredClass) throws BeanValidationException {
+ if (beanValidator.shouldValidate(obj, beanValidationMode, preferredValidatorFactory)) beanValidator.validate(obj, beanValidationGroups);
+ return buildJAXBElementFromObject(obj, declaredClass);
+ }
+
+ /**
+ * Create a JAXBElement instance. If the object is an instance
+ * of XMLRoot, we will use its field values to create the
* JAXBElement. If the object is not an XMLRoot instance, we
* will have to determine the 'name' value. This will be done
* using the object's descriptor default root element - any
@@ -223,13 +254,12 @@ public class JAXBUnmarshaller implements Unmarshaller {
jaxbElement.setNil(((Root)obj).isNil());
jaxbElement.setValue(null);
}
- return jaxbElement;
- }
-
-
- if(obj instanceof JAXBElement) {
- return (JAXBElement) obj;
- }
+ return jaxbElement;
+ }
+
+ if(obj instanceof JAXBElement) {
+ return (JAXBElement) obj;
+ }
// at this point, the default root element of the object being marshalled
// to == the root element - here we need to create a JAXBElement
@@ -256,15 +286,15 @@ public class JAXBUnmarshaller implements Unmarshaller {
if (rootNamespaceUri == null) {
qname = new QName(rootName);
} else {
- qname = new QName(rootNamespaceUri, rootName);
- }
- if(declaredClass != null){
- return jaxbContext.createJAXBElement(qname, declaredClass, obj);
- }else{
- return jaxbContext.createJAXBElement(qname, obj.getClass(), obj);
- }
- }
-
+ qname = new QName(rootNamespaceUri, rootName);
+ }
+ if(declaredClass != null){
+ return jaxbContext.createJAXBElement(qname, declaredClass, obj);
+ }else{
+ return jaxbContext.createJAXBElement(qname, obj.getClass(), obj);
+ }
+ }
+
public JAXBElement unmarshal(Node node, Class javaClass) throws JAXBException {
if(null == javaClass) {
throw new IllegalArgumentException();
@@ -274,35 +304,37 @@ public class JAXBUnmarshaller implements Unmarshaller {
if(jaxbContext.getArrayClassesToGeneratedClasses() != null) {
Class generatedClass = jaxbContext.getArrayClassesToGeneratedClasses().get(javaClass.getCanonicalName());
if(generatedClass != null){
- classToUnmarshalTo = generatedClass;
- }
- }
- return buildJAXBElementFromObject(xmlUnmarshaller.unmarshal(node, classToUnmarshalTo), javaClass);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
- public Object unmarshal(Source source) throws JAXBException {
- try {
- Object value = xmlUnmarshaller.unmarshal(source);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
+ classToUnmarshalTo = generatedClass;
+ }
+ }
+ return validateAndBuildJAXBElement(xmlUnmarshaller.unmarshal(node, classToUnmarshalTo), javaClass); // xmlbindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ }
}
+ public Object unmarshal(Source source) throws JAXBException {
+ try {
+ Object value = xmlUnmarshaller.unmarshal(source);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
public JAXBElement unmarshal(Source source, Class javaClass) throws JAXBException {
if(null == javaClass) {
- throw new IllegalArgumentException();
- }
- Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
-
- try {
- return buildJAXBElementFromObject(xmlUnmarshaller.unmarshal(source, classToUnmarshalTo), javaClass);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
+ throw new IllegalArgumentException();
+ }
+ Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
+
+ try {
+ return validateAndBuildJAXBElement(xmlUnmarshaller.unmarshal(source, classToUnmarshalTo), javaClass); // json object + xml bindings
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ }
}
private JAXBElement unmarshal(Source source, Class javaClass, Class declaredType) {
@@ -310,13 +342,13 @@ public class JAXBUnmarshaller implements Unmarshaller {
if(jaxbContext.getArrayClassesToGeneratedClasses() != null) {
Class generatedClass = jaxbContext.getArrayClassesToGeneratedClasses().get(javaClass.getCanonicalName());
if(generatedClass != null){
- classToUnmarshalTo = generatedClass;
- }
- }
- return buildJAXBElementFromObject(xmlUnmarshaller.unmarshal(source, classToUnmarshalTo), declaredType);
- }
-
- public JAXBElement unmarshal(Source source, Type type) throws JAXBException {
+ classToUnmarshalTo = generatedClass;
+ }
+ }
+ return validateAndBuildJAXBElement(xmlUnmarshaller.unmarshal(source, classToUnmarshalTo), declaredType); // never used in tests. (I guess its only for ParameterizedTypes)
+ }
+
+ public JAXBElement unmarshal(Source source, Type type) throws JAXBException {
if(null == type) {
throw new IllegalArgumentException();
}
@@ -406,21 +438,21 @@ public class JAXBUnmarshaller implements Unmarshaller {
PrimitiveContentHandler primitiveContentHandler = new PrimitiveContentHandler(javaClass);
staxReader.setContentHandler(primitiveContentHandler);
staxReader.parse(inputSource);
- return primitiveContentHandler.getJaxbElement();
- }
- Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
- JAXBElement unmarshalled = buildJAXBElementFromObject(xmlUnmarshaller.unmarshal(staxReader, inputSource, classToUnmarshalTo), javaClass);
-
- if(classToUnmarshalTo != javaClass){
- JAXBElement returnVal = new JAXBElement(unmarshalled.getName(), javaClass, unmarshalled.getScope(), unmarshalled.getValue());
+ return primitiveContentHandler.getJaxbElement();
+ }
+ Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
+ JAXBElement unmarshalled = validateAndBuildJAXBElement(xmlUnmarshaller.unmarshal(staxReader, inputSource, classToUnmarshalTo), javaClass); // xmlbindings + object (xmlelement) + "nomappings.SomeClass" + "jaxb.stax.EndEventRoot"
+
+ if(classToUnmarshalTo != javaClass){
+ JAXBElement returnVal = new JAXBElement(unmarshalled.getName(), javaClass, unmarshalled.getScope(), unmarshalled.getValue());
return returnVal;
- }
- return unmarshalled;
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- } catch (Exception e) {
- throw new JAXBException(e);
- }
+ }
+ return unmarshalled;
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException); // Exception [EclipseLink-25004] cvc-maxInclusive-valid: Value '1234567' is not facet-valid with respect to maxInclusive '999999' for type 'id-type'.
+ } catch (Exception e) {
+ throw new JAXBException(e);
+ }
}
public JAXBElement unmarshal(XMLStreamReader streamReader, Type type) throws JAXBException {
@@ -481,17 +513,17 @@ public class JAXBUnmarshaller implements Unmarshaller {
staxReader.parse(inputSource);
return primitiveArrayContentHandler.getJaxbElement();
}
- }
-
- if(null != xmlDescriptor && null == getSchema()) {
- RootLevelXmlAdapter adapter= null;
- if(jaxbContext.getTypeMappingInfoToJavaTypeAdapters().size() >0){
- adapter = jaxbContext.getTypeMappingInfoToJavaTypeAdapters().get(type);
- }
- UnmarshalRecord wrapper = (UnmarshalRecord) xmlDescriptor.getObjectBuilder().createRecord((AbstractSession) xmlUnmarshaller.getXMLContext().getSession());
- org.eclipse.persistence.internal.oxm.record.UnmarshalRecord unmarshalRecord = (org.eclipse.persistence.internal.oxm.record.UnmarshalRecord) wrapper.getUnmarshalRecord();
- XMLStreamReaderReader staxReader = new XMLStreamReaderReader(xmlUnmarshaller);
- unmarshalRecord.setUnmarshaller(xmlUnmarshaller);
+ }
+
+ if(null != xmlDescriptor && null == getSchema()) {
+ RootLevelXmlAdapter adapter= null;
+ if(jaxbContext.getTypeMappingInfoToJavaTypeAdapters().size() >0){
+ adapter = jaxbContext.getTypeMappingInfoToJavaTypeAdapters().get(type);
+ }
+ UnmarshalRecord wrapper = (UnmarshalRecord) xmlDescriptor.getObjectBuilder().createRecord((AbstractSession) xmlUnmarshaller.getXMLContext().getSession());
+ org.eclipse.persistence.internal.oxm.record.UnmarshalRecord unmarshalRecord = (org.eclipse.persistence.internal.oxm.record.UnmarshalRecord) wrapper.getUnmarshalRecord();
+ XMLStreamReaderReader staxReader = new XMLStreamReaderReader(xmlUnmarshaller);
+ unmarshalRecord.setUnmarshaller(xmlUnmarshaller);
unmarshalRecord.setXMLReader(staxReader);
staxReader.setContentHandler(unmarshalRecord);
staxReader.parse(streamReader);
@@ -499,17 +531,17 @@ public class JAXBUnmarshaller implements Unmarshaller {
if(unmarshalRecord.isNil()) {
value = null;
} else {
- value = unmarshalRecord.getCurrentObject();
- }
- if(value instanceof WrappedValue){
- value = ((WrappedValue)value).getValue();
- }
-
- if(value instanceof ManyValue){
- value = ((ManyValue)value).getItem();
- }
- if(adapter != null) {
- try {
+ value = unmarshalRecord.getCurrentObject();
+ }
+ if(value instanceof WrappedValue){
+ value = ((WrappedValue)value).getValue();
+ }
+
+ if(value instanceof ManyValue){
+ value = ((ManyValue)value).getItem();
+ }
+ if(adapter != null) {
+ try {
value = adapter.getXmlAdapter().unmarshal(value);
} catch(Exception ex) {
throw new JAXBException(XMLMarshalException.marshalException(ex));
@@ -525,20 +557,20 @@ public class JAXBUnmarshaller implements Unmarshaller {
}
if(jaxbContext.getTypeMappingInfoToGeneratedType() == null) {
return unmarshal(streamReader, type.getType());
- }
- RootLevelXmlAdapter adapter= null;
- if(jaxbContext.getTypeMappingInfoToJavaTypeAdapters().size() >0){
- adapter = jaxbContext.getTypeMappingInfoToJavaTypeAdapters().get(type);
- }
- Class unmarshalClass = null;
- if(jaxbContext.getTypeMappingInfoToGeneratedType().size() >0){
- unmarshalClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(type);
- }
-
- if(unmarshalClass != null){
- JAXBElement unmarshalled = unmarshal(streamReader, unmarshalClass);
- Class declaredClass = null;
- if(type.getType() instanceof Class){
+ }
+ RootLevelXmlAdapter adapter= null;
+ if(jaxbContext.getTypeMappingInfoToJavaTypeAdapters().size() >0){
+ adapter = jaxbContext.getTypeMappingInfoToJavaTypeAdapters().get(type);
+ }
+ Class unmarshalClass = null;
+ if(jaxbContext.getTypeMappingInfoToGeneratedType().size() >0){
+ unmarshalClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(type);
+ }
+
+ if(unmarshalClass != null){
+ JAXBElement unmarshalled = unmarshal(streamReader, unmarshalClass);
+ Class declaredClass = null;
+ if(type.getType() instanceof Class){
declaredClass = (Class)type.getType();
}else{
declaredClass = Object.class;
@@ -581,27 +613,29 @@ public class JAXBUnmarshaller implements Unmarshaller {
throw new IllegalArgumentException();
}
try {
- XMLStreamReaderReader staxReader = new XMLStreamReaderReader(xmlUnmarshaller);
- XMLStreamReaderInputSource inputSource = new XMLStreamReaderInputSource(streamReader);
- Object value = xmlUnmarshaller.unmarshal(staxReader, inputSource);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
+ XMLStreamReaderReader staxReader = new XMLStreamReaderReader(xmlUnmarshaller);
+ XMLStreamReaderInputSource inputSource = new XMLStreamReaderInputSource(streamReader);
+ Object value = xmlUnmarshaller.unmarshal(staxReader, inputSource);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
public JAXBElement unmarshal(XMLEventReader eventReader, Class javaClass) throws JAXBException {
if(null == eventReader || null == javaClass) {
throw new IllegalArgumentException();
}
try {
- Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
- XMLEventReaderReader staxReader = new XMLEventReaderReader(xmlUnmarshaller);
- XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(eventReader);
- JAXBElement unmarshalled = buildJAXBElementFromObject(xmlUnmarshaller.unmarshal(staxReader, inputSource, classToUnmarshalTo), javaClass);
-
- if(classToUnmarshalTo != javaClass){
- JAXBElement returnVal = new JAXBElement(unmarshalled.getName(), javaClass, unmarshalled.getScope(), unmarshalled.getValue());
+ Class classToUnmarshalTo = getClassToUnmarshalTo(javaClass);
+ XMLEventReaderReader staxReader = new XMLEventReaderReader(xmlUnmarshaller);
+ XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(eventReader);
+ JAXBElement unmarshalled = validateAndBuildJAXBElement(xmlUnmarshaller.unmarshal(staxReader, inputSource, classToUnmarshalTo), javaClass); // json object + xml bindings
+
+ if(classToUnmarshalTo != javaClass){
+ JAXBElement returnVal = new JAXBElement(unmarshalled.getName(), javaClass, unmarshalled.getScope(), unmarshalled.getValue());
return returnVal;
}
return unmarshalled;
@@ -697,15 +731,17 @@ public class JAXBUnmarshaller implements Unmarshaller {
throw new IllegalArgumentException();
}
try {
- XMLEventReaderReader staxReader = new XMLEventReaderReader(xmlUnmarshaller);
- XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(eventReader);
- Object value = xmlUnmarshaller.unmarshal(staxReader, inputSource);
- return createJAXBElementOrUnwrapIfRequired(value);
- } catch (XMLMarshalException xmlMarshalException) {
- throw handleXMLMarshalException(xmlMarshalException);
- }
- }
-
+ XMLEventReaderReader staxReader = new XMLEventReaderReader(xmlUnmarshaller);
+ XMLEventReaderInputSource inputSource = new XMLEventReaderInputSource(eventReader);
+ Object value = xmlUnmarshaller.unmarshal(staxReader, inputSource);
+ return validateAndTransformIfRequired(value); // xml bindings + object
+ } catch (XMLMarshalException xmlMarshalException) {
+ throw handleXMLMarshalException(xmlMarshalException);
+ } catch (BeanValidationException bve) {
+ throw new UnmarshalException(bve.getMessage(), String.valueOf(bve.getErrorCode()), bve);
+ }
+ }
+
public UnmarshallerHandler getUnmarshallerHandler() {
return new JAXBUnmarshallerHandler(this);
}
@@ -749,10 +785,10 @@ public class JAXBUnmarshaller implements Unmarshaller {
if(value instanceof MediaType) {
mType = (MediaType) value;
} else if(value instanceof String) {
- mType = MediaType.getMediaType((String)value);
- }
+ mType = MediaType.getMediaType((String)value);
+ }
if(mType == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
+ throw new PropertyException(key, Constants.EMPTY_STRING);
}
xmlUnmarshaller.setMediaType(mType);
} else if (key.equals(UnmarshallerProperties.UNMARSHALLING_CASE_INSENSITIVE)){
@@ -761,60 +797,75 @@ public class JAXBUnmarshaller implements Unmarshaller {
}
xmlUnmarshaller.setCaseInsensitive((Boolean)value);
} else if (key.equals(UnmarshallerProperties.AUTO_DETECT_MEDIA_TYPE)){
- if(value == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
- }
- xmlUnmarshaller.setAutoDetectMediaType((Boolean)value);
- } else if (key.equals(UnmarshallerProperties.JSON_ATTRIBUTE_PREFIX)){
- xmlUnmarshaller.setAttributePrefix((String)value);
- } else if (UnmarshallerProperties.JSON_INCLUDE_ROOT.equals(key)) {
- if(value == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
- }
- xmlUnmarshaller.setIncludeRoot((Boolean)value);
- } else if (UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER.equals(key)){
- if (value == null){
- xmlUnmarshaller.setNamespaceResolver(null);
- } else if (value instanceof Map){
- Map<String, String> namespaces = (Map<String, String>)value;
- NamespaceResolver nr = new NamespaceResolver();
- Iterator<Entry<String, String>> namesapcesIter = namespaces.entrySet().iterator();
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ xmlUnmarshaller.setAutoDetectMediaType((Boolean)value);
+ } else if (key.equals(UnmarshallerProperties.JSON_ATTRIBUTE_PREFIX)){
+ xmlUnmarshaller.setAttributePrefix((String)value);
+ } else if (UnmarshallerProperties.JSON_INCLUDE_ROOT.equals(key)) {
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ xmlUnmarshaller.setIncludeRoot((Boolean)value);
+ } else if (UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER.equals(key)){
+ if (value == null){
+ xmlUnmarshaller.setNamespaceResolver(null);
+ } else if (value instanceof Map){
+ Map<String, String> namespaces = (Map<String, String>)value;
+ NamespaceResolver nr = new NamespaceResolver();
+ Iterator<Entry<String, String>> namesapcesIter = namespaces.entrySet().iterator();
for (int i=0;i<namespaces.size(); i++){
Entry<String, String> nextEntry = namesapcesIter.next();
nr.put(nextEntry.getValue(), nextEntry.getKey());
- }
- xmlUnmarshaller.setNamespaceResolver(nr);
- } else if (value instanceof NamespacePrefixMapper){
- xmlUnmarshaller.setNamespaceResolver(new PrefixMapperNamespaceResolver((NamespacePrefixMapper)value, null));
- }
- } else if (UnmarshallerProperties.JSON_VALUE_WRAPPER.equals(key)){
- xmlUnmarshaller.setValueWrapper((String)value);
- } else if (UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR.equals(key)){
- if(value == null){
- throw new PropertyException(key, Constants.EMPTY_STRING);
- }
- xmlUnmarshaller.setNamespaceSeparator((Character)value);
- } else if (UnmarshallerProperties.ID_RESOLVER.equals(key)) {
- setIDResolver((IDResolver) value);
- } else if (SUN_ID_RESOLVER.equals(key) || SUN_JSE_ID_RESOLVER.equals(key)) {
- if(value == null){
- setIDResolver(null);
- }else {
- setIDResolver(new IDResolverWrapper(value));
- }
- } else if (UnmarshallerProperties.OBJECT_GRAPH.equals(key)) {
- if(value instanceof ObjectGraphImpl) {
- xmlUnmarshaller.setUnmarshalAttributeGroup(((ObjectGraphImpl)value).getAttributeGroup());
- } else if(value instanceof String || value == null) {
- xmlUnmarshaller.setUnmarshalAttributeGroup(value);
- } else {
+ }
+ xmlUnmarshaller.setNamespaceResolver(nr);
+ } else if (value instanceof NamespacePrefixMapper){
+ xmlUnmarshaller.setNamespaceResolver(new PrefixMapperNamespaceResolver((NamespacePrefixMapper)value, null));
+ }
+ } else if (UnmarshallerProperties.JSON_VALUE_WRAPPER.equals(key)){
+ xmlUnmarshaller.setValueWrapper((String)value);
+ } else if (UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR.equals(key)){
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ xmlUnmarshaller.setNamespaceSeparator((Character)value);
+ } else if (UnmarshallerProperties.ID_RESOLVER.equals(key)) {
+ setIDResolver((IDResolver) value);
+ } else if (SUN_ID_RESOLVER.equals(key) || SUN_JSE_ID_RESOLVER.equals(key)) {
+ if(value == null){
+ setIDResolver(null);
+ }else {
+ setIDResolver(new IDResolverWrapper(value));
+ }
+ } else if (UnmarshallerProperties.OBJECT_GRAPH.equals(key)) {
+ if(value instanceof ObjectGraphImpl) {
+ xmlUnmarshaller.setUnmarshalAttributeGroup(((ObjectGraphImpl) value).getAttributeGroup());
+ } else if(value instanceof String || value == null) {
+ xmlUnmarshaller.setUnmarshalAttributeGroup(value);
+ } else {
throw org.eclipse.persistence.exceptions.JAXBException.invalidValueForObjectGraph(value);
- }
- } else if (UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME.equals(key)) {
- xmlUnmarshaller.setWrapperAsCollectionName((Boolean) value);
- } else {
- throw new PropertyException(key, value);
- }
+ }
+ } else if (UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME.equals(key)) {
+ xmlUnmarshaller.setWrapperAsCollectionName((Boolean) value);
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_MODE.equals(key)){
+ if(value == null){
+ throw new PropertyException(key, Constants.EMPTY_STRING);
+ }
+ this.beanValidationMode = ((BeanValidationMode) value);
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_FACTORY.equals(key)) {
+ if(value == null){
+ // Allow null value for preferred validation factory.
+ }
+ this.preferredValidatorFactory = ((ValidatorFactory)value);
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_GROUPS.equals(key)) {
+ if(value == null){
+ // Allow null value for preferred validation factory.
+ }
+ this.beanValidationGroups = ((Class<?>[]) value);
+ } else {
+ throw new PropertyException(key, value);
+ }
}
/**
@@ -837,15 +888,15 @@ public class JAXBUnmarshaller implements Unmarshaller {
return xmlUnmarshaller.getAttributePrefix();
} else if (key.equals(UnmarshallerProperties.JSON_INCLUDE_ROOT)) {
return xmlUnmarshaller.isIncludeRoot();
- } else if (key.equals(UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR)) {
- return xmlUnmarshaller.getNamespaceSeparator();
- } else if (key.equals(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER)) {
- if(xmlUnmarshaller.getNamespaceResolver() == null){
- return null;
- }
- if (xmlUnmarshaller.getNamespaceResolver() instanceof PrefixMapperNamespaceResolver) {
- PrefixMapperNamespaceResolver wrapper = (PrefixMapperNamespaceResolver) xmlUnmarshaller.getNamespaceResolver();
- return wrapper.getPrefixMapper();
+ } else if (key.equals(UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR)) {
+ return xmlUnmarshaller.getNamespaceSeparator();
+ } else if (key.equals(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER)) {
+ if(xmlUnmarshaller.getNamespaceResolver() == null){
+ return null;
+ }
+ if (xmlUnmarshaller.getNamespaceResolver() instanceof PrefixMapperNamespaceResolver) {
+ PrefixMapperNamespaceResolver wrapper = (PrefixMapperNamespaceResolver) xmlUnmarshaller.getNamespaceResolver();
+ return wrapper.getPrefixMapper();
} else {
Map<String, String> nsMap = new HashMap<String, String>();
Map<String, String> prefixesToNS = xmlUnmarshaller.getNamespaceResolver().getPrefixesToNamespaces();
@@ -861,23 +912,29 @@ public class JAXBUnmarshaller implements Unmarshaller {
return xmlUnmarshaller.getValueWrapper();
} else if (UnmarshallerProperties.ID_RESOLVER.equals(key)) {
return xmlUnmarshaller.getIDResolver();
- } else if (SUN_ID_RESOLVER.equals(key) || SUN_JSE_ID_RESOLVER.equals(key)) {
- IDResolverWrapper wrapper = (IDResolverWrapper) xmlUnmarshaller.getIDResolver();
- if(wrapper == null){
- return null;
- }
- return wrapper.getResolver();
- } else if (UnmarshallerProperties.OBJECT_GRAPH.equals(key)) {
+ } else if (SUN_ID_RESOLVER.equals(key) || SUN_JSE_ID_RESOLVER.equals(key)) {
+ IDResolverWrapper wrapper = (IDResolverWrapper) xmlUnmarshaller.getIDResolver();
+ if(wrapper == null){
+ return null;
+ }
+ return wrapper.getResolver();
+ } else if (UnmarshallerProperties.OBJECT_GRAPH.equals(key)) {
Object graph = xmlUnmarshaller.getUnmarshalAttributeGroup();
if(graph instanceof CoreAttributeGroup) {
return new ObjectGraphImpl((CoreAttributeGroup)graph);
}
- return graph;
- } else if(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME.equals(key)) {
- return xmlUnmarshaller.isWrapperAsCollectionName();
- }
- throw new PropertyException(key);
- }
+ return graph;
+ } else if(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME.equals(key)) {
+ return xmlUnmarshaller.isWrapperAsCollectionName();
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_MODE.equals(key)) {
+ return this.beanValidationMode;
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_FACTORY.equals(key)) {
+ return this.preferredValidatorFactory;
+ } else if (UnmarshallerProperties.BEAN_VALIDATION_GROUPS.equals(key)) {
+ return this.beanValidationGroups;
+ }
+ throw new PropertyException(key);
+ }
public Unmarshaller.Listener getListener() {
return ((JAXBUnmarshalListener)xmlUnmarshaller.getUnmarshalListener()).getListener();
@@ -928,17 +985,22 @@ public class JAXBUnmarshaller implements Unmarshaller {
xmlUnmarshaller.setAttachmentUnmarshaller(null);
} else {
xmlUnmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerAdapter(unmarshaller));
- }
- }
-
- public void setUnmarshalCallbacks(java.util.HashMap callbacks) {
- ((JAXBUnmarshalListener)xmlUnmarshaller.getUnmarshalListener()).setClassBasedUnmarshalEvents(callbacks);
- }
-
- private Object createJAXBElementOrUnwrapIfRequired(Object value){
- if(value instanceof Root){
- JAXBElement jaxbElement = jaxbContext.createJAXBElementFromXMLRoot((Root)value, Object.class);
- jaxbElement.setNil(((Root) value).isNil());
+ }
+ }
+
+ public void setUnmarshalCallbacks(Map callbacks) {
+ ((JAXBUnmarshalListener)xmlUnmarshaller.getUnmarshalListener()).setClassBasedUnmarshalEvents(callbacks);
+ }
+
+ private Object validateAndTransformIfRequired(Object value) throws BeanValidationException {
+ if (beanValidator.shouldValidate(value, beanValidationMode, preferredValidatorFactory)) beanValidator.validate(value, beanValidationGroups);
+ return createJAXBElementOrUnwrapIfRequired(value);
+ }
+
+ private Object createJAXBElementOrUnwrapIfRequired(Object value) {
+ if(value instanceof Root){
+ JAXBElement jaxbElement = jaxbContext.createJAXBElementFromXMLRoot((Root)value, Object.class);
+ jaxbElement.setNil(((Root) value).isNil());
return jaxbElement;
} else if(value instanceof WrappedValue) {
return ((WrappedValue)value).getValue();
@@ -967,53 +1029,57 @@ public class JAXBUnmarshaller implements Unmarshaller {
Class generatedClass = jaxbContext.getCollectionClassesToGeneratedClasses().get(originalClass);
if(generatedClass != null){
classToUnmarshalTo = generatedClass;
- }
- }
- if(jaxbContext.getTypeToTypeMappingInfo() != null){
- TypeMappingInfo tmi = jaxbContext.getTypeToTypeMappingInfo().get(originalClass);
- if(tmi != null && jaxbContext.getTypeMappingInfoToGeneratedType() != null) {
- Class generatedClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(tmi);
- if(generatedClass != null){
- classToUnmarshalTo = generatedClass;
- }
- }
- }
- return classToUnmarshalTo;
- }
+ }
+ }
+ if(jaxbContext.getTypeToTypeMappingInfo() != null){
+ TypeMappingInfo tmi = jaxbContext.getTypeToTypeMappingInfo().get(originalClass);
+ if(tmi != null && jaxbContext.getTypeMappingInfoToGeneratedType() != null) {
+ Class generatedClass = jaxbContext.getTypeMappingInfoToGeneratedType().get(tmi);
+ if(generatedClass != null){
+ classToUnmarshalTo = generatedClass;
+ }
+ }
+ }
+ return classToUnmarshalTo;
+ }
private JAXBException handleXMLMarshalException(XMLMarshalException xmlMarshalException) {
if(xmlMarshalException.getErrorCode() == XMLMarshalException.NULL_ARGUMENT) {
throw new IllegalArgumentException(xmlMarshalException);
- } else {
- return new UnmarshalException(xmlMarshalException);
- }
- }
-
-
- /**
- * Return this Unmarshaller's custom IDResolver.
- *
- * @see IDResolver
- * @since 2.3.3
- * @return the custom IDResolver, or null if one has not been specified.
+ } else {
+ return new UnmarshalException(xmlMarshalException);
+ }
+ }
+
+
+ /**
+ * Return this Unmarshaller's custom IDResolver.
+ *
+ * @see IDResolver
+ * @since 2.3.3
+ * @return the custom IDResolver, or null if one has not been specified.
*/
public IDResolver getIDResolver() {
return getXMLUnmarshaller().getIDResolver();
}
-
- /**
- * Set this Unmarshaller's custom IDResolver.
- *
- * @see IDResolver
- * @since 2.3.3
- */
+
+ /**
+ * Set this Unmarshaller's custom IDResolver.
+ *
+ * @see IDResolver
+ * @since 2.3.3
+ */
public void setIDResolver(IDResolver idResolver) {
- getXMLUnmarshaller().setIDResolver(idResolver);
- }
-
- private static class PrimitiveContentHandler<T> extends DefaultHandler {
-
- private Class<T> clazz;
+ getXMLUnmarshaller().setIDResolver(idResolver);
+ }
+
+ public Set<? extends ConstraintViolation<?>> getConstraintViolations() {
+ return beanValidator.getConstraintViolations();
+ }
+
+ private static class PrimitiveContentHandler<T> extends DefaultHandler {
+
+ private Class<T> clazz;
private JAXBElement<T> jaxbElement;
private Map<String, String> namespaces = new HashMap<String, String>(3);
private StringBuilder stringBuilder = new StringBuilder();
@@ -1039,26 +1105,26 @@ public class JAXBUnmarshaller implements Unmarshaller {
value = (T) xcm.convertObject(stringBuilder.toString(), clazz, Constants.BASE_64_BINARY_QNAME);
} else {
value = (T) xcm.convertObject(stringBuilder.toString(), clazz);
- }
- } else {
- int colonIndex = xsiType.indexOf(':');
-
- String typePrefix;
- String typeName;
- if(colonIndex == -1) {
+ }
+ } else {
+ int colonIndex = xsiType.indexOf(':');
+
+ String typePrefix;
+ String typeName;
+ if(colonIndex == -1) {
typePrefix = Constants.EMPTY_STRING;
typeName = xsiType;
} else {
typePrefix = xsiType.substring(0, colonIndex);
typeName = xsiType.substring(colonIndex + 1);
}
- String typeNamespace = namespaces.get(typePrefix);
- QName typeQName = new QName(typeNamespace, typeName);
- value = (T) xcm.convertObject(stringBuilder.toString(), clazz, typeQName);
-
- }
-
- QName qName;
+ String typeNamespace = namespaces.get(typePrefix);
+ QName typeQName = new QName(typeNamespace, typeName);
+ value = (T) xcm.convertObject(stringBuilder.toString(), clazz, typeQName);
+
+ }
+
+ QName qName;
if(namespaceURI != null && namespaceURI.length() == 0) {
qName = new QName(qualifiedName);
} else {
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/MarshallerProperties.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/MarshallerProperties.java
index 998e254..d8185dd 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/MarshallerProperties.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/MarshallerProperties.java
@@ -6,12 +6,14 @@
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
- * Blaise Doughan - 2.3.3 - initial implementation
- ******************************************************************************/
-package org.eclipse.persistence.jaxb;
-
+ *
+ * Contributors:
+ * Blaise Doughan - 2.3.3 - initial implementation
+ * Marcel Valovy - 2.6 - added case insensitive unmarshalling property
+ * - added bean validation related properties
+ ******************************************************************************/
+package org.eclipse.persistence.jaxb;
+
/**
* These are properties that may be set on an instance of Marshaller. Below is
* an example of using the property mechanism to enable MOXy's JSON binding for
@@ -184,7 +186,34 @@ public class MarshallerProperties {
* @since 2.4.2
* @see org.eclipse.persistence.jaxb.JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME
* @see org.eclipse.persistence.jaxb.UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME
- */
- public static final String JSON_WRAPPER_AS_ARRAY_NAME = JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME;
-
+ */
+ public static final String JSON_WRAPPER_AS_ARRAY_NAME = JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME;
+
+ /**
+ * Property for setting bean validation mode.
+ * Valid values {@link BeanValidationMode#AUTO} (default),{@link BeanValidationMode#CALLBACK}, {@link BeanValidationMode#NONE}.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_MODE
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_MODE
+ */
+ public static final String BEAN_VALIDATION_MODE = JAXBContextProperties.BEAN_VALIDATION_MODE;
+
+ /**
+ * Property for setting preferred or custom validator factory. Must implement javax.validation.ValidatorFactory.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_FACTORY
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_FACTORY
+ */
+ public static final String BEAN_VALIDATION_FACTORY = JAXBContextProperties.BEAN_VALIDATION_FACTORY;
+
+ /**
+ * Allows to set bean validation target groups. Must be of type Class<?>[].
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_GROUPS
+ * @see org.eclipse.persistence.jaxb.UnmarshallerProperties#BEAN_VALIDATION_GROUPS
+ */
+ public static final String BEAN_VALIDATION_GROUPS = JAXBContextProperties.BEAN_VALIDATION_GROUPS;
} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/UnmarshallerProperties.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/UnmarshallerProperties.java
index 1acd726..7d19ee7 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/UnmarshallerProperties.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/UnmarshallerProperties.java
@@ -9,7 +9,8 @@
*
* Contributors:
* Blaise Doughan - 2.3.3 - initial implementation
- * Marcel Valovy - 2.6.0 - added case insensitive unmarshalling property
+ * Marcel Valovy - 2.6 - added case insensitive unmarshalling property
+ * - added bean validation related properties
******************************************************************************/
package org.eclipse.persistence.jaxb;
@@ -203,6 +204,34 @@ public class UnmarshallerProperties {
* @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=331241">EclipseLink Forum, Bug 331241.</a>
* @see org.eclipse.persistence.jaxb.JAXBContextProperties#UNMARSHALLING_CASE_INSENSITIVE
*/
- public static final String UNMARSHALLING_CASE_INSENSITIVE = "eclipselink.unmarshalling.case-insensitive";
+ public static final String UNMARSHALLING_CASE_INSENSITIVE = JAXBContextProperties.UNMARSHALLING_CASE_INSENSITIVE;
+
+ /**
+ * Property for setting bean validation mode.
+ * Valid values {@link BeanValidationMode#AUTO} (default),{@link BeanValidationMode#CALLBACK}, {@link BeanValidationMode#NONE}.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_MODE
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_MODE
+ */
+ public static final String BEAN_VALIDATION_MODE = JAXBContextProperties.BEAN_VALIDATION_MODE;
+
+ /**
+ * Property for setting preferred or custom validator factory. Must implement javax.validation.ValidatorFactory.
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_FACTORY
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_FACTORY
+ */
+ public static final String BEAN_VALIDATION_FACTORY = JAXBContextProperties.BEAN_VALIDATION_FACTORY;
+
+ /**
+ * Property for setting bean validation target groups. Must be of type Class<?>[].
+ *
+ * @since 2.6
+ * @see org.eclipse.persistence.jaxb.JAXBContextProperties#BEAN_VALIDATION_GROUPS
+ * @see org.eclipse.persistence.jaxb.MarshallerProperties#BEAN_VALIDATION_GROUPS
+ */
+ public static final String BEAN_VALIDATION_GROUPS = JAXBContextProperties.BEAN_VALIDATION_GROUPS;
} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/AnnotationsProcessor.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/AnnotationsProcessor.java
index eed443d..1fe5aea 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/AnnotationsProcessor.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/AnnotationsProcessor.java
@@ -3,11 +3,11 @@
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
- * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
- * and the Eclipse Distribution License is available at
- * http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.jaxb.compiler;
@@ -27,13 +27,12 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.bind.annotation.XmlAccessorOrder;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
@@ -90,14 +89,30 @@ import org.eclipse.persistence.internal.libraries.asm.Label;
import org.eclipse.persistence.internal.libraries.asm.Type;
import org.eclipse.persistence.internal.oxm.Constants;
import org.eclipse.persistence.internal.oxm.Namespace;
-import org.eclipse.persistence.internal.oxm.XMLConversionManager;
-import org.eclipse.persistence.internal.oxm.XPathFragment;
-import org.eclipse.persistence.internal.oxm.mappings.Field;
-import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
-import org.eclipse.persistence.jaxb.TypeMappingInfo;
-import org.eclipse.persistence.jaxb.javamodel.AnnotationProxy;
-import org.eclipse.persistence.jaxb.javamodel.Helper;
-import org.eclipse.persistence.jaxb.javamodel.JavaAnnotation;
+import org.eclipse.persistence.internal.oxm.XMLConversionManager;
+import org.eclipse.persistence.internal.oxm.XPathFragment;
+import org.eclipse.persistence.internal.oxm.mappings.Field;
+import org.eclipse.persistence.jaxb.compiler.facets.DecimalMaxFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.DecimalMinFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.DigitsFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.MaxFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.MinFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.PatternFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.PatternListFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.SizeFacet;
+import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
+import org.eclipse.persistence.jaxb.TypeMappingInfo;
+import javax.validation.constraints.DecimalMax;
+import javax.validation.constraints.DecimalMin;
+import javax.validation.constraints.Digits;
+import javax.validation.constraints.Max;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import org.eclipse.persistence.jaxb.javamodel.AnnotationProxy;
+import org.eclipse.persistence.jaxb.javamodel.Helper;
+import org.eclipse.persistence.jaxb.javamodel.JavaAnnotation;
import org.eclipse.persistence.jaxb.javamodel.JavaClass;
import org.eclipse.persistence.jaxb.javamodel.JavaConstructor;
import org.eclipse.persistence.jaxb.javamodel.JavaField;
@@ -162,18 +177,18 @@ import org.eclipse.persistence.oxm.annotations.XmlWriteTransformers;
* <li>Centralize processing which is common to both Schema Generation and
* Mapping Generation tasks</li>
* <p>
- * This class does the initial processing of the JAXB 2.0 Generation. It
- * generates meta data that can be used by the later Schema Generation and
- * Mapping Generation steps.
- *
- * @see org.eclipse.persistence.jaxb.compiler.Generator
- * @author mmacivor
- * @since Oracle TopLink 11.1.1.0.0
- */
-public class AnnotationsProcessor {
- static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler";
- static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart";
- private static final String JAVAX_XML_BIND_JAXBELEMENT = "javax.xml.bind.JAXBElement";
+ * This class does the initial processing of the JAXB 2.0 Generation. It
+ * generates meta data that can be used by the later Schema Generation and
+ * Mapping Generation steps.
+ *
+ * @see org.eclipse.persistence.jaxb.compiler.Generator
+ * @author mmacivor
+ * @since Oracle TopLink 11.1.1.0.0
+ */
+public final class AnnotationsProcessor {
+ static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler";
+ static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart";
+ private static final String JAVAX_XML_BIND_JAXBELEMENT = "javax.xml.bind.JAXBElement";
private static final String JAVAX_XML_BIND_ANNOTATION = "javax.xml.bind.annotation";
private static final String OXM_ANNOTATIONS = "org.eclipse.persistence.oxm.annotations";
private static final String TYPE_METHOD_NAME = "type";
@@ -197,114 +212,114 @@ public class AnnotationsProcessor {
private static final String GET_STR = "get";
private static final String SET_STR = "set";
private static final Character DOT_CHR = '.';
- private static final Character DOLLAR_SIGN_CHR = '$';
- private static final Character SLASH_CHR = '/';
-
- private ArrayList<JavaClass> typeInfoClasses;
- private HashMap<String, PackageInfo> packageToPackageInfoMappings;
- private HashMap<String, MarshalCallback> marshalCallbacks;
- private HashMap<String, QName> userDefinedSchemaTypes;
- private HashMap<String, TypeInfo> typeInfo;
- private ArrayList<QName> typeQNames;
- private HashMap<String, UnmarshalCallback> unmarshalCallbacks;
- private HashMap<String, HashMap<QName, ElementDeclaration>> elementDeclarations;
- private HashMap<String, ElementDeclaration> xmlRootElements;
- private List<ElementDeclaration> localElements;
- private HashMap<String, JavaMethod> factoryMethods;
- private Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry> xmlRegistries;
- private List<String> objectFactoryClassNames;
- private List<JavaClass> classesToProcessPropertyTypes;
+ private static final Character DOLLAR_SIGN_CHR = '$';
+ private static final Character SLASH_CHR = '/';
+
+ private List<JavaClass> typeInfoClasses;
+ private Map<String, PackageInfo> packageToPackageInfoMappings;
+ private Map<String, MarshalCallback> marshalCallbacks;
+ private Map<String, QName> userDefinedSchemaTypes;
+ private Map<String, TypeInfo> typeInfos;
+ private List<QName> typeQNames;
+ private Map<String, UnmarshalCallback> unmarshalCallbacks;
+ private Map<String, Map<QName, ElementDeclaration>> elementDeclarations;
+ private Map<String, ElementDeclaration> xmlRootElements;
+ private List<ElementDeclaration> localElements;
+ private Map<String, JavaMethod> factoryMethods;
+ private Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry> xmlRegistries;
+ private List<String> objectFactoryClassNames;
+ private List<JavaClass> classesToProcessPropertyTypes;
private Map<String, Class> arrayClassesToGeneratedClasses;
- private Map<Class, JavaClass> generatedClassesToArrayClasses;
- private Map<java.lang.reflect.Type, Class> collectionClassesToGeneratedClasses;
- private Map<Class, java.lang.reflect.Type> generatedClassesToCollectionClasses;
-
- private Map<JavaClass, List<TypeMappingInfo>> javaClassToTypeMappingInfos;
- private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses;
- private Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses;
- private Map<TypeMappingInfo, QName> typeMappingInfoToSchemaType;
-
- private Helper helper;
- private String defaultTargetNamespace;
+ private Map<Class, JavaClass> generatedClassesToArrayClasses;
+ private Map<java.lang.reflect.Type, Class> collectionClassesToGeneratedClasses;
+ private Map<Class, java.lang.reflect.Type> generatedClassesToCollectionClasses;
+ private Map<JavaClass, List<TypeMappingInfo>> javaClassToTypeMappingInfos;
+ private Map<TypeMappingInfo, Class> typeMappingInfosToGeneratedClasses;
+ private Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses;
+ private Map<TypeMappingInfo, QName> typeMappingInfosToSchemaTypes;
+
+ private Helper helper;
+ private String defaultTargetNamespace;
private JAXBMetadataLogger logger;
private boolean isDefaultNamespaceAllowed;
- private boolean xmlAccessorFactorySupport;
-
- private boolean hasSwaRef;
-
- private List<String> referencedByTransformer;
- private boolean hasXmlBindings = false;
-
- public AnnotationsProcessor(Helper helper) {
- this.helper = helper;
- isDefaultNamespaceAllowed = true;
- hasSwaRef = false;
- }
+ private boolean xmlAccessorFactorySupport;
+
+ private boolean hasSwaRef;
+
+ private List<String> referencedByTransformer;
+ private boolean hasXmlBindings = false;
+ private boolean facets;
+
+ public AnnotationsProcessor(Helper helper) {
+ this.helper = helper;
+ this.facets = helper.isFacets();
+ isDefaultNamespaceAllowed = true;
+ hasSwaRef = false;
+ }
/**
* This event is called when annotation processing is completed,
* and provides a chance to deference anything that is no longer
* needed (to reduce the memory footprint of this object).
*/
- void postInitialize() {
- typeInfoClasses = null;
- packageToPackageInfoMappings = null;
- typeInfo = null;
- typeQNames = null;
- elementDeclarations = null;
- xmlRootElements = null;
+ void postInitialize() {
+ typeInfoClasses = null;
+ packageToPackageInfoMappings = null;
+ typeInfos = null;
+ typeQNames = null;
+ elementDeclarations = null;
+ xmlRootElements = null;
localElements = null;
factoryMethods = null;
xmlRegistries = null;
- objectFactoryClassNames = null;
- classesToProcessPropertyTypes = null;
- javaClassToTypeMappingInfos = null;
- typeMappingInfoToGeneratedClasses = null;
- typeMappingInfoToAdapterClasses = null;
- helper = null;
- logger = null;
+ objectFactoryClassNames = null;
+ classesToProcessPropertyTypes = null;
+ javaClassToTypeMappingInfos = null;
+ typeMappingInfosToGeneratedClasses = null;
+ typeMappingInfoToAdapterClasses = null;
+ helper = null;
+ logger = null;
referencedByTransformer = null;
}
-
- /**
- * Generate TypeInfo instances for a given array of JavaClasses.
- *
- * @param classes
- */
- void processClassesAndProperties(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
- init(classes, typeMappingInfos);
- preBuildTypeInfo(classes);
- classes = postBuildTypeInfo(classes);
- processPropertyTypes(this.typeInfoClasses.toArray(new JavaClass[this.typeInfoClasses.size()]));
- finalizeProperties();
- createElementsForTypeMappingInfo();
- processJavaClasses(null);
- }
-
- public void createElementsForTypeMappingInfo() {
- if (this.javaClassToTypeMappingInfos != null && !this.javaClassToTypeMappingInfos.isEmpty()) {
- Set<JavaClass> classes = this.javaClassToTypeMappingInfos.keySet();
- for (JavaClass nextClass : classes) {
- List<TypeMappingInfo> nextInfos = this.javaClassToTypeMappingInfos.get(nextClass);
+
+ /**
+ * Generate TypeInfo instances for a given array of JavaClasses.
+ *
+ * @param classes
+ */
+ void processClassesAndProperties(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
+ init(classes, typeMappingInfos);
+ preBuildTypeInfo(classes);
+ postBuildTypeInfo(classes);
+ processPropertyTypes(this.typeInfoClasses.toArray(new JavaClass[this.typeInfoClasses.size()]));
+ finalizeProperties();
+ createElementsForTypeMappingInfo();
+ checkForCallbackMethods();
+ }
+
+ public void createElementsForTypeMappingInfo() {
+ if (javaClassToTypeMappingInfos != null && !javaClassToTypeMappingInfos.isEmpty()) {
+ Set<JavaClass> classes = this.javaClassToTypeMappingInfos.keySet();
+ for (JavaClass nextClass : classes) {
+ List<TypeMappingInfo> nextInfos = this.javaClassToTypeMappingInfos.get(nextClass);
for(TypeMappingInfo nextInfo:nextInfos) {
if (nextInfo != null) {
- boolean xmlAttachmentRef = false;
- String xmlMimeType = null;
- java.lang.annotation.Annotation[] annotations = getAnnotations(nextInfo);
- Class adapterClass = this.typeMappingInfoToAdapterClasses.get(nextInfo);
- Class declJavaType = null;
- if (adapterClass != null) {
- declJavaType = CompilerHelper.getTypeFromAdapterClass(adapterClass);
- }
- if (annotations != null) {
- for (int j = 0; j < annotations.length; j++) {
- java.lang.annotation.Annotation nextAnnotation = annotations[j];
- if (nextAnnotation != null) {
- if (nextAnnotation instanceof XmlMimeType) {
- XmlMimeType javaAnnotation = (XmlMimeType) nextAnnotation;
+ boolean xmlAttachmentRef = false;
+ String xmlMimeType = null;
+ java.lang.annotation.Annotation[] annotations = getAnnotations(nextInfo);
+ Class adapterClass = typeMappingInfoToAdapterClasses.get(nextInfo);
+ Class declJavaType = null;
+ if (adapterClass != null) {
+ declJavaType = CompilerHelper.getTypeFromAdapterClass(adapterClass);
+ }
+ if (annotations != null) {
+ for (Annotation nextAnnotation : annotations) {
+ if (nextAnnotation != null) {
+ if (nextAnnotation instanceof XmlMimeType) {
+ XmlMimeType javaAnnotation = (XmlMimeType) nextAnnotation;
xmlMimeType = javaAnnotation.value();
} else if (nextAnnotation instanceof XmlAttachmentRef) {
xmlAttachmentRef = true;
@@ -313,28 +328,28 @@ public class AnnotationsProcessor {
}
}
}
- }
- }
-
- QName qname = null;
-
- String nextClassName = nextClass.getQualifiedName();
-
+ }
+ }
+
+ QName qname;
+
+ String nextClassName = nextClass.getQualifiedName();
+
if (declJavaType != null) {
- nextClassName = declJavaType.getCanonicalName();
- }
-
- if (typeMappingInfoToGeneratedClasses != null) {
- Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo);
- if (generatedClass != null) {
- nextClassName = generatedClass.getCanonicalName();
- }
- }
-
- TypeInfo nextTypeInfo = typeInfo.get(nextClassName);
- if (nextTypeInfo != null) {
- qname = new QName(nextTypeInfo.getClassNamespace(), nextTypeInfo.getSchemaTypeName());
- } else {
+ nextClassName = declJavaType.getCanonicalName();
+ }
+
+ if (typeMappingInfosToGeneratedClasses != null) {
+ Class generatedClass = typeMappingInfosToGeneratedClasses.get(nextInfo);
+ if (generatedClass != null) {
+ nextClassName = generatedClass.getCanonicalName();
+ }
+ }
+
+ TypeInfo nextTypeInfo = typeInfos.get(nextClassName);
+ if (nextTypeInfo != null) {
+ qname = new QName(nextTypeInfo.getClassNamespace(), nextTypeInfo.getSchemaTypeName());
+ } else {
qname = getUserDefinedSchemaTypes().get(nextClassName);
if (qname == null) {
if (nextClassName.equals(ClassConstants.APBYTE.getName()) || nextClassName.equals(Image.class.getName()) || nextClassName.equals(Source.class.getName()) || nextClassName.equals("javax.activation.DataHandler")) {
@@ -352,37 +367,37 @@ public class AnnotationsProcessor {
qname = (QName) XMLConversionManager.getDefaultJavaTypes().get(theClass);
}
}
- }
-
- if (qname != null) {
- typeMappingInfoToSchemaType.put(nextInfo, qname);
- }
-
- if (nextInfo.getXmlTagName() != null) {
+ }
+
+ if (qname != null) {
+ typeMappingInfosToSchemaTypes.put(nextInfo, qname);
+ }
+
+ if (nextInfo.getXmlTagName() != null) {
ElementDeclaration element = new ElementDeclaration(nextInfo.getXmlTagName(), nextClass, nextClass.getQualifiedName(), false);
element.setTypeMappingInfo(nextInfo);
element.setXmlMimeType(xmlMimeType);
element.setXmlAttachmentRef(xmlAttachmentRef);
element.setNillable(nextInfo.isNillable());
- if (declJavaType != null) {
- element.setJavaType(helper.getJavaClass(declJavaType));
- }
- Class generatedClass = typeMappingInfoToGeneratedClasses.get(nextInfo);
- if (generatedClass != null) {
- element.setJavaType(helper.getJavaClass(generatedClass));
- }
+ if (declJavaType != null) {
+ element.setJavaType(helper.getJavaClass(declJavaType));
+ }
+ Class generatedClass = typeMappingInfosToGeneratedClasses.get(nextInfo);
+ if (generatedClass != null) {
+ element.setJavaType(helper.getJavaClass(generatedClass));
+ }
if (nextInfo.getElementScope() == TypeMappingInfo.ElementScope.Global) {
ElementDeclaration currentElement = this.getGlobalElements().get(element.getElementName());
if (currentElement == null) {
addGlobalElement(element.getElementName(), element);
- } else {
- // if(currentElement.getTypeMappingInfo() == null) {
- // the global element that exists came from an annotation
-
- //} else {
- this.localElements.add(element);
- //}
+ } else {
+ // if(currentElement.getTypeMappingInfo() == null) {
+ // the global element that exists came from an annotation
+
+ //} else {
+ this.localElements.add(element);
+ //}
}
} else {
this.localElements.add(element);
@@ -404,33 +419,33 @@ public class AnnotationsProcessor {
/**
* Returns an array of Annotations for a given TypeMappingInfo. This array
* will either be populated from the TypeMappingInfo's array of annotations,
- * or based on an xml-element if present. The xml-element will take
- * precedence over the annotation array; if there is an xml-element the
- * Array of Annotations will be ignored.
- *
- * @param tmInfo
- * @return
- */
+ * or based on an xml-element if present. The xml-element will take
+ * precedence over the annotation array; if there is an xml-element the
+ * Array of Annotations will be ignored.
+ *
+ * @param tmInfo
+ * @return
+ */
private java.lang.annotation.Annotation[] getAnnotations(TypeMappingInfo tmInfo) {
if (tmInfo.getXmlElement() != null) {
ClassLoader loader = helper.getClassLoader();
// create a single ConversionManager for that will be shared by the
// proxy objects
ConversionManager cMgr = new ConversionManager();
- cMgr.setLoader(loader);
-
- // unmarshal the node into an XmlElement
- org.eclipse.persistence.jaxb.xmlmodel.XmlElement xElt = (org.eclipse.persistence.jaxb.xmlmodel.XmlElement) CompilerHelper.getXmlElement(tmInfo.getXmlElement(), loader);
- List annotations = new ArrayList();
- // where applicable, a given dynamic proxy will contain a Map of
- // method name/return value entries
- Map<String, Object> components = null;
- // handle @XmlElement: set 'type' method
- if (!(xElt.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT"))) {
- components = new HashMap();
- components.put(TYPE_METHOD_NAME, xElt.getType());
- annotations.add(AnnotationProxy.getProxy(components, XmlElement.class, loader, cMgr));
- }
+ cMgr.setLoader(loader);
+
+ // unmarshal the node into an XmlElement
+ org.eclipse.persistence.jaxb.xmlmodel.XmlElement xElt = CompilerHelper.getXmlElement(tmInfo.getXmlElement(), loader);
+ List annotations = new ArrayList();
+ // where applicable, a given dynamic proxy will contain a Map of
+ // method name/return value entries
+ Map<String, Object> components = null;
+ // handle @XmlElement: set 'type' method
+ if (!(xElt.getType().equals("javax.xml.bind.annotation.XmlElement.DEFAULT"))) {
+ components = new HashMap<String, Object>();
+ components.put(TYPE_METHOD_NAME, xElt.getType());
+ annotations.add(AnnotationProxy.getProxy(components, XmlElement.class, loader, cMgr));
+ }
// handle @XmlList
if (xElt.isXmlList()) {
annotations.add(AnnotationProxy.getProxy(components, XmlList.class, loader, cMgr));
@@ -438,19 +453,19 @@ public class AnnotationsProcessor {
// handle @XmlAttachmentRef
if (xElt.isXmlAttachmentRef()) {
annotations.add(AnnotationProxy.getProxy(components, XmlAttachmentRef.class, loader, cMgr));
- }
- // handle @XmlMimeType: set 'value' method
- if (xElt.getXmlMimeType() != null) {
- components = new HashMap();
- components.put(VALUE_METHOD_NAME, xElt.getXmlMimeType());
- annotations.add(AnnotationProxy.getProxy(components, XmlMimeType.class, loader, cMgr));
- }
- // handle @XmlJavaTypeAdapter: set 'type' and 'value' methods
- if (xElt.getXmlJavaTypeAdapter() != null) {
- components = new HashMap();
- components.put(TYPE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getType());
- components.put(VALUE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getValue());
- annotations.add(AnnotationProxy.getProxy(components, XmlJavaTypeAdapter.class, loader, cMgr));
+ }
+ // handle @XmlMimeType: set 'value' method
+ if (xElt.getXmlMimeType() != null) {
+ components = new HashMap<String, Object>();
+ components.put(VALUE_METHOD_NAME, xElt.getXmlMimeType());
+ annotations.add(AnnotationProxy.getProxy(components, XmlMimeType.class, loader, cMgr));
+ }
+ // handle @XmlJavaTypeAdapter: set 'type' and 'value' methods
+ if (xElt.getXmlJavaTypeAdapter() != null) {
+ components = new HashMap<String, Object>();
+ components.put(TYPE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getType());
+ components.put(VALUE_METHOD_NAME, xElt.getXmlJavaTypeAdapter().getValue());
+ annotations.add(AnnotationProxy.getProxy(components, XmlJavaTypeAdapter.class, loader, cMgr));
}
// return the newly created array of dynamic proxy objects
return (java.lang.annotation.Annotation[]) annotations.toArray(new java.lang.annotation.Annotation[annotations.size()]);
@@ -464,13 +479,13 @@ public class AnnotationsProcessor {
* Initialize maps, lists, etc. Typically called prior to processing a set
* of classes via preBuildTypeInfo, postBuildTypeInfo, processJavaClasses.
*/
- void init(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
- typeInfoClasses = new ArrayList<JavaClass>();
- referencedByTransformer = new ArrayList<String>();
- typeInfo = new HashMap<String, TypeInfo>();
- typeQNames = new ArrayList<QName>();
- classesToProcessPropertyTypes = new ArrayList<JavaClass>();
- objectFactoryClassNames = new ArrayList<String>();
+ void init(JavaClass[] classes, TypeMappingInfo[] typeMappingInfos) {
+ typeInfoClasses = new ArrayList<JavaClass>();
+ referencedByTransformer = new ArrayList<String>();
+ typeInfos = new HashMap<String, TypeInfo>();
+ typeQNames = new ArrayList<QName>();
+ classesToProcessPropertyTypes = new ArrayList<JavaClass>();
+ objectFactoryClassNames = new ArrayList<String>();
userDefinedSchemaTypes = new HashMap<String, QName>();
if (packageToPackageInfoMappings == null) {
packageToPackageInfoMappings = new HashMap<String, PackageInfo>();
@@ -480,16 +495,16 @@ public class AnnotationsProcessor {
this.xmlRootElements = new HashMap<String, ElementDeclaration>();
arrayClassesToGeneratedClasses = new HashMap<String, Class>();
- collectionClassesToGeneratedClasses = new HashMap<java.lang.reflect.Type, Class>();
- generatedClassesToArrayClasses = new HashMap<Class, JavaClass>();
- generatedClassesToCollectionClasses = new HashMap<Class, java.lang.reflect.Type>();
- typeMappingInfoToGeneratedClasses = new HashMap<TypeMappingInfo, Class>();
- typeMappingInfoToSchemaType = new HashMap<TypeMappingInfo, QName>();
- elementDeclarations = new HashMap<String, HashMap<QName, ElementDeclaration>>();
- HashMap globalElements = new HashMap<QName, ElementDeclaration>();
- elementDeclarations.put(XmlElementDecl.GLOBAL.class.getName(), globalElements);
- localElements = new ArrayList<ElementDeclaration>();
-
+ collectionClassesToGeneratedClasses = new HashMap<java.lang.reflect.Type, Class>();
+ generatedClassesToArrayClasses = new HashMap<Class, JavaClass>();
+ generatedClassesToCollectionClasses = new HashMap<Class, java.lang.reflect.Type>();
+ typeMappingInfosToGeneratedClasses = new HashMap<TypeMappingInfo, Class>();
+ typeMappingInfosToSchemaTypes = new HashMap<TypeMappingInfo, QName>();
+ elementDeclarations = new HashMap<String, Map<QName, ElementDeclaration>>();
+ Map globalElements = new HashMap<QName, ElementDeclaration>();
+ elementDeclarations.put(XmlElementDecl.GLOBAL.class.getName(), globalElements);
+ localElements = new ArrayList<ElementDeclaration>();
+
javaClassToTypeMappingInfos = new HashMap<JavaClass, List<TypeMappingInfo>>();
if (typeMappingInfos != null) {
for (int i = 0; i < typeMappingInfos.length; i++) {
@@ -518,20 +533,20 @@ public class AnnotationsProcessor {
/**
* Process class level annotations only. It is assumed that a call to init()
- * has been made prior to calling this method. After the types created via
- * this method have been modified (if necessary) postBuildTypeInfo and
- * processJavaClasses should be called to finish processing.
- *
- * @param javaClasses
- * @return
- */
- public Map<String, TypeInfo> preBuildTypeInfo(JavaClass[] javaClasses) {
- for (JavaClass javaClass : javaClasses) {
- String qualifiedName = javaClass.getQualifiedName();
- TypeInfo info = typeInfo.get(qualifiedName);
- if (javaClass == null || javaClass.isArray()|| (info!=null && info.isPreBuilt()) || !shouldGenerateTypeInfo(javaClass) || isXmlRegistry(javaClass) ) {
- continue;
- }
+ * has been made prior to calling this method. After the types created via
+ * this method have been modified (if necessary) postBuildTypeInfo and
+ * processJavaClasses should be called to finish processing.
+ *
+ * @param javaClasses
+ * @return
+ */
+ public Map<String, TypeInfo> preBuildTypeInfo(JavaClass[] javaClasses) {
+ for (JavaClass javaClass : javaClasses) {
+ String qualifiedName = javaClass.getQualifiedName();
+ TypeInfo info = typeInfos.get(qualifiedName);
+ if (javaClass == null || javaClass.isArray()|| (info!=null && info.isPreBuilt()) || !shouldGenerateTypeInfo(javaClass) || isXmlRegistry(javaClass) ) {
+ continue;
+ }
if (javaClass.isEnum()) {
@@ -551,28 +566,28 @@ public class AnnotationsProcessor {
processXmlExtensible(javaClass, info);
// handle @XmlInlineBinaryData
- if (helper.isAnnotationPresent(javaClass, XmlInlineBinaryData.class)) {
- info.setInlineBinaryData(true);
- }
-
- // handle @NamedObjectGraph
- processNamedObjectGraphs(javaClass, info);
-
+ if (helper.isAnnotationPresent(javaClass, XmlInlineBinaryData.class)) {
+ info.setInlineBinaryData(true);
+ }
+
+ // handle @NamedObjectGraph
+ processNamedObjectGraphs(javaClass, info);
+
// handle @XmlRootElement
processXmlRootElement(javaClass, info);
// handle @XmlSeeAlso
processXmlSeeAlso(javaClass, info);
-
- PackageInfo packageInfo = getPackageInfoForPackage(javaClass);
- if(packageInfo != null && packageInfo.getPackageLevelAdaptersByClass().size() > 0){
- for(String adapterClass :packageInfo.getPackageLevelAdaptersByClass().keySet()){
- JavaClass boundType = packageInfo.getPackageLevelAdaptersByClass().get(adapterClass);
- info.getPackageLevelAdaptersByClass().put(adapterClass, boundType);
- }
- }
- NamespaceInfo namespaceInfo = packageInfo.getNamespaceInfo();
- // handle @XmlType
+
+ PackageInfo packageInfo = getPackageInfoForPackage(javaClass);
+ if(packageInfo != null && packageInfo.getPackageLevelAdaptersByClass().size() > 0){
+ for(String adapterClass :packageInfo.getPackageLevelAdaptersByClass().keySet()){
+ JavaClass boundType = packageInfo.getPackageLevelAdaptersByClass().get(adapterClass);
+ info.getPackageLevelAdaptersByClass().put(adapterClass, boundType);
+ }
+ }
+ NamespaceInfo namespaceInfo = packageInfo.getNamespaceInfo();
+ // handle @XmlType
preProcessXmlType(javaClass, info, namespaceInfo);
// handle @XmlAccessorType
@@ -580,13 +595,13 @@ public class AnnotationsProcessor {
// handle @XmlAccessorOrder
preProcessXmlAccessorOrder(javaClass, info, namespaceInfo);
-
- // handle package level @XmlJavaTypeAdapters
- processPackageLevelAdapters(javaClass, info);
-
- // handle Accessor Factory
- processAccessorFactory(javaClass, info);
-
+
+ // handle package level @XmlJavaTypeAdapters
+ processPackageLevelAdapters(javaClass, info);
+
+ // handle Accessor Factory
+ processAccessorFactory(javaClass, info);
+
// handle class level @XmlJavaTypeAdapters
processClassLevelAdapters(javaClass, info);
@@ -622,29 +637,27 @@ public class AnnotationsProcessor {
if (helper.isAnnotationPresent(javaClass, XmlDiscriminatorValue.class)) {
XmlDiscriminatorValue xmlDiscriminatorValue = (XmlDiscriminatorValue) helper.getAnnotation(javaClass, XmlDiscriminatorValue.class);
info.setXmlDiscriminatorValue(xmlDiscriminatorValue.value());
- }
-
- typeInfoClasses.add(javaClass);
- typeInfo.put(info.getJavaClassName(), info);
- }
- return typeInfo;
- }
-
- private void processNamedObjectGraphs(JavaClass javaClass, TypeInfo info) {
- ArrayList<XmlNamedObjectGraph> objectGraphs = new ArrayList<XmlNamedObjectGraph>();
- if(helper.isAnnotationPresent(javaClass, XmlNamedObjectGraphs.class)) {
- XmlNamedObjectGraphs graphs = (XmlNamedObjectGraphs)helper.getAnnotation(javaClass, XmlNamedObjectGraphs.class);
- for(XmlNamedObjectGraph next: graphs.value()) {
- objectGraphs.add(next);
- }
- }
- if(helper.isAnnotationPresent(javaClass, XmlNamedObjectGraph.class)) {
- objectGraphs.add((XmlNamedObjectGraph)helper.getAnnotation(javaClass, XmlNamedObjectGraph.class));
- }
-
- for(XmlNamedObjectGraph next:objectGraphs) {
- org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph namedGraph = new org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph();
- namedGraph.setName(next.name());
+ }
+
+ typeInfoClasses.add(javaClass);
+ typeInfos.put(info.getJavaClassName(), info);
+ }
+ return typeInfos;
+ }
+
+ private void processNamedObjectGraphs(JavaClass javaClass, TypeInfo info) {
+ List<XmlNamedObjectGraph> objectGraphs = new ArrayList<XmlNamedObjectGraph>();
+ if(helper.isAnnotationPresent(javaClass, XmlNamedObjectGraphs.class)) {
+ XmlNamedObjectGraphs graphs = (XmlNamedObjectGraphs)helper.getAnnotation(javaClass, XmlNamedObjectGraphs.class);
+ Collections.addAll(objectGraphs, graphs.value());
+ }
+ if(helper.isAnnotationPresent(javaClass, XmlNamedObjectGraph.class)) {
+ objectGraphs.add((XmlNamedObjectGraph)helper.getAnnotation(javaClass, XmlNamedObjectGraph.class));
+ }
+
+ for(XmlNamedObjectGraph next:objectGraphs) {
+ org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph namedGraph = new org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph();
+ namedGraph.setName(next.name());
for(XmlNamedAttributeNode nextNode:next.attributeNodes()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlNamedAttributeNode namedNode = new org.eclipse.persistence.jaxb.xmlmodel.XmlNamedAttributeNode();
@@ -710,64 +723,61 @@ public class AnnotationsProcessor {
info.setPackageLevelXmlAccessorFactory(pInfo.getAccessorFactory());
}
}
-
- /**
- * Process any additional classes (i.e. inner classes, @XmlSeeAlso,
- *
- * @XmlRegistry, etc.) for a given set of JavaClasses, then complete
- * building all of the required TypeInfo objects. This method
- * is typically called after init and preBuildTypeInfo have
- * been called.
- *
- * @param javaClasses
- * @return updated array of JavaClasses, made up of the original classes
- * plus any additional ones
- */
- public JavaClass[] postBuildTypeInfo(JavaClass[] javaClasses) {
- if (javaClasses.length == 0) {
- return javaClasses;
- }
- ArrayList<JavaClass> originalList = new ArrayList<JavaClass>(javaClasses.length);
- for(JavaClass next:javaClasses) {
- originalList.add(next);
- }
- // create type info instances for any additional classes
- javaClasses = processAdditionalClasses(javaClasses);
- preBuildTypeInfo(javaClasses);
- buildTypeInfo(javaClasses);
- updateGlobalElements(javaClasses);
- if(javaClasses.length > originalList.size()) {
- ArrayList<JavaClass> newClasses = new ArrayList(javaClasses.length - originalList.size());
- for(JavaClass next:javaClasses) {
- if(!(originalList.contains(next))) {
- newClasses.add(next);
+
+ /**
+ * Process any additional classes (i.e. inner classes, @XmlSeeAlso,
+ *
+ * @XmlRegistry, etc.) for a given set of JavaClasses, then complete
+ * building all of the required TypeInfo objects. This method
+ * is typically called after init and preBuildTypeInfo have
+ * been called.
+ *
+ * @param javaClasses
+ * @return updated array of JavaClasses, made up of the original classes
+ * plus any additional ones
+ */
+ public JavaClass[] postBuildTypeInfo(JavaClass[] javaClasses) {
+ if (javaClasses.length == 0) {
+ return javaClasses;
+ }
+ List<JavaClass> originalList = Arrays.asList(javaClasses);
+ // create type info instances for any additional classes
+ javaClasses = processAdditionalClasses(javaClasses);
+ preBuildTypeInfo(javaClasses);
+ buildTypeInfo(javaClasses);
+ updateGlobalElements(javaClasses);
+ if(javaClasses.length > originalList.size()) {
+ List<JavaClass> newClasses = new ArrayList<JavaClass>(javaClasses.length - originalList.size());
+ for(JavaClass next:javaClasses) {
+ if(!(originalList.contains(next))) {
+ newClasses.add(next);
}
}
postBuildTypeInfo(newClasses.toArray(new JavaClass[newClasses.size()]));
}
return javaClasses;
}
-
- /**
- * INTERNAL:
- *
- * Complete building TypeInfo objects for a given set of JavaClass
- * instances. This method assumes that init, preBuildTypeInfo, and
- * postBuildTypeInfo have been called.
- *
- * @param allClasses
- * @return
- */
+
+ /**
+ * INTERNAL:
+ *
+ * Complete building TypeInfo objects for a given set of JavaClass
+ * instances. This method assumes that init, preBuildTypeInfo, and
+ * postBuildTypeInfo have been called.
+ *
+ * @param allClasses
+ * @return
+ */
private Map<String, TypeInfo> buildTypeInfo(JavaClass[] allClasses) {
for (JavaClass javaClass : allClasses) {
if (javaClass == null) {
- continue;
- }
-
- TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
- if (info == null || info.isPostBuilt()) {
- continue;
- }
+ continue;
+ }
+
+ TypeInfo info = typeInfos.get(javaClass.getQualifiedName());
+ if (info == null || info.isPostBuilt()) {
+ continue;
+ }
info.setPostBuilt(true);
// handle factory methods
@@ -779,24 +789,24 @@ public class AnnotationsProcessor {
if(transformer == TypeInfo.DEFAULT_NAME_TRANSFORMER){
XMLNameTransformer nsInfoXmlNameTransformer = packageInfo.getXmlNameTransformer();
- if (nsInfoXmlNameTransformer != null) {
- info.setXmlNameTransformer(nsInfoXmlNameTransformer);
- } else if (helper.isAnnotationPresent(javaClass, XmlNameTransformer.class)) {
- XmlNameTransformer nameTranformer = (XmlNameTransformer) helper.getAnnotation(javaClass, XmlNameTransformer.class);
- Class nameTransformerClass = nameTranformer.value();
- try {
- info.setXmlNameTransformer((XMLNameTransformer) nameTransformerClass.newInstance());
- } catch (InstantiationException ex) {
+ if (nsInfoXmlNameTransformer != null) {
+ info.setXmlNameTransformer(nsInfoXmlNameTransformer);
+ } else if (helper.isAnnotationPresent(javaClass, XmlNameTransformer.class)) {
+ XmlNameTransformer xmlNameTransformer = (XmlNameTransformer) helper.getAnnotation(javaClass, XmlNameTransformer.class);
+ Class nameTransformerClass = xmlNameTransformer.value();
+ try {
+ info.setXmlNameTransformer((XMLNameTransformer) nameTransformerClass.newInstance());
+ } catch (InstantiationException ex) {
throw JAXBException.exceptionWithNameTransformerClass(nameTransformerClass.getName(), ex);
} catch (IllegalAccessException ex) {
- throw JAXBException.exceptionWithNameTransformerClass(nameTransformerClass.getName(), ex);
- }
- } else if (helper.isAnnotationPresent(javaClass.getPackage(), XmlNameTransformer.class)) {
- XmlNameTransformer nameTranformer = (XmlNameTransformer) helper.getAnnotation(javaClass.getPackage(), XmlNameTransformer.class);
- Class nameTransformerClass = nameTranformer.value();
- try {
- info.setXmlNameTransformer((XMLNameTransformer) nameTransformerClass.newInstance());
- } catch (InstantiationException ex) {
+ throw JAXBException.exceptionWithNameTransformerClass(nameTransformerClass.getName(), ex);
+ }
+ } else if (helper.isAnnotationPresent(javaClass.getPackage(), XmlNameTransformer.class)) {
+ XmlNameTransformer xmlNameTransformer = (XmlNameTransformer) helper.getAnnotation(javaClass.getPackage(), XmlNameTransformer.class);
+ Class nameTransformerClass = xmlNameTransformer.value();
+ try {
+ info.setXmlNameTransformer((XMLNameTransformer) nameTransformerClass.newInstance());
+ } catch (InstantiationException ex) {
throw JAXBException.exceptionWithNameTransformerClass(nameTransformerClass.getName(), ex);
} catch (IllegalAccessException ex) {
throw JAXBException.exceptionWithNameTransformerClass(nameTransformerClass.getName(), ex);
@@ -817,13 +827,13 @@ public class AnnotationsProcessor {
}
// process schema type name
- processTypeQName(javaClass, info, packageInfo.getNamespaceInfo());
-
- // handle superclass if necessary
- JavaClass superClass = (JavaClass) javaClass.getSuperclass();
- processReferencedClass(superClass);
- processPropertiesSuperClass(javaClass, info);
-
+ processTypeQName(javaClass, info, packageInfo.getNamespaceInfo());
+
+ // handle superclass if necessary
+ JavaClass superClass = javaClass.getSuperclass();
+ processReferencedClass(superClass);
+ processPropertiesSuperClass(javaClass, info);
+
// add properties
info.setProperties(getPropertiesForClass(javaClass, info));
@@ -832,159 +842,156 @@ public class AnnotationsProcessor {
// handle @XmlAccessorOrder
postProcessXmlAccessorOrder(info, packageInfo);
+
+ validatePropOrderForInfo(info);
+ }
+ return typeInfos;
+ }
+
+ private TypeInfo processReferencedClass(JavaClass referencedClass){
+ if (shouldGenerateTypeInfo(referencedClass)) {
+ TypeInfo existingInfo = typeInfos.get(referencedClass.getQualifiedName());
+ if (existingInfo == null || !existingInfo.isPreBuilt()) {
+ PackageInfo pInfo = getPackageInfoForPackage(referencedClass);
+ JavaClass adapterClass = pInfo.getPackageLevelAdaptersByClass().get(referencedClass);
+ if (adapterClass == null) {
+ CompilerHelper.addClassToClassLoader(referencedClass, helper.getClassLoader());
+ JavaClass[] jClassArray = new JavaClass[] { referencedClass };
+ buildNewTypeInfo(jClassArray);
+ }
+ return typeInfos.get(referencedClass.getQualifiedName());
+ } else {
+ if (!existingInfo.isPostBuilt()) {
+ PackageInfo pInfo = getPackageInfoForPackage(referencedClass);
+ JavaClass adapterClass = pInfo.getPackageLevelAdaptersByClass().get(referencedClass);
+ if (adapterClass == null) {
+ CompilerHelper.addClassToClassLoader(referencedClass, helper.getClassLoader());
+ JavaClass[] javaClasses = new JavaClass[] { referencedClass };
+ javaClasses = postBuildTypeInfo(javaClasses);
+ for(JavaClass next:javaClasses) {
+ processPropertyTypes(next);
+ }
+ }
+ }
+ return existingInfo;
+ }
+ }
+ return null;
+ }
+
+ /*
+ * Get virtual property and XmlID information from parent and set it on info if available
+ */
+ public void processPropertiesSuperClass(JavaClass cls, TypeInfo info) {
+ JavaClass superClass = cls.getSuperclass();
+ if (superClass == null) {
+ return;
+ }
+ TypeInfo superClassInfo = this.typeInfos.get(superClass.getQualifiedName());
+ if(superClassInfo != null) {
+ processPropertiesSuperClass(superClass, superClassInfo);
+ classesToProcessPropertyTypes.add(superClass);
+ if(superClassInfo.getXmlVirtualAccessMethods() != null && info.getXmlVirtualAccessMethods() == null) {
+ info.setXmlVirtualAccessMethods(superClassInfo.getXmlVirtualAccessMethods());
+ }
+ if(superClassInfo.isIDSet()){
+ info.setIDProperty(superClassInfo.getIDProperty());
+ }
+ }
+ }
- validatePropOrderForInfo(info);
- }
- return typeInfo;
- }
-
- private TypeInfo processReferencedClass(JavaClass referencedClass){
- if (shouldGenerateTypeInfo(referencedClass)) {
- TypeInfo existingInfo = typeInfo.get(referencedClass.getQualifiedName());
- if(existingInfo == null || !existingInfo.isPreBuilt()){
- PackageInfo pInfo = getPackageInfoForPackage(referencedClass);
- JavaClass adapterClass = pInfo.getPackageLevelAdaptersByClass().get(referencedClass);
- if(adapterClass == null){
- CompilerHelper.addClassToClassLoader(referencedClass, helper.getClassLoader());
- JavaClass[] jClassArray = new JavaClass[] { referencedClass };
- buildNewTypeInfo(jClassArray);
- }
- return typeInfo.get(referencedClass.getQualifiedName());
- }else{
- if(existingInfo !=null && !existingInfo.isPostBuilt()){
- PackageInfo pInfo = getPackageInfoForPackage(referencedClass);
- JavaClass adapterClass = pInfo.getPackageLevelAdaptersByClass().get(referencedClass);
- if(adapterClass == null){
- CompilerHelper.addClassToClassLoader(referencedClass, helper.getClassLoader());
- JavaClass[] javaClasses = new JavaClass[] { referencedClass };
- javaClasses = postBuildTypeInfo(javaClasses);
- for(JavaClass next:javaClasses) {
- processPropertyTypes(next);
- }
- }
- }
- return existingInfo;
- }
- }
- return null;
- }
-
- /*
- * Get virtual property and XmlID information from parent and set it on info if available
- */
- public void processPropertiesSuperClass(JavaClass cls, TypeInfo info) {
- JavaClass superClass = (JavaClass) cls.getSuperclass();
- if(superClass == null) {
- return;
- }
- TypeInfo superClassInfo = this.typeInfo.get(superClass.getQualifiedName());
- if(superClassInfo != null) {
- processPropertiesSuperClass(superClass, superClassInfo);
- classesToProcessPropertyTypes.add(superClass);
- if(superClassInfo.getXmlVirtualAccessMethods() != null && info.getXmlVirtualAccessMethods() == null) {
- info.setXmlVirtualAccessMethods(superClassInfo.getXmlVirtualAccessMethods());
- }
- if(superClassInfo.isIDSet()){
- info.setIDProperty(superClassInfo.getIDProperty());
- }
- }
- }
-
- /**
- * Perform any final generation and/or validation operations on TypeInfo
- * properties.
- *
- */
- public void finalizeProperties() {
-
- for (TypeInfo tInfo: getTypeInfo().values()) {
- // don't need to validate props on a transient class at this point
- if (tInfo.isTransient()) {
- continue;
- }
- JavaClass jClass = tInfo.getJavaClass();
- String[] propOrder = tInfo.getPropOrder();
- boolean hasPropOrder = propOrder.length > 0 && !(propOrder.length == 1 && propOrder[0].equals(Constants.EMPTY_STRING));
- // If a property is marked transient, ensure it doesn't exist in the propOrder
- List<String> propOrderList = Arrays.asList(tInfo.getPropOrder());
- ArrayList<Property> propsList = tInfo.getPropertyList();
- for (int i = 0; i < propsList.size(); i++) {
- Property p = propsList.get(i);
- if (p.isTransient() && propOrderList.contains(p.getPropertyName())) {
- throw org.eclipse.persistence.exceptions.JAXBException.transientInProporder(p.getPropertyName());
- }
- if(hasPropOrder && !p.isAttribute() && !p.isTransient() && !p.isInverseReference()){
- if (!propOrderList.contains(p.getPropertyName())) {
- throw JAXBException.missingPropertyInPropOrder(p.getPropertyName(), tInfo.getJavaClassName());
- }
- }
- }
-
- if (!jClass.isInterface() && !tInfo.isEnumerationType() && !jClass.isAbstract()) {
- if (tInfo.getFactoryMethodName() == null && tInfo.getObjectFactoryClassName() == null) {
- JavaConstructor zeroArgConstructor = jClass.getDeclaredConstructor(new JavaClass[] {});
+ /**
+ * Perform any final generation and/or validation operations on TypeInfo
+ * properties.
+ *
+ */
+ public void finalizeProperties() {
+
+ for (TypeInfo tInfo: getTypeInfos().values()) {
+ // don't need to validate props on a transient class at this point
+ if (tInfo.isTransient()) {
+ continue;
+ }
+ JavaClass jClass = tInfo.getJavaClass();
+ String[] propOrder = tInfo.getPropOrder();
+ boolean hasPropOrder = propOrder.length > 0 && !(propOrder.length == 1 && propOrder[0].equals(Constants.EMPTY_STRING));
+ // If a property is marked transient, ensure it doesn't exist in the propOrder
+ List<String> propOrderList = Arrays.asList(tInfo.getPropOrder());
+ List<Property> propsList = tInfo.getPropertyList();
+ for (Property p : propsList) {
+ if (p.isTransient() && propOrderList.contains(p.getPropertyName())) {
+ throw JAXBException.transientInProporder(p.getPropertyName());
+ }
+ if (hasPropOrder && !p.isAttribute() && !p.isTransient() && !p.isInverseReference()) {
+ if (!propOrderList.contains(p.getPropertyName())) {
+ throw JAXBException.missingPropertyInPropOrder(p.getPropertyName(), tInfo.getJavaClassName());
+ }
+ }
+ }
+
+ if (!jClass.isInterface() && !tInfo.isEnumerationType() && !jClass.isAbstract()) {
+ if (tInfo.getFactoryMethodName() == null && tInfo.getObjectFactoryClassName() == null) {
+ JavaConstructor zeroArgConstructor = jClass.getDeclaredConstructor(new JavaClass[] {});
if (zeroArgConstructor == null) {
- if (tInfo.isSetXmlJavaTypeAdapter()) {
- tInfo.setTransient(true);
- } else {
- if(!referencedByTransformer.contains(jClass.getName())){
- throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodOrConstructorRequired(jClass.getName());
- }
- }
- }
- }
+ if (tInfo.isSetXmlJavaTypeAdapter()) {
+ tInfo.setTransient(true);
+ } else {
+ if(!referencedByTransformer.contains(jClass.getName())){
+ throw org.eclipse.persistence.exceptions.JAXBException.factoryMethodOrConstructorRequired(jClass.getName());
+ }
+ }
+ }
+ }
}
// validate XmlValue
if (tInfo.getXmlValueProperty() != null) {
validateXmlValueFieldOrProperty(jClass, tInfo.getXmlValueProperty());
}
- // Keep a list of "any" properties to verify if multiples exist
- // that they have different element wrappers
- List<Property> anyElementProperties = new ArrayList<Property>();
-
- for (Property property : tInfo.getPropertyList()) {
- // Check that @XmlAttribute references a Java type that maps to text in XML
- if (property.isAttribute()) {
- validateXmlAttributeFieldOrProperty(tInfo, property);
- }
- JavaClass typeClass = property.getActualType();
-
- if(property.isChoice()){
- Collection<Property> choiceProps = property.getChoiceProperties();
- Iterator<Property> choicePropsIter = choiceProps.iterator();
- while(choicePropsIter.hasNext()){
- Property nextChoiceProp = choicePropsIter.next();
- JavaClass nextChoicePropTypeClass = nextChoiceProp.getActualType();
- TypeInfo targetInfo = typeInfo.get(nextChoicePropTypeClass.getQualifiedName());
- finalizeProperty(property, targetInfo, nextChoicePropTypeClass, jClass);
- }
- }else{
- TypeInfo targetInfo = typeInfo.get(typeClass.getQualifiedName());
- finalizeProperty(property, targetInfo, typeClass, jClass);
- }
-
- // only one XmlValue is allowed per class, and if there is one
- // only XmlAttributes are allowed
- if (tInfo.isSetXmlValueProperty()) {
+ // Keep a list of "any" properties to verify if multiples exist
+ // that they have different element wrappers
+ List<Property> anyElementProperties = new ArrayList<Property>();
+
+ for (Property property : tInfo.getPropertyList()) {
+ // Check that @XmlAttribute references a Java type that maps to text in XML
+ if (property.isAttribute()) {
+ validateXmlAttributeFieldOrProperty(tInfo, property);
+ }
+ JavaClass propertyClass = property.getActualType();
+
+ if (property.isChoice()) {
+ Collection<Property> choiceProps = property.getChoiceProperties();
+ for (Property nextChoiceProp : choiceProps) {
+ JavaClass nextChoicePropTypeClass = nextChoiceProp.getActualType();
+ TypeInfo targetInfo = typeInfos.get(nextChoicePropTypeClass.getQualifiedName());
+ finalizeProperty(property, targetInfo, nextChoicePropTypeClass, jClass);
+ }
+ } else {
+ TypeInfo targetInfo = typeInfos.get(propertyClass.getQualifiedName());
+ finalizeProperty(property, targetInfo, propertyClass, jClass);
+ }
+
+ // only one XmlValue is allowed per class, and if there is one
+ // only XmlAttributes are allowed
+ if (tInfo.isSetXmlValueProperty()) {
if (property.isXmlValue() && !(tInfo.getXmlValueProperty().getPropertyName().equals(property.getPropertyName()))) {
throw JAXBException.xmlValueAlreadySet(property.getPropertyName(), tInfo.getXmlValueProperty().getPropertyName(), jClass.getName());
}
if (!property.isXmlValue() && !property.isAttribute() && !property.isInverseReference() && !property.isTransient()) {
- throw JAXBException.propertyOrFieldShouldBeAnAttribute(property.getPropertyName());
- }
- }
-
-
- // handle XmlElementRef(s) - validate and build the required
- // ElementDeclaration object
- if (property.isReference()) {
- processReferenceProperty(property, tInfo, jClass);
- }
-
- if (property.isSwaAttachmentRef() && !this.hasSwaRef) {
- this.hasSwaRef = true;
- }
+ throw JAXBException.propertyOrFieldShouldBeAnAttribute(property.getPropertyName());
+ }
+ }
+
+
+ // handle XmlElementRef(s) - validate and build the required
+ // ElementDeclaration object
+ if (property.isReference()) {
+ processReferenceProperty(property, tInfo, jClass);
+ }
+
+ if (property.isSwaAttachmentRef() && !this.hasSwaRef) {
+ this.hasSwaRef = true;
+ }
// there can only be one XmlID per type info
if (property.isXmlId() && tInfo.getIDProperty() != null && !(tInfo.getIDProperty().getPropertyName().equals(property.getPropertyName()))) {
@@ -1022,59 +1029,59 @@ public class AnnotationsProcessor {
throw JAXBException.invalidElementWrapper(property.getPropertyName());
}
}
-
- // handle XmlTransformation - validate transformer class/method
- if (property.isXmlTransformation()) {
- processXmlTransformationProperty(property);
- }
- // validate XmlJoinNodes
- if (property.isSetXmlJoinNodes()) {
- TypeInfo targetInfo = typeInfo.get(typeClass.getQualifiedName());
-
- // the target class must have an associated TypeInfo
- if (targetInfo == null) {
- throw JAXBException.invalidXmlJoinNodeReferencedClass(property.getPropertyName(), typeClass.getQualifiedName());
- }
- // validate each referencedXmlPath - target TypeInfo should
- // have XmlID/XmlKey property with matching XmlPath
- if (targetInfo.getIDProperty() == null && targetInfo.getXmlKeyProperties() == null) {
- throw JAXBException.noKeyOrIDPropertyOnJoinTarget(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
- }
- }
- }
- }
- }
-
- private void finalizeProperty(Property property, TypeInfo targetInfo, JavaClass typeClass, JavaClass jClass){
- if (targetInfo != null && targetInfo.isTransient() && property.getXmlElements() == null) {
- property.setTransientType(true);
- }
-
- // validate XmlIDREF
- if (property.isXmlIdRef()) {
- // the target class must have an associated TypeInfo unless
- // it is Object
- if (targetInfo == null && !typeClass.getQualifiedName().equals(JAVA_LANG_OBJECT)) {
- throw JAXBException.invalidIDREFClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
- }
- // if the property is an XmlIDREF, the target must have an
- // XmlID set
- if (targetInfo != null && targetInfo.getIDProperty() == null) {
- throw JAXBException.invalidIdRef(property.getPropertyName(), typeClass.getQualifiedName());
- }
- }
- }
-
- /**
- * Process a given TypeInfo instance's properties.
- *
- * @param info
- */
- private void processTypeInfoProperties(JavaClass javaClass, TypeInfo info) {
- ArrayList<Property> properties = info.getPropertyList();
- for (Property property : properties) {
- // handle @XmlID
- processXmlID(property, javaClass, info);
+
+ // handle XmlTransformation - validate transformer class/method
+ if (property.isXmlTransformation()) {
+ validateXmlTransformationProperty(property);
+ }
+ // validate XmlJoinNodes
+ if (property.isSetXmlJoinNodes()) {
+ TypeInfo targetInfo = typeInfos.get(propertyClass.getQualifiedName());
+
+ // the target class must have an associated TypeInfo
+ if (targetInfo == null) {
+ throw JAXBException.invalidXmlJoinNodeReferencedClass(property.getPropertyName(), propertyClass.getQualifiedName());
+ }
+ // validate each referencedXmlPath - target TypeInfo should
+ // have XmlID/XmlKey property with matching XmlPath
+ if (targetInfo.getIDProperty() == null && targetInfo.getXmlKeyProperties() == null) {
+ throw JAXBException.noKeyOrIDPropertyOnJoinTarget(jClass.getQualifiedName(), property.getPropertyName(), propertyClass.getQualifiedName());
+ }
+ }
+ }
+ }
+ }
+
+ private void finalizeProperty(Property property, TypeInfo targetInfo, JavaClass typeClass, JavaClass jClass){
+ if (targetInfo != null && targetInfo.isTransient() && property.getXmlElements() == null) {
+ property.setTransientType(true);
+ }
+
+ // validate XmlIDREF
+ if (property.isXmlIdRef()) {
+ // the target class must have an associated TypeInfo unless
+ // it is Object
+ if (targetInfo == null && !typeClass.getQualifiedName().equals(JAVA_LANG_OBJECT)) {
+ throw JAXBException.invalidIDREFClass(jClass.getQualifiedName(), property.getPropertyName(), typeClass.getQualifiedName());
+ }
+ // if the property is an XmlIDREF, the target must have an
+ // XmlID set
+ if (targetInfo != null && targetInfo.getIDProperty() == null) {
+ throw JAXBException.invalidIdRef(property.getPropertyName(), typeClass.getQualifiedName());
+ }
+ }
+ }
+
+ /**
+ * Process a given TypeInfo instance's properties.
+ *
+ * @param info
+ */
+ private void processTypeInfoProperties(JavaClass javaClass, TypeInfo info) {
+ List<Property> properties = info.getPropertyList();
+ for (Property property : properties) {
+ // handle @XmlID
+ processXmlID(property, javaClass, info);
// handle @XmlIDREF - validate these properties after processing of
// all types is completed
@@ -1085,75 +1092,54 @@ public class AnnotationsProcessor {
processReferencedClass(property.getValueType());
}
}
- }
-
- void processPropertyTypes(JavaClass[] classes) {
- for (JavaClass next : classes) {
- processPropertyTypes(next);
- classesToProcessPropertyTypes.remove(next);
- }
- for (int i =0; i< classesToProcessPropertyTypes.size(); i++){
- JavaClass next = classesToProcessPropertyTypes.get(i);
- processPropertyTypes(next);
- }
- }
-
- private void processPropertyTypes(JavaClass next){
-
- TypeInfo info = getTypeInfo().get(next.getQualifiedName());
- if (info != null) {
-
- for (Property property : info.getPropertyList()) {
-
- if (property.isXmlLocation()) {
- info.setLocationAware(true);
- }
-
- if (property.isTransient()) {
- continue;
- }
- JavaClass type = property.getActualType();
-
- if(property.isReference()) {
- processReferencePropertyTypes(property, info, next);
- }
-
-
- if (property.isChoice()) {
-
- processChoiceProperty(property, info, next, type);
- for (Property choiceProp : property.getChoiceProperties()) {
- type = choiceProp.getActualType();
- processReferencedClass(type);
- }
- }else{
- processReferencedClass(type);
- }
- }
- }
-
- }
-
- /**
- * This method was initially designed to handle processing one or more
- * JavaClass instances. Over time its functionality has been broken apart
- * and handled in different methods. Its sole purpose now is to check for
- * callback methods.
- *
- * @param classes
- * this paramater can and should be null as it is not used
- */
- public void processJavaClasses(JavaClass[] classes) {
- checkForCallbackMethods();
- }
-
- /**
- * Process any additional classes, such as inner classes, @XmlRegistry or
- * from @XmlSeeAlso.
- *
- * @param classes
- * @return
- */
+ }
+
+ void processPropertyTypes(JavaClass[] classes) {
+ for (JavaClass next : classes) {
+ processPropertyTypes(next);
+ classesToProcessPropertyTypes.remove(next);
+ }
+ for (int i =0; i< classesToProcessPropertyTypes.size(); i++) { // throws cme when using foreach
+ JavaClass next = classesToProcessPropertyTypes.get(i);
+ processPropertyTypes(next);
+ }
+ }
+
+ private void processPropertyTypes(JavaClass next){
+
+ TypeInfo info = getTypeInfos().get(next.getQualifiedName());
+ if (info != null) {
+ for (Property property : info.getPropertyList()) {
+ if (property.isXmlLocation())
+ info.setLocationAware(true);
+ if (property.isTransient())
+ continue;
+
+ JavaClass type = property.getActualType();
+ if (property.isReference()) {
+ processReferencePropertyTypes(property, info, next);
+ }
+ if (property.isChoice()) {
+ processChoiceProperty(property, info, next, type);
+ for (Property choiceProp : property.getChoiceProperties()) {
+ type = choiceProp.getActualType();
+ processReferencedClass(type);
+ }
+ } else {
+ processReferencedClass(type);
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Process any additional classes, such as inner classes, @XmlRegistry or
+ * from @XmlSeeAlso.
+ *
+ * @param classes
+ * @return
+ */
private JavaClass[] processAdditionalClasses(JavaClass[] classes) {
ArrayList<JavaClass> extraClasses = new ArrayList<JavaClass>();
ArrayList<JavaClass> classesToProcess = new ArrayList<JavaClass>();
@@ -1171,13 +1157,13 @@ public class AnnotationsProcessor {
for (JavaClass javaClass : extraClasses) {
processClass(javaClass, classesToProcess);
}
-
- return classesToProcess.toArray(new JavaClass[classesToProcess.size()]);
- }
-
- private void processAdditionalClasses(JavaClass cls, TypeMappingInfo tmi, ArrayList<JavaClass> extraClasses, ArrayList<JavaClass> classesToProcess) {
- Class xmlElementType = null;
- JavaClass javaClass = cls;
+
+ return classesToProcess.toArray(new JavaClass[classesToProcess.size()]);
+ }
+
+ private void processAdditionalClasses(JavaClass cls, TypeMappingInfo tmi, ArrayList<JavaClass> extraClasses, ArrayList<JavaClass> classesToProcess) {
+ Class xmlElementType = null;
+ JavaClass javaClass = cls;
if (tmi != null) {
Class adapterClass = this.typeMappingInfoToAdapterClasses.get(tmi);
if (adapterClass != null) {
@@ -1187,33 +1173,29 @@ public class AnnotationsProcessor {
// look for marshal method
for (Object nextMethod : adapterJavaClass.getDeclaredMethods()) {
JavaMethod method = (JavaMethod) nextMethod;
- if (method.getName().equals("marshal")) {
- JavaClass returnType = method.getReturnType();
- if (!returnType.getQualifiedName().equals(newType.getQualifiedName())) {
- newType = (JavaClass) returnType;
- break;
- }
- }
+ if (method.getName().equals("marshal")) {
+ JavaClass returnType = method.getReturnType();
+ if (!returnType.getQualifiedName().equals(newType.getQualifiedName())) {
+ newType = returnType;
+ break;
+ }
+ }
}
if (!helper.isBuiltInJavaType(javaClass)) {
extraClasses.add(javaClass);
}
javaClass = newType;
- }
- java.lang.annotation.Annotation[] annotations = getAnnotations(tmi);
- if (annotations != null) {
- for (int j = 0; j < annotations.length; j++) {
- java.lang.annotation.Annotation nextAnnotation = annotations[j];
-
- if (nextAnnotation != null) {
- if (nextAnnotation instanceof XmlElement) {
- XmlElement javaAnnotation = (XmlElement) nextAnnotation;
- if (javaAnnotation.type() != XmlElement.DEFAULT.class) {
- xmlElementType = javaAnnotation.type();
- }
- }
- }
- }
+ }
+ java.lang.annotation.Annotation[] annotations = getAnnotations(tmi);
+ if (annotations != null) {
+ for (Annotation nextAnnotation : annotations) {
+ if (nextAnnotation != null && nextAnnotation instanceof XmlElement) {
+ XmlElement javaAnnotation = (XmlElement) nextAnnotation;
+ if (javaAnnotation.type() != XmlElement.DEFAULT.class) {
+ xmlElementType = javaAnnotation.type();
+ }
+ }
+ }
}
}
@@ -1228,46 +1210,46 @@ public class AnnotationsProcessor {
extraClasses.add(javaClass.getComponentType());
}
Class generatedClass;
- if (null == tmi) {
- generatedClass = arrayClassesToGeneratedClasses.get(javaClass.getName());
- } else {
- generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
- }
- if (generatedClass == null) {
- generatedClass = generateWrapperForArrayClass(javaClass, tmi, xmlElementType, extraClasses);
+ if (null == tmi) {
+ generatedClass = arrayClassesToGeneratedClasses.get(javaClass.getName());
+ } else {
+ generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfosToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
+ }
+ if (generatedClass == null) {
+ generatedClass = generateWrapperForArrayClass(javaClass, tmi, xmlElementType, extraClasses);
extraClasses.add(helper.getJavaClass(generatedClass));
- arrayClassesToGeneratedClasses.put(javaClass.getName(), generatedClass);
- }
- generatedClassesToArrayClasses.put(generatedClass, javaClass);
- typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
-
- } else if (helper.isCollectionType(javaClass)) {
- JavaClass componentClass;
- Collection args = javaClass.getActualTypeArguments();
- if (args.size() >0) {
- componentClass = (JavaClass) args.iterator().next();
- if (!componentClass.isPrimitive()) {
- extraClasses.add(componentClass);
+ arrayClassesToGeneratedClasses.put(javaClass.getName(), generatedClass);
+ }
+ generatedClassesToArrayClasses.put(generatedClass, javaClass);
+ typeMappingInfosToGeneratedClasses.put(tmi, generatedClass);
+
+ } else if (helper.isCollectionType(javaClass)) {
+ JavaClass componentClass;
+ Collection args = javaClass.getActualTypeArguments();
+ if (!args.isEmpty()) {
+ componentClass = (JavaClass) args.iterator().next();
+ if (!componentClass.isPrimitive()) {
+ extraClasses.add(componentClass);
}
} else {
- componentClass = helper.getJavaClass(Object.class);
- }
-
- Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
- if (generatedClass == null) {
- generatedClass = generateCollectionValue(javaClass, tmi, xmlElementType, extraClasses);
- extraClasses.add(helper.getJavaClass(generatedClass));
- }
- typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
- } else if (helper.isMapType(javaClass)) {
- JavaClass keyClass;
- JavaClass valueClass;
- Collection args = javaClass.getActualTypeArguments();
- Iterator argsIter = args.iterator();
- if (args.size() > 1) {
- keyClass = (JavaClass) argsIter.next();
- if (!helper.isBuiltInJavaType(keyClass)) {
- extraClasses.add(keyClass);
+ componentClass = helper.getJavaClass(Object.class);
+ }
+
+ Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfosToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
+ if (generatedClass == null) {
+ generatedClass = generateCollectionValue(javaClass, tmi, xmlElementType, extraClasses);
+ extraClasses.add(helper.getJavaClass(generatedClass));
+ }
+ typeMappingInfosToGeneratedClasses.put(tmi, generatedClass);
+ } else if (helper.isMapType(javaClass)) {
+ JavaClass keyClass;
+ JavaClass valueClass;
+ Collection args = javaClass.getActualTypeArguments();
+ Iterator argsIter = args.iterator();
+ if (!args.isEmpty()) {
+ keyClass = (JavaClass) argsIter.next();
+ if (!helper.isBuiltInJavaType(keyClass)) {
+ extraClasses.add(keyClass);
}
valueClass = (JavaClass) argsIter.next();
if (!helper.isBuiltInJavaType(valueClass)) {
@@ -1275,53 +1257,53 @@ public class AnnotationsProcessor {
}
} else {
keyClass = helper.getJavaClass(Object.class);
- valueClass = helper.getJavaClass(Object.class);
- }
-
- Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
- if (generatedClass == null) {
- generatedClass = generateWrapperForMapClass(javaClass, keyClass, valueClass, tmi);
- extraClasses.add(helper.getJavaClass(generatedClass));
- }
- typeMappingInfoToGeneratedClasses.put(tmi, generatedClass);
- } else {
- // process @XmlRegistry, @XmlSeeAlso and inner classes
- processClass(javaClass, classesToProcess);
- }
- }
-
- /**
- * Adds additional classes to the given List, from inner classes,
- *
- * @XmlRegistry or @XmlSeeAlso.
- *
- * @param javaClass
- * @param classesToProcess
- */
+ valueClass = helper.getJavaClass(Object.class);
+ }
+
+ Class generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfosToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader());
+ if (generatedClass == null) {
+ generatedClass = generateWrapperForMapClass(javaClass, keyClass, valueClass, tmi);
+ extraClasses.add(helper.getJavaClass(generatedClass));
+ }
+ typeMappingInfosToGeneratedClasses.put(tmi, generatedClass);
+ } else {
+ // process @XmlRegistry, @XmlSeeAlso and inner classes
+ processClass(javaClass, classesToProcess);
+ }
+ }
+
+ /**
+ * Adds additional classes to the given List, from inner classes,
+ *
+ * @XmlRegistry or @XmlSeeAlso.
+ *
+ * @param javaClass
+ * @param classesToProcess
+ */
private void processClass(JavaClass javaClass, ArrayList<JavaClass> classesToProcess) {
if (shouldGenerateTypeInfo(javaClass)) {
if (isXmlRegistry(javaClass)) {
this.processObjectFactory(javaClass, classesToProcess);
- } else {
- classesToProcess.add(javaClass);
- // handle @XmlSeeAlso
- TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
- if (info != null && info.isSetXmlSeeAlso()) {
- for (String jClassName : info.getXmlSeeAlso()) {
- classesToProcess.add(helper.getJavaClass(jClassName));
+ } else {
+ classesToProcess.add(javaClass);
+ // handle @XmlSeeAlso
+ TypeInfo info = typeInfos.get(javaClass.getQualifiedName());
+ if (info != null && info.isSetXmlSeeAlso()) {
+ for (String jClassName : info.getXmlSeeAlso()) {
+ classesToProcess.add(helper.getJavaClass(jClassName));
}
}
}
}
}
- /**
- * Process an @XmlSeeAlso annotation. TypeInfo instances will be created for
- * each class listed.
- *
- * @param javaClass
- */
- private void processXmlSeeAlso(JavaClass javaClass, TypeInfo info) {
+ /**
+ * Process an @XmlSeeAlso annotation. TypeInfo instances will be created for
+ * each class listed.
+ *
+ * @param javaClass
+ */
+ private void processXmlSeeAlso(JavaClass javaClass, TypeInfo info) {
// reflectively load @XmlSeeAlso class to avoid dependency
Class xmlSeeAlsoClass = null;
Method valueMethod = null;
@@ -1339,24 +1321,24 @@ public class AnnotationsProcessor {
try {
values = (Class[]) PrivilegedAccessHelper.invokeMethod(valueMethod, seeAlso, new Object[] {});
} catch (Exception ex) {
- }
-
- if (values != null) {
- List<String> seeAlsoClassNames = new ArrayList<String>();
- for (Class next : values) {
- seeAlsoClassNames.add(next.getName());
- }
+ }
+
+ if (values != null) {
+ List<String> seeAlsoClassNames = new ArrayList<String>();
+ for (Class next : values) {
+ seeAlsoClassNames.add(next.getName());
+ }
info.setXmlSeeAlso(seeAlsoClassNames);
}
}
}
-
- /**
- * Process any factory methods.
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process any factory methods.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processFactoryMethods(JavaClass javaClass, TypeInfo info) {
JavaMethod factoryMethod = this.factoryMethods.get(javaClass.getRawName());
if (factoryMethod != null) {
@@ -1374,13 +1356,13 @@ public class AnnotationsProcessor {
}
}
}
-
- /**
- * Process any package-level @XmlJavaTypeAdapters.
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process any package-level @XmlJavaTypeAdapters.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processPackageLevelAdapters(JavaClass javaClass, TypeInfo info) {
JavaPackage pack = javaClass.getPackage();
if (helper.isAnnotationPresent(pack, XmlJavaTypeAdapters.class)) {
@@ -1406,13 +1388,13 @@ public class AnnotationsProcessor {
getLogger().logWarning(JAXBMetadataLogger.INVALID_BOUND_TYPE, new Object[] { boundType, adapterClass });
}
}
-
- /**
- * Process any class-level @XmlJavaTypeAdapters.
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process any class-level @XmlJavaTypeAdapters.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processClassLevelAdapters(JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(javaClass, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(javaClass, XmlJavaTypeAdapter.class);
@@ -1428,13 +1410,13 @@ public class AnnotationsProcessor {
info.setXmlJavaTypeAdapter(xja);
}
}
-
- /**
- * Process any @XmlSchemaType(s).
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process any @XmlSchemaType(s).
+ *
+ * @param javaClass
+ * @param info
+ */
private void processSchemaTypes(JavaClass javaClass, TypeInfo info) {
JavaPackage pack = javaClass.getPackage();
if (helper.isAnnotationPresent(pack, XmlSchemaTypes.class)) {
@@ -1447,13 +1429,13 @@ public class AnnotationsProcessor {
processSchemaType((XmlSchemaType) helper.getAnnotation(pack, XmlSchemaType.class));
}
}
-
- /**
- * Process @XmlRootElement annotation on a given JavaClass.
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process @XmlRootElement annotation on a given JavaClass.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processXmlRootElement(JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(javaClass, XmlRootElement.class)) {
XmlRootElement rootElemAnnotation = (XmlRootElement) helper.getAnnotation(javaClass, XmlRootElement.class);
@@ -1463,13 +1445,13 @@ public class AnnotationsProcessor {
info.setXmlRootElement(xmlRE);
}
}
-
- /**
- * Process @XmlExtensible annotation on a given JavaClass.
- *
- * @param javaClass
- * @param info
- */
+
+ /**
+ * Process @XmlExtensible annotation on a given JavaClass.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processXmlExtensible(JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(javaClass, XmlVirtualAccessMethods.class)) {
XmlVirtualAccessMethods extAnnotation = (XmlVirtualAccessMethods) helper.getAnnotation(javaClass, XmlVirtualAccessMethods.class);
@@ -1482,55 +1464,55 @@ public class AnnotationsProcessor {
}
/**
- * Process @XmlType annotation on a given JavaClass and update the TypeInfo
- * for pre-processing. Note that if no @XmlType annotation is present we
- * still create a new XmlType an set it on the TypeInfo.
- *
- * @param javaClass
- * @param info
- * @param packageNamespace
- */
- private void preProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
- org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = new org.eclipse.persistence.jaxb.xmlmodel.XmlType();
- if (helper.isAnnotationPresent(javaClass, XmlType.class)) {
- XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class);
- // set name
- xmlType.setName(typeAnnotation.name());
- // set namespace
- xmlType.setNamespace(typeAnnotation.namespace());
- // set propOrder
- String[] propOrder = typeAnnotation.propOrder();
- // handle case where propOrder is an empty array
- if (propOrder != null) {
- xmlType.getPropOrder();
- }
- for (String prop : propOrder) {
- xmlType.getPropOrder().add(prop);
- }
- // set factoryClass
- Class factoryClass = typeAnnotation.factoryClass();
- if (factoryClass == DEFAULT.class) {
- xmlType.setFactoryClass("javax.xml.bind.annotation.XmlType.DEFAULT");
- } else {
- xmlType.setFactoryClass(factoryClass.getCanonicalName());
- }
- // set factoryMethodName
- xmlType.setFactoryMethod(typeAnnotation.factoryMethod());
- } else {
- // set defaults
- xmlType.setNamespace(packageNamespace.getNamespace());
- }
- info.setXmlType(xmlType);
- }
-
- /**
- * Process XmlType for a given TypeInfo. Here we assume that the TypeInfo
- * has an XmlType set - typically via preProcessXmlType or XmlProcessor
- * override.
- *
- * @param javaClass
- * @param info
- * @param packageNamespace
+ * Process @XmlType annotation on a given JavaClass and update the TypeInfo
+ * for pre-processing. Note that if no @XmlType annotation is present we
+ * still create a new XmlType an set it on the TypeInfo.
+ *
+ * @param javaClass
+ * @param info
+ * @param packageNamespace
+ */
+ private void preProcessXmlType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
+ org.eclipse.persistence.jaxb.xmlmodel.XmlType xmlType = new org.eclipse.persistence.jaxb.xmlmodel.XmlType(); // 14 xmlType=XmlType - default settings: name=null, namespace=null, factoryClass=null, factoryMethod=null, propOrder=null.
+ if (helper.isAnnotationPresent(javaClass, XmlType.class)) {
+ XmlType typeAnnotation = (XmlType) helper.getAnnotation(javaClass, XmlType.class); // 15 typeAnnotation=com.sun.proxy.$Proxy6"@javax.xml.bind.annotation.XmlType(factoryMethod=, name=OneClass, propOrder=[car], factoryClass=class javax.xml.bind.annotation.XmlType$DEFAULT, namespace=##default)"
+ // set name
+ xmlType.setName(typeAnnotation.name()); // 16 XmlType - name="OneClass
+ // set namespace
+ xmlType.setNamespace(typeAnnotation.namespace()); // 17 xmlType - namespace="##default"
+ // set propOrder
+ String[] propOrder = typeAnnotation.propOrder(); // 18 propOrder = ["car"]
+ // initializes xmlType.propOrder to an empty ArrayList
+ if (propOrder != null) {
+ xmlType.getPropOrder(); // 19 OK, so this only initializes xmlType.propOrder to an empty ArrayList
+ }
+ for (String prop : propOrder) {
+ xmlType.getPropOrder().add(prop); // 20 - puts "car" into xmlType.propOrder
+ }
+ // set factoryClass
+ Class factoryClass = typeAnnotation.factoryClass(); // 21 factoryClass=java.lang.Class"class javax.xml.bind.annotation.XmlType$DEFAULT"
+ if (factoryClass == DEFAULT.class) {
+ xmlType.setFactoryClass("javax.xml.bind.annotation.XmlType.DEFAULT"); // 22
+ } else {
+ xmlType.setFactoryClass(factoryClass.getCanonicalName());
+ }
+ // set factoryMethodName
+ xmlType.setFactoryMethod(typeAnnotation.factoryMethod()); // 23 defaults to factoryMethod=""
+ } else {
+ // set defaults
+ xmlType.setNamespace(packageNamespace.getNamespace());
+ }
+ info.setXmlType(xmlType); // 24
+ }
+
+ /**
+ * Process XmlType for a given TypeInfo. Here we assume that the TypeInfo
+ * has an XmlType set - typically via preProcessXmlType or XmlProcessor
+ * override.
+ *
+ * @param javaClass
+ * @param info
+ * @param packageNamespace
*/
private void postProcessXmlType(JavaClass javaClass, TypeInfo info, PackageInfo packageNamespace) {
// assumes that the TypeInfo has an XmlType set from
@@ -1589,13 +1571,13 @@ public class AnnotationsProcessor {
}
}
- /**
- * Process @XmlAccessorType annotation on a given JavaClass and update the
- * TypeInfo for pre-processing.
- *
- * @param javaClass
- * @param info
- * @param packageNamespace
+ /**
+ * Process @XmlAccessorType annotation on a given JavaClass and update the
+ * TypeInfo for pre-processing.
+ *
+ * @param javaClass
+ * @param info
+ * @param packageNamespace
*/
private void preProcessXmlAccessorType(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType xmlAccessType;
@@ -1606,22 +1588,22 @@ public class AnnotationsProcessor {
}
}
- /**
- * Post process XmlAccessorType. In some cases, such as @XmlSeeAlso classes,
- * the access type may not have been set
- *
- * @param info
- */
- private void postProcessXmlAccessorType(TypeInfo info, PackageInfo packageNamespace) {
+ /**
+ * Post process XmlAccessorType. In some cases, such as @XmlSeeAlso classes,
+ * the access type may not have been set
+ *
+ * @param info
+ */
+ private void postProcessXmlAccessorType(TypeInfo info, PackageInfo packageNamespace) {
if (!info.isSetXmlAccessType()) {
// Check for super class
- JavaClass next = helper.getJavaClass(info.getJavaClassName()).getSuperclass();
- while (next != null && !(next.getName().equals(JAVA_LANG_OBJECT))) {
- processReferencedClass(next);
- TypeInfo parentInfo = this.typeInfo.get(next.getName());
- if (parentInfo != null && parentInfo.isSetXmlAccessType()) {
- info.setXmlAccessType(parentInfo.getXmlAccessType());
- break;
+ JavaClass next = helper.getJavaClass(info.getJavaClassName()).getSuperclass();
+ while (next != null && !(next.getName().equals(JAVA_LANG_OBJECT))) {
+ processReferencedClass(next);
+ TypeInfo parentInfo = this.typeInfos.get(next.getName());
+ if (parentInfo != null && parentInfo.isSetXmlAccessType()) {
+ info.setXmlAccessType(parentInfo.getXmlAccessType());
+ break;
}
next = next.getSuperclass();
}
@@ -1633,13 +1615,13 @@ public class AnnotationsProcessor {
}
}
- /**
- * Process package and class @XmlAccessorOrder. Class level annotation
- * overrides a package level annotation.
- *
- * @param javaClass
- * @param info
- * @param packageNamespace
+ /**
+ * Process package and class @XmlAccessorOrder. Class level annotation
+ * overrides a package level annotation.
+ *
+ * @param javaClass
+ * @param info
+ * @param packageNamespace
*/
private void preProcessXmlAccessorOrder(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
XmlAccessorOrder order = null;
@@ -1651,108 +1633,177 @@ public class AnnotationsProcessor {
}
/**
- * Post process XmlAccessorOrder. This method assumes that the given
- * TypeInfo has already had its order set (via annotations in
- * preProcessXmlAccessorOrder or via xml metadata override in XMLProcessor).
- *
- * @param javaClass
- * @param info
- */
- private void postProcessXmlAccessorOrder(TypeInfo info, PackageInfo packageNamespace) {
- if (!info.isSetXmlAccessOrder()) {
+ * Post process XmlAccessorOrder. This method assumes that the given
+ * TypeInfo has already had its order set (via annotations in
+ * preProcessXmlAccessorOrder or via xml metadata override in XMLProcessor).
+ *
+ * @param info
+ * @param packageNamespace
+ */
+ private void postProcessXmlAccessorOrder(TypeInfo info, PackageInfo packageNamespace) {
+ if (!info.isSetXmlAccessOrder()) {
// use value in package-info.java as last resort - will default if
// not set
info.setXmlAccessOrder(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder.fromValue(packageNamespace.getAccessOrder().name()));
}
info.orderProperties();
}
-
- /**
- * Process @XmlElement annotation on a given property.
- *
- * @param property
- */
- private void processXmlElement(Property property, TypeInfo info) {
+
+ /**
+ * Process @XmlElement annotation on a given property.
+ *
+ * @param property
+ */
+ private void processXmlElement(Property property, TypeInfo info) {
if (helper.isAnnotationPresent(property.getElement(), XmlElement.class)) {
XmlElement element = (XmlElement) helper.getAnnotation(property.getElement(), XmlElement.class);
property.setIsRequired(element.required());
property.setNillable(element.nillable());
if (element.type() != XmlElement.DEFAULT.class && !(property.isSwaAttachmentRef())) {
property.setOriginalType(property.getType());
- if (helper.isCollectionType(property.getType()) || property.getType().isArray()) {
- property.setGenericType(helper.getJavaClass(element.type()));
- } else {
- JavaClass originalType = property.getType();
- JavaClass newType =helper.getJavaClass(element.type());
- if(!originalType.getName().equals(newType.getName())){
- property.setTyped(true);
- property.setSchemaType((QName) helper.getXMLToJavaTypeMap().get(newType.getName()));
- }
- property.setType(newType);
- }
- property.setHasXmlElementType(true);
+ if (helper.isCollectionType(property.getType()) || property.getType().isArray()) {
+ property.setGenericType(helper.getJavaClass(element.type()));
+ } else {
+ JavaClass originalType = property.getType();
+ JavaClass newType =helper.getJavaClass(element.type());
+ if(!originalType.getName().equals(newType.getName())){
+ property.setTyped(true);
+ property.setSchemaType((QName) helper.getXMLToJavaTypeMap().get(newType.getName()));
+ }
+ property.setType(newType);
+ }
+ property.setHasXmlElementType(true);
}
// handle default value
- if (!element.defaultValue().equals(ELEMENT_DECL_DEFAULT)) {
- property.setDefaultValue(element.defaultValue());
- }
- }
- }
-
- /**
- * Process @XmlID annotation on a given property
- *
- * @param property
- * @param info
- */
+ if (!element.defaultValue().equals(ELEMENT_DECL_DEFAULT)) {
+ property.setDefaultValue(element.defaultValue());
+ }
+
+ if (facets) addFacets(property);
+ }
+ }
+
+ private void addFacets(Property property) {
+ final JavaHasAnnotations element = property.getElement();
+ if (helper.isAnnotationPresent(element, DecimalMin.class)) {
+ DecimalMin a = (DecimalMin) helper.getAnnotation(element, DecimalMin.class);
+ DecimalMinFacet facet = new DecimalMinFacet(a.value(), a.inclusive());
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, DecimalMax.class)) {
+ DecimalMax a = (DecimalMax) helper.getAnnotation(element, DecimalMax.class);
+ DecimalMaxFacet facet = new DecimalMaxFacet(a.value(), a.inclusive());
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, Digits.class)) {
+ Digits a = (Digits) helper.getAnnotation(element, Digits.class);
+ DigitsFacet facet = new DigitsFacet(a.integer(), a.fraction());
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, Max.class)) {
+ Max a = (Max) helper.getAnnotation(element, Max.class);
+ MaxFacet facet = new MaxFacet(a.value());
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, Min.class)) {
+ Min a = (Min) helper.getAnnotation(element, Min.class);
+ MinFacet facet = new MinFacet(a.value());
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, NotNull.class)) {
+ property.setNotNullAnnotated(true);
+ }
+ if (helper.isAnnotationPresent(element, Pattern.class)) {
+ Pattern a = (Pattern) helper.getAnnotation(element, Pattern.class);
+ PatternFacet facet = new PatternFacet(a.regexp(), a.flags());
+ property.addFacet(facet);
+ }
+ /* Example:
+ @Pattern.List({
+ @Pattern(regexp = "first_expression", message = "first.Pattern.message"),
+ @Pattern(regexp = "second_expression", message = "second.Pattern.message"),
+ @Pattern(regexp = "third_expression", message = "third.Pattern.message")
+ }) */
+ if (helper.isAnnotationPresent(element, Pattern.List.class)) {
+ Pattern.List a = (Pattern.List) helper.getAnnotation(element, Pattern.List.class);
+ PatternListFacet facet = new PatternListFacet(new ArrayList<PatternFacet>());
+ for (Pattern pat : a.value()) {
+ PatternFacet pf = new PatternFacet(pat.regexp(), pat.flags());
+ facet.addPattern(pf);
+ }
+ property.addFacet(facet);
+ }
+ if (helper.isAnnotationPresent(element, Size.class)) {
+ Size a = (Size) helper.getAnnotation(element, Size.class);
+ final int min = a.min();
+ final int max = a.max();
+ if (min != 0 || max != Integer.MAX_VALUE) { // Fixes generation of an empty facet.
+ if ("java.lang.String".equals(property.getType().getName())) { // @Size serves for both length facet and occurs restriction.
+ SizeFacet facet = new SizeFacet(min, max); // For minLength, maxLength.
+ property.addFacet(facet);
+ } else { // For minOccurs, maxOccurs.
+ if (min > 0) property.setMinOccurs(min); // 0 is default minBoundary.
+ if (max < Integer.MAX_VALUE) property.setMaxOccurs(max); // 2^31 is default maxBoundary.
+ }
+ }
+ }
+ }
+
+ /**
+ * Process @XmlID annotation on a given property
+ *
+ * @param property
+ * @param info
+ */
private void processXmlID(Property property, JavaClass javaClass, TypeInfo info) {
if (helper.isAnnotationPresent(property.getElement(), XmlID.class)) {
property.setIsXmlId(true);
info.setIDProperty(property);
}
}
-
- /**
- * Process @XmlIDREF on a given property.
- *
- * @param property
- */
- private void processXmlIDREF(Property property) {
+
+ /**
+ * Process @XmlIDREF on a given property.
+ *
+ * @param property
+ */
+ private void processXmlIDREF(Property property) {
if (helper.isAnnotationPresent(property.getElement(), XmlIDREF.class)) {
property.setIsXmlIdRef(true);
}
}
-
- /**
- * Process @XmlJavaTypeAdapter on a given property.
- *
- * @param property
- * @param propertyType
- */
- private void processXmlJavaTypeAdapter(Property property, TypeInfo info, JavaClass javaClass) {
- JavaClass adapterClass = null;
+
+ /**
+ * Process @XmlJavaTypeAdapter on a given property.
+ *
+ * @param property
+ * @param info
+ * @param javaClass
+ */
+ private void processXmlJavaTypeAdapter(Property property, TypeInfo info, JavaClass javaClass) {
+ JavaClass adapterClass = null;
JavaClass ptype = property.getActualType();
if (helper.isAnnotationPresent(property.getElement(), XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(property.getElement(), XmlJavaTypeAdapter.class);
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
xja.setValue(adapter.value().getName());
- xja.setType(adapter.type().getName());
- property.setXmlJavaTypeAdapter(xja);
- } else {
- TypeInfo ptypeInfo = typeInfo.get(ptype.getQualifiedName());
- org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter;
- if (ptypeInfo == null && shouldGenerateTypeInfo(ptype)) {
- if (helper.isAnnotationPresent(ptype, XmlJavaTypeAdapter.class)) {
- XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(ptype, XmlJavaTypeAdapter.class);
- org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
- xja.setValue(adapter.value().getName());
- String boundType = adapter.type().getName();
- if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) {
- boundType = ptype.getRawName();
- }
- xja.setType(adapter.type().getName());
- property.setXmlJavaTypeAdapter(xja);
- }
+ xja.setType(adapter.type().getName());
+ property.setXmlJavaTypeAdapter(xja);
+ } else {
+ TypeInfo ptypeInfo = typeInfos.get(ptype.getQualifiedName());
+ org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter;
+ if (ptypeInfo == null && shouldGenerateTypeInfo(ptype)) {
+ if (helper.isAnnotationPresent(ptype, XmlJavaTypeAdapter.class)) {
+ XmlJavaTypeAdapter adapter = (XmlJavaTypeAdapter) helper.getAnnotation(ptype, XmlJavaTypeAdapter.class);
+ org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xja = new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
+ xja.setValue(adapter.value().getName());
+ /*String boundType = adapter.type().getName();
+ if (boundType == null || boundType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) {
+ boundType = ptype.getRawName();
+ } value from boundType is not used - fix if you know what it should do. */
+ xja.setType(adapter.type().getName());
+ property.setXmlJavaTypeAdapter(xja);
+ }
}
if (ptypeInfo != null) {
if (null != (xmlJavaTypeAdapter = ptypeInfo.getXmlJavaTypeAdapter())) {
@@ -1776,13 +1827,13 @@ public class AnnotationsProcessor {
}
}
- /**
- * Store a QName (if necessary) based on a given TypeInfo's schema type
- * name.
- *
- * @param javaClass
- * @param info
- */
+ /**
+ * Store a QName (if necessary) based on a given TypeInfo's schema type
+ * name.
+ *
+ * @param javaClass
+ * @param info
+ */
private void processTypeQName(JavaClass javaClass, TypeInfo info, NamespaceInfo packageNamespace) {
if(info.isTransient()) {
return;
@@ -1825,26 +1876,26 @@ public class AnnotationsProcessor {
public ArrayList<Property> getPropertiesForClass(JavaClass cls, TypeInfo info) {
ArrayList<Property> returnList = new ArrayList<Property>();
- if (!info.isTransient()) {
- JavaClass superClass = cls.getSuperclass();
- if (null != superClass) {
- TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName());
- ArrayList<Property> superClassProperties;
- while (superClassInfo != null && superClassInfo.isTransient()) {
- if (info.getXmlAccessType() == XmlAccessType.FIELD) {
- superClassProperties = getFieldPropertiesForClass(superClass, superClassInfo, false);
- } else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) {
- superClassProperties = getPropertyPropertiesForClass(superClass, superClassInfo, false);
- } else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) {
+ if (!info.isTransient()) {
+ JavaClass superClass = cls.getSuperclass();
+ if (null != superClass) {
+ TypeInfo superClassInfo = typeInfos.get(superClass.getQualifiedName());
+ ArrayList<Property> superClassProperties;
+ while (superClassInfo != null && superClassInfo.isTransient()) {
+ if (info.getXmlAccessType() == XmlAccessType.FIELD) {
+ superClassProperties = getFieldPropertiesForClass(superClass, superClassInfo, false);
+ } else if (info.getXmlAccessType() == XmlAccessType.PROPERTY) {
+ superClassProperties = getPropertyPropertiesForClass(superClass, superClassInfo, false);
+ } else if (info.getXmlAccessType() == XmlAccessType.PUBLIC_MEMBER) {
superClassProperties = getPublicMemberPropertiesForClass(superClass, superClassInfo);
} else {
- superClassProperties = getNoAccessTypePropertiesForClass(superClass, superClassInfo);
- }
- superClass = superClass.getSuperclass();
- superClassInfo = typeInfo.get(superClass.getQualifiedName());
- for(Property next:superClassProperties) {
- next.setIsSuperClassProperty(true);
- }
+ superClassProperties = getNoAccessTypePropertiesForClass(superClass, superClassInfo);
+ }
+ superClass = superClass.getSuperclass();
+ superClassInfo = typeInfos.get(superClass.getQualifiedName());
+ for(Property next:superClassProperties) {
+ next.setIsSuperClassProperty(true);
+ }
returnList.addAll(0, superClassProperties);
}
}
@@ -1873,89 +1924,88 @@ public class AnnotationsProcessor {
public ArrayList<Property> getFieldPropertiesForClass(JavaClass cls, TypeInfo info, boolean onlyPublic, boolean onlyExplicit) {
ArrayList<Property> properties = new ArrayList<Property>();
if (cls == null) {
- return properties;
- }
-
- for (Iterator<JavaField> fieldIt = cls.getDeclaredFields().iterator(); fieldIt.hasNext();) {
- Property property = null;
- JavaField nextField = fieldIt.next();
- int modifiers = nextField.getModifiers();
-
- if (!Modifier.isTransient(modifiers) && ((Modifier.isPublic(nextField.getModifiers()) && onlyPublic) || !onlyPublic ||hasJAXBAnnotations(nextField))) {
- if (!Modifier.isStatic(modifiers)) {
- if ((onlyExplicit && hasJAXBAnnotations(nextField)) || !onlyExplicit) {
- try {
- property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType());
- properties.add(property);
- } catch(JAXBException ex) {
- if(ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !helper.isAnnotationPresent(nextField, XmlTransient.class)) {
- throw ex;
- }
- }
- }
- } else {
- try {
- property = buildNewProperty(info, cls, nextField, nextField.getName(), nextField.getResolvedType());
- if (helper.isAnnotationPresent(nextField, XmlAttribute.class)) {
- Object value = ((JavaFieldImpl) nextField).get(null);
- if (value != null) {
- String stringValue = (String) XMLConversionManager.getDefaultXMLManager().convertObject(value, String.class, property.getSchemaType());
- property.setFixedValue(stringValue);
- }
- }
- property.setWriteOnly(true);
- if(!hasJAXBAnnotations(nextField)) {
- property.setTransient(true);
- }
- properties.add(property);
+ return properties;
+ }
+
+ for (JavaField javaField : (Iterable<JavaField>) cls.getDeclaredFields()) {
+ Property property = null;
+ int modifiers = javaField.getModifiers();
+
+ if (!Modifier.isTransient(modifiers) && ((Modifier.isPublic(javaField.getModifiers()) && onlyPublic) || !onlyPublic || hasJAXBAnnotations(javaField))) {
+ if (!Modifier.isStatic(modifiers)) {
+ if ((onlyExplicit && hasJAXBAnnotations(javaField)) || !onlyExplicit) {
+ try {
+ property = buildNewProperty(info, cls, javaField, javaField.getName(), javaField.getResolvedType());
+ properties.add(property);
+ } catch (JAXBException ex) {
+ if (ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !helper.isAnnotationPresent(javaField, XmlTransient.class)) {
+ throw ex;
+ }
+ }
+ }
+ } else {
+ try {
+ property = buildNewProperty(info, cls, javaField, javaField.getName(), javaField.getResolvedType());
+ if (helper.isAnnotationPresent(javaField, XmlAttribute.class)) {
+ Object value = ((JavaFieldImpl) javaField).get(null);
+ if (value != null) {
+ String stringValue = (String) XMLConversionManager.getDefaultXMLManager().convertObject(value, String.class, property.getSchemaType());
+ property.setFixedValue(stringValue);
+ }
+ }
+ property.setWriteOnly(true);
+ if (!hasJAXBAnnotations(javaField)) {
+ property.setTransient(true);
+ }
+ properties.add(property);
} catch (ClassCastException e) {
- // do Nothing
- } catch (IllegalAccessException e) {
- // do Nothing
- } catch(JAXBException ex) {
- if(ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !helper.isAnnotationPresent(nextField, XmlTransient.class)) {
- throw ex;
- }
- }
- }
- }
-
- if (helper.isAnnotationPresent(nextField, XmlTransient.class)) {
- if(property != null){
- property.setTransient(true);
- }
- }
- }
- return properties;
- }
-
- /*
- * Create a new Property Object and process the annotations that are common
- * to fields and methods
- */
- Property buildNewProperty(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) {
- Property property = null;
- if (helper.isAnnotationPresent(javaHasAnnotations, XmlElements.class)) {
- property = buildChoiceProperty(javaHasAnnotations);
- } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementRef.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlElementRefs.class)) {
-
- findAndProcessObjectFactory(cls);
-
- property = buildReferenceProperty(info, javaHasAnnotations, propertyName, ptype);
- if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
- XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
+ // do Nothing
+ } catch (IllegalAccessException e) {
+ // do Nothing
+ } catch (JAXBException ex) {
+ if (ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !helper.isAnnotationPresent(javaField, XmlTransient.class)) {
+ throw ex;
+ }
+ }
+ }
+ }
+
+ if (helper.isAnnotationPresent(javaField, XmlTransient.class)) {
+ if (property != null) {
+ property.setTransient(true);
+ }
+ }
+ }
+ return properties;
+ }
+
+ /*
+ * Create a new Property Object and process the annotations that are common
+ * to fields and methods
+ */
+ Property buildNewProperty(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, String propertyName, JavaClass ptype) {
+ Property property = null;
+ if (helper.isAnnotationPresent(javaHasAnnotations, XmlElements.class)) {
+ property = buildChoiceProperty(javaHasAnnotations);
+ } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlElementRef.class) || helper.isAnnotationPresent(javaHasAnnotations, XmlElementRefs.class)) {
+
+ findAndProcessObjectFactory(cls);
+
+ property = buildReferenceProperty(info, javaHasAnnotations, propertyName, ptype);
+ if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
+ XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
property.setIsAny(true);
if (anyElement.value() != null) {
property.setDomHandlerClassName(anyElement.value().getName());
}
property.setLax(anyElement.lax());
- info.setAnyElementPropertyName(propertyName);
- }
- } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
- findAndProcessObjectFactory(cls);
- XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
- property = new Property(helper);
- property.setIsAny(true);
+ info.setAnyElementPropertyName(propertyName);
+ }
+ } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlAnyElement.class)) {
+ findAndProcessObjectFactory(cls);
+ XmlAnyElement anyElement = (XmlAnyElement) helper.getAnnotation(javaHasAnnotations, XmlAnyElement.class);
+ property = new Property(helper);
+ property.setIsAny(true);
if (anyElement.value() != null) {
property.setDomHandlerClassName(anyElement.value().getName());
}
@@ -1970,60 +2020,60 @@ public class AnnotationsProcessor {
property.setElement(javaHasAnnotations);
// if there is a TypeInfo for ptype check it for transient, otherwise
- // check the class
- if (helper.isCollectionType(ptype)) {
- JavaClass componentType = helper.getJavaClass(Object.class);
-
- Collection typeArgs = ptype.getActualTypeArguments();
- if(typeArgs.size() > 0) {
- componentType = (JavaClass) typeArgs.iterator().next();
- }
- updatePropertyType(property, ptype, componentType);
- }else{
- updatePropertyType(property, ptype, ptype);
- }
-
- if(helper.isAnnotationPresent(javaHasAnnotations, XmlVariableNode.class)){
- XmlVariableNode variableNode = (XmlVariableNode) helper.getAnnotation(javaHasAnnotations, XmlVariableNode.class);
- if(variableNode.type() != XmlVariableNode.DEFAULT.class){
- property.setVariableClassName(variableNode.type().getName());
-
- JavaClass componentType = helper.getJavaClass(variableNode.type());
-
- if(helper.isCollectionType(ptype)){
- property.setGenericType(componentType);
- }else{
- property.setType(componentType);
- }
-
- }
- if(!variableNode.value().equals("##default")){
- property.setVariableAttributeName(variableNode.value());
- }
- property.setVariableNodeAttribute(variableNode.attribute());
- }
-
-
- if((ptype.isArray() && !areEquals(ptype, byte[].class)) || (helper.isCollectionType(ptype) && !helper.isAnnotationPresent(javaHasAnnotations, XmlList.class)) ){
- property.setNillable(true);
- }
- processPropertyAnnotations(info, cls, javaHasAnnotations, property);
-
- if (helper.isAnnotationPresent(javaHasAnnotations, XmlPath.class)) {
- XmlPath xmlPath = (XmlPath) helper.getAnnotation(javaHasAnnotations, XmlPath.class);
- property.setXmlPath(xmlPath.value());
- Field tempField = new XMLField(xmlPath.value());
- boolean isAttribute = tempField.getLastXPathFragment().isAttribute();
- property.setIsAttribute(isAttribute);
+ // check the class
+ if (helper.isCollectionType(ptype)) {
+ JavaClass componentType = helper.getJavaClass(Object.class);
+
+ Collection typeArgs = ptype.getActualTypeArguments();
+ if(!typeArgs.isEmpty()) {
+ componentType = (JavaClass) typeArgs.iterator().next();
+ }
+ updatePropertyType(property, ptype, componentType);
+ }else{
+ updatePropertyType(property, ptype, ptype);
+ }
+
+ if(helper.isAnnotationPresent(javaHasAnnotations, XmlVariableNode.class)){
+ XmlVariableNode variableNode = (XmlVariableNode) helper.getAnnotation(javaHasAnnotations, XmlVariableNode.class);
+ if(variableNode.type() != XmlVariableNode.DEFAULT.class){
+ property.setVariableClassName(variableNode.type().getName());
+
+ JavaClass componentType = helper.getJavaClass(variableNode.type());
+
+ if(helper.isCollectionType(ptype)){
+ property.setGenericType(componentType);
+ }else{
+ property.setType(componentType);
+ }
+
+ }
+ if(!variableNode.value().equals("##default")){
+ property.setVariableAttributeName(variableNode.value());
+ }
+ property.setVariableNodeAttribute(variableNode.attribute());
+ }
+
+
+ if((ptype.isArray() && !areEquals(ptype, byte[].class)) || (helper.isCollectionType(ptype) && !helper.isAnnotationPresent(javaHasAnnotations, XmlList.class)) ){
+ property.setNillable(true);
+ }
+ processPropertyAnnotations(info, cls, javaHasAnnotations, property);
+
+ if (helper.isAnnotationPresent(javaHasAnnotations, XmlPath.class)) {
+ XmlPath xmlPath = (XmlPath) helper.getAnnotation(javaHasAnnotations, XmlPath.class);
+ property.setXmlPath(xmlPath.value());
+ Field tempField = new XMLField(xmlPath.value());
+ boolean isAttribute = tempField.getLastXPathFragment().isAttribute();
+ property.setIsAttribute(isAttribute);
// set schema name
String schemaName = XMLProcessor.getNameFromXPath(xmlPath.value(), property.getPropertyName(), isAttribute);
- QName qName;
- NamespaceInfo nsInfo = getPackageInfoForPackage(cls).getNamespaceInfo();
- if(isAttribute){
- if (nsInfo.isAttributeFormQualified()) {
- qName = new QName(nsInfo.getNamespace(), schemaName);
- } else {
- qName = new QName(schemaName);
+ QName qName;
+ NamespaceInfo nsInfo = getPackageInfoForPackage(cls).getNamespaceInfo();
+ if(isAttribute){
+ if (nsInfo.isAttributeFormQualified()) {
+ qName = new QName(nsInfo.getNamespace(), schemaName);
+ } else {
+ qName = new QName(schemaName);
}
}else{
if (nsInfo.isElementFormQualified()) {
@@ -2047,13 +2097,13 @@ public class AnnotationsProcessor {
String predicatePath = currentPath;
TypeInfo targetInfo = info;
if(fragment.getNextFragment() == null) {
- //if this is the last fragment, and there's no text after, then this is
- //complex. May need to add the attribute property to the target type.
- processReferencedClass(ptype);
- TypeInfo predicateTypeInfo = typeInfo.get(ptype.getQualifiedName());
- if(predicateTypeInfo != null) {
- targetInfo = predicateTypeInfo;
- predicatePath = "";
+ //if this is the last fragment, and there's no text after, then this is
+ //complex. May need to add the attribute property to the target type.
+ processReferencedClass(ptype);
+ TypeInfo predicateTypeInfo = typeInfos.get(ptype.getQualifiedName());
+ if(predicateTypeInfo != null) {
+ targetInfo = predicateTypeInfo;
+ predicatePath = "";
}
}
Property predicateProperty = new Property(helper);
@@ -2080,13 +2130,13 @@ public class AnnotationsProcessor {
} else {
currentPath += fragment.getXPath();
}
- currentPath += "/";
- fragment = fragment.getNextFragment();
- }
-
- } else {
- property.setSchemaName(getQNameForProperty(property, propertyName, javaHasAnnotations, getPackageInfoForPackage(cls).getNamespaceInfo(), info));
- }
+ currentPath += "/";
+ fragment = fragment.getNextFragment();
+ }
+
+ } else {
+ property.setSchemaName(getQNameForProperty(property, propertyName, javaHasAnnotations, getPackageInfoForPackage(cls).getNamespaceInfo(), info));
+ }
ptype = property.getActualType();
if (ptype.isPrimitive()) {
@@ -2097,76 +2147,75 @@ public class AnnotationsProcessor {
property.setIsRequired(true);
}
}
-
- // apply class level adapters - don't override property level adapter
- if (!property.isSetXmlJavaTypeAdapter()) {
- TypeInfo refClassInfo = getTypeInfo().get(ptype.getQualifiedName());
- if (refClassInfo != null && refClassInfo.isSetXmlJavaTypeAdapter()) {
- org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter = null;
- try {
+
+ // apply class level adapters - don't override property level adapter
+ if (!property.isSetXmlJavaTypeAdapter()) {
+ TypeInfo refClassInfo = getTypeInfos().get(ptype.getQualifiedName());
+ if (refClassInfo != null && refClassInfo.isSetXmlJavaTypeAdapter()) {
+ org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter xmlJavaTypeAdapter = null;
+ try {
xmlJavaTypeAdapter = refClassInfo.getXmlJavaTypeAdapter();
property.setXmlJavaTypeAdapter(refClassInfo.getXmlJavaTypeAdapter());
} catch (JAXBException e) {
throw JAXBException.invalidTypeAdapterClass(xmlJavaTypeAdapter.getValue(), cls.getName());
}
}
- }
-
- if(property.isXmlTransformation()){
- referencedByTransformer.add(property.getType().getName());
- }
- return property;
- }
-
-
- private void updatePropertyType(Property property, JavaClass ptype, JavaClass componentType){
- TypeInfo componentTypeInfo = typeInfo.get(componentType);
- if((componentTypeInfo != null && !componentTypeInfo.isTransient()) || !helper.isAnnotationPresent(componentType, XmlTransient.class)){
- property.setType(ptype);
- }else{
+ }
+
+ if(property.isXmlTransformation()){
+ referencedByTransformer.add(property.getType().getName());
+ }
+ return property;
+ }
+
+
+ private void updatePropertyType(Property property, JavaClass ptype, JavaClass componentType){
+ TypeInfo componentTypeInfo = typeInfos.get(componentType);
+ if((componentTypeInfo != null && !componentTypeInfo.isTransient()) || !helper.isAnnotationPresent(componentType, XmlTransient.class)){
+ property.setType(ptype);
+ }else{
JavaClass parent = componentType.getSuperclass();
while (parent != null) {
if (parent.getName().equals(JAVA_LANG_OBJECT)) {
property.setTransientType(true);
property.setType(ptype);
break;
- }
- // if there is a TypeInfo for parent check it for transient,
- // otherwise check the class
- TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName());
- if ((parentTypeInfo != null && !parentTypeInfo.isTransient()) || !helper.isAnnotationPresent(parent, XmlTransient.class)) {
- property.setType(parent);
- break;
+ }
+ // if there is a TypeInfo for parent check it for transient,
+ // otherwise check the class
+ TypeInfo parentTypeInfo = typeInfos.get(parent.getQualifiedName());
+ if ((parentTypeInfo != null && !parentTypeInfo.isTransient()) || !helper.isAnnotationPresent(parent, XmlTransient.class)) {
+ property.setType(parent);
+ break;
}
parent = parent.getSuperclass();
- }
- }
- }
-
- /**
- * Build a new 'choice' property. Here, we flag a new property as a 'choice'
- * and create/set an XmlModel XmlElements object based on the @XmlElements
- * annotation.
- *
- * Validation and building of the XmlElement properties will be done during
- * finalizeProperties in the processChoiceProperty method.
- *
- * @param javaHasAnnotations
- * @return
- */
+ }
+ }
+ }
+
+ /**
+ * Build a new 'choice' property. Here, we flag a new property as a 'choice'
+ * and create/set an XmlModel XmlElements object based on the @XmlElements
+ * annotation.
+ *
+ * Validation and building of the XmlElement properties will be done during
+ * finalizeProperties in the processChoiceProperty method.
+ *
+ * @param javaHasAnnotations
+ * @return
+ */
private Property buildChoiceProperty(JavaHasAnnotations javaHasAnnotations) {
Property choiceProperty = new Property(helper);
choiceProperty.setChoice(true);
boolean isIdRef = helper.isAnnotationPresent(javaHasAnnotations, XmlIDREF.class);
choiceProperty.setIsXmlIdRef(isIdRef);
- // build an XmlElement to set on the Property
- org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements();
- XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value();
- for (int i = 0; i < elements.length; i++) {
- XmlElement next = elements[i];
- org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement();
- xmlElement.setDefaultValue(next.defaultValue());
- xmlElement.setName(next.name());
+ // build an XmlElement to set on the Property
+ org.eclipse.persistence.jaxb.xmlmodel.XmlElements xmlElements = new org.eclipse.persistence.jaxb.xmlmodel.XmlElements();
+ XmlElement[] elements = ((XmlElements) helper.getAnnotation(javaHasAnnotations, XmlElements.class)).value();
+ for (XmlElement next : elements) {
+ org.eclipse.persistence.jaxb.xmlmodel.XmlElement xmlElement = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement();
+ xmlElement.setDefaultValue(next.defaultValue());
+ xmlElement.setName(next.name());
xmlElement.setNamespace(next.namespace());
xmlElement.setNillable(next.nillable());
xmlElement.setRequired(next.required());
@@ -2250,13 +2299,13 @@ public class AnnotationsProcessor {
/**
* Complete creation of a 'choice' property. Here, a Property is created for
- * each XmlElement in the XmlElements list. Validation is performed as well.
- * Each created Property is added to the owning Property's list of choice
- * properties.
- *
- * @param choiceProperty
- * @param info
- * @param cls
+ * each XmlElement in the XmlElements list. Validation is performed as well.
+ * Each created Property is added to the owning Property's list of choice
+ * properties.
+ *
+ * @param choiceProperty
+ * @param info
+ * @param cls
* @param propertyType
*/
private void processChoiceProperty(Property choiceProperty, TypeInfo info, JavaClass cls, JavaClass propertyType) {
@@ -2272,13 +2321,13 @@ public class AnnotationsProcessor {
XmlPath[] paths = null;
if (helper.isAnnotationPresent(choiceProperty.getElement(), XmlPaths.class)) {
- XmlPaths pathAnnotation = (XmlPaths) helper.getAnnotation(choiceProperty.getElement(), XmlPaths.class);
- paths = pathAnnotation.value();
- }
- ArrayList<Property> choiceProperties = new ArrayList<Property>();
- for (int i = 0; i < choiceProperty.getXmlElements().getXmlElement().size(); i++) {
- org.eclipse.persistence.jaxb.xmlmodel.XmlElement next = choiceProperty.getXmlElements().getXmlElement().get(i);
- Property choiceProp = new Property(helper);
+ XmlPaths pathAnnotation = (XmlPaths) helper.getAnnotation(choiceProperty.getElement(), XmlPaths.class);
+ paths = pathAnnotation.value();
+ }
+ List<Property> choiceProperties = new ArrayList<Property>();
+ for (int i = 0; i < choiceProperty.getXmlElements().getXmlElement().size(); i++) {
+ org.eclipse.persistence.jaxb.xmlmodel.XmlElement next = choiceProperty.getXmlElements().getXmlElement().get(i);
+ Property choiceProp = new Property(helper);
String name;
String namespace;
@@ -2316,18 +2365,18 @@ public class AnnotationsProcessor {
}
}
- // if the property has xml-idref, the target type of each
- // xml-element in the list must have an xml-id property
- if (choiceProperty.isXmlIdRef()) {
-
- JavaClass nextCls = helper.getJavaClass(next.getType());
- processReferencedClass(nextCls);
- TypeInfo tInfo = typeInfo.get(next.getType());
-
-
- if (tInfo == null || !tInfo.isIDSet()) {
- throw JAXBException.invalidXmlElementInXmlElementsList(propertyName, name);
- }
+ // if the property has xml-idref, the target type of each
+ // xml-element in the list must have an xml-id property
+ if (choiceProperty.isXmlIdRef()) {
+
+ JavaClass nextCls = helper.getJavaClass(next.getType());
+ processReferencedClass(nextCls);
+ TypeInfo tInfo = typeInfos.get(next.getType());
+
+
+ if (tInfo == null || !tInfo.isIDSet()) {
+ throw JAXBException.invalidXmlElementInXmlElementsList(propertyName, name);
+ }
}
QName qName = null;
@@ -2367,34 +2416,34 @@ public class AnnotationsProcessor {
} else {
choiceProp.setType(pType);
}
- }
- }
- }
-
- choiceProp.setSchemaName(qName);
- choiceProp.setSchemaType(getSchemaTypeFor(choiceProp.getType()));
- choiceProp.setIsXmlIdRef(choiceProperty.isXmlIdRef());
- choiceProp.setXmlElementWrapper(choiceProperty.getXmlElementWrapper());
- choiceProperties.add(choiceProp);
- processReferencedClass(choiceProp.getType());
- TypeInfo newInfo = typeInfo.get(choiceProp.getType().getQualifiedName());
- if (newInfo != null && newInfo.isTransient()) {
- throw JAXBException.invalidReferenceToTransientClass(info.getJavaClassName(), choiceProperty.getPropertyName(), newInfo.getJavaClassName());
- }
- }
- choiceProperty.setChoiceProperties(choiceProperties);
- }
-
+ }
+ }
+ }
+
+ choiceProp.setSchemaName(qName);
+ choiceProp.setSchemaType(getSchemaTypeFor(choiceProp.getType()));
+ choiceProp.setIsXmlIdRef(choiceProperty.isXmlIdRef());
+ choiceProp.setXmlElementWrapper(choiceProperty.getXmlElementWrapper());
+ choiceProperties.add(choiceProp);
+ processReferencedClass(choiceProp.getType());
+ TypeInfo newInfo = typeInfos.get(choiceProp.getType().getQualifiedName());
+ if (newInfo != null && newInfo.isTransient()) {
+ throw JAXBException.invalidReferenceToTransientClass(info.getJavaClassName(), choiceProperty.getPropertyName(), newInfo.getJavaClassName());
+ }
+ }
+ choiceProperty.setChoiceProperties(choiceProperties);
+ }
+
/**
* Build a reference property. Here we will build a list of XML model
* XmlElementRef objects, based on the @XmlElement(s) annotation, to store
- * on the Property. Processing of the elements and validation will be
- * performed during the finalize property phase via the
- * processReferenceProperty method.
- *
- * @param info
- * @param javaHasAnnotations
- * @param propertyName
+ * on the Property. Processing of the elements and validation will be
+ * performed during the finalize property phase via the
+ * processReferenceProperty method.
+ *
+ * @param info
+ * @param javaHasAnnotations
+ * @param propertyName
* @param ptype
* @return
*/
@@ -2415,54 +2464,54 @@ public class AnnotationsProcessor {
List<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef> eltRefs = new ArrayList<org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef>();
for (XmlElementRef nextRef : elementRefs) {
org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef eltRef = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef();
- eltRef.setName(nextRef.name());
- eltRef.setNamespace(nextRef.namespace());
- eltRef.setType(nextRef.type().getName());
- property.setIsRequired(true);
- try{
- Method requireMethod = PrivilegedAccessHelper.getMethod(XmlElementRef.class, "required", new Class[0], true);
- if(requireMethod != null){
- Boolean val = (Boolean)PrivilegedAccessHelper.invokeMethod(requireMethod, nextRef);
- property.setIsRequired(val);
- }
- } catch (Exception exception){
- }
- eltRefs.add(eltRef);
+ eltRef.setName(nextRef.name());
+ eltRef.setNamespace(nextRef.namespace());
+ eltRef.setType(nextRef.type().getName());
+ property.setIsRequired(true);
+ try{
+ Method requireMethod = PrivilegedAccessHelper.getMethod(XmlElementRef.class, "required", new Class[0], true);
+ if(requireMethod != null){
+ Boolean val = (Boolean)PrivilegedAccessHelper.invokeMethod(requireMethod, nextRef);
+ property.setIsRequired(val);
+ }
+ } catch (Exception exception){
+ }
+ eltRefs.add(eltRef);
}
property.setIsReference(true);
property.setXmlElementRefs(eltRefs);
return property;
}
-
- /**
- * Build a reference property.
- *
- * @param property
- * @param info
- * @param javaHasAnnotations
- * @return
- */
- private Property processReferenceProperty(Property property, TypeInfo info, JavaClass cls) {
-
- for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) {
- JavaClass type = property.getType();
- String typeName = type.getQualifiedName();
- if (helper.isCollectionType(property.getType())) {
- if (type.hasActualTypeArguments()) {
- type = property.getGenericType();
+
+ /**
+ * Build a reference property.
+ *
+ * @param property
+ * @param info
+ * @param cls
+ * @return
+ */
+ private Property processReferenceProperty(Property property, TypeInfo info, JavaClass cls) {
+
+ for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) {
+ JavaClass type = property.getType();
+ String typeName;
+ if (helper.isCollectionType(property.getType())) {
+ if (type.hasActualTypeArguments()) {
+ type = property.getGenericType();
typeName = type.getQualifiedName();
}
}
if (!(nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef.DEFAULT") || nextRef.getType().equals("javax.xml.bind.annotation.XmlElementRef$DEFAULT"))) {
- typeName = nextRef.getType();
- type = helper.getJavaClass(typeName);
- }
-
- boolean missingReference = true;
- for (Entry<String, ElementDeclaration> entry : xmlRootElements.entrySet()) {
- ElementDeclaration entryValue = entry.getValue();
+ typeName = nextRef.getType();
+ type = helper.getJavaClass(typeName);
+ }
+
+ boolean missingReference = true;
+ for (Entry<String, ElementDeclaration> entry : xmlRootElements.entrySet()) {
+ ElementDeclaration entryValue = entry.getValue();
if (!(areEquals(type, Object.class)) && type.isAssignableFrom(entryValue.getJavaType())) {
addReferencedElement(property, entryValue);
missingReference = false;
@@ -2475,13 +2524,13 @@ public class AnnotationsProcessor {
namespace = EMPTY_STRING;
}
QName qname = new QName(namespace, name);
- JavaClass scopeClass = cls;
- ElementDeclaration referencedElement = null;
- while (!(scopeClass.getName().equals(JAVA_LANG_OBJECT))) {
- HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
- if (elements != null) {
- referencedElement = elements.get(qname);
- }
+ JavaClass scopeClass = cls;
+ ElementDeclaration referencedElement = null;
+ while (!(scopeClass.getName().equals(JAVA_LANG_OBJECT))) {
+ Map<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
+ if (elements != null) {
+ referencedElement = elements.get(qname);
+ }
if (referencedElement != null) {
break;
}
@@ -2496,29 +2545,29 @@ public class AnnotationsProcessor {
throw org.eclipse.persistence.exceptions.JAXBException.invalidElementRef(property.getPropertyName(), cls.getName());
}
}
- }
- return property;
- }
-
- private void processReferencePropertyTypes(Property property, TypeInfo info, JavaClass theClass) {
- for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) {
- JavaClass type = property.getType();
+ }
+ return property;
+ }
+
+ private void processReferencePropertyTypes(Property property, TypeInfo info, JavaClass theClass) {
+ for (org.eclipse.persistence.jaxb.xmlmodel.XmlElementRef nextRef : property.getXmlElementRefs()) {
+ JavaClass type = property.getType();
String typeName = type.getQualifiedName();
if (helper.isCollectionType(property.getType())) {
if (type.hasActualTypeArguments()) {
type = property.getGenericType();
- typeName = type.getQualifiedName();
- }
- }
-
- if(JAVAX_XML_BIND_JAXBELEMENT.equals(typeName)){
- Collection args = type.getActualTypeArguments();
- if(args.size() > 0){
- JavaClass theType = (JavaClass) args.iterator().next();
- processReferencedClass(theType);
- }
- }
-
+ typeName = type.getQualifiedName();
+ }
+ }
+
+ if(JAVAX_XML_BIND_JAXBELEMENT.equals(typeName)){
+ Collection args = type.getActualTypeArguments();
+ if(args.size() > 0){
+ JavaClass theType = (JavaClass) args.iterator().next();
+ processReferencedClass(theType);
+ }
+ }
+
// for DEFAULT, if from XML the type will be
// "XmlElementRef.DEFAULT",
// and from annotations the value will be "XmlElementref$DEFAULT"
@@ -2527,87 +2576,87 @@ public class AnnotationsProcessor {
type = helper.getJavaClass(typeName);
}
processReferencedClass(type);
- }
- }
-
- private void processPropertyAnnotations(TypeInfo info, JavaClass cls, JavaHasAnnotations javaHasAnnotations, Property property) {
- // Check for mixed context
- if (helper.isAnnotationPresent(javaHasAnnotations, XmlMixed.class)) {
- info.setMixed(true);
- property.setMixedContent(true);
- findAndProcessObjectFactory(cls);
- }
- if (helper.isAnnotationPresent(javaHasAnnotations, XmlContainerProperty.class)) {
- XmlContainerProperty container = (XmlContainerProperty) helper.getAnnotation(javaHasAnnotations, XmlContainerProperty.class);
- property.setInverseReferencePropertyName(container.value());
- property.setInverseReferencePropertyGetMethodName(container.getMethodName());
- property.setInverseReferencePropertySetMethodName(container.setMethodName());
- } else if (helper.isAnnotationPresent(javaHasAnnotations, XmlInverseReference.class)) {
- XmlInverseReference inverseReference = (XmlInverseReference) helper.getAnnotation(javaHasAnnotations, XmlInverseReference.class);
- property.setInverseReferencePropertyName(inverseReference.mappedBy());
-
- TypeInfo targetInfo = this.getTypeInfo().get(property.getActualType().getName());
- if (targetInfo != null && targetInfo.getXmlAccessType() == XmlAccessType.PROPERTY) {
- String propName = property.getPropertyName();
- propName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
+ }
+ }
+
+ private void processPropertyAnnotations(TypeInfo info, JavaClass cls, JavaHasAnnotations propertyElement, Property property) {
+ // Check for mixed context
+ if (helper.isAnnotationPresent(propertyElement, XmlMixed.class)) {
+ info.setMixed(true);
+ property.setMixedContent(true);
+ findAndProcessObjectFactory(cls);
+ }
+ if (helper.isAnnotationPresent(propertyElement, XmlContainerProperty.class)) {
+ XmlContainerProperty container = (XmlContainerProperty) helper.getAnnotation(propertyElement, XmlContainerProperty.class);
+ property.setInverseReferencePropertyName(container.value());
+ property.setInverseReferencePropertyGetMethodName(container.getMethodName());
+ property.setInverseReferencePropertySetMethodName(container.setMethodName());
+ } else if (helper.isAnnotationPresent(propertyElement, XmlInverseReference.class)) {
+ XmlInverseReference inverseReference = (XmlInverseReference) helper.getAnnotation(propertyElement, XmlInverseReference.class);
+ property.setInverseReferencePropertyName(inverseReference.mappedBy());
+
+ TypeInfo targetInfo = this.getTypeInfos().get(property.getActualType().getName());
+ if (targetInfo != null && targetInfo.getXmlAccessType() == XmlAccessType.PROPERTY) {
+ String propName = property.getPropertyName();
+ propName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
property.setInverseReferencePropertyGetMethodName(GET_STR + propName);
- property.setInverseReferencePropertySetMethodName(SET_STR + propName);
- }
-
- property.setInverseReference(true, helper.isAnnotationPresent(javaHasAnnotations, XmlElement.class));
- }
-
- processXmlJavaTypeAdapter(property, info, cls);
- if (helper.isAnnotationPresent(property.getElement(), XmlAttachmentRef.class) && areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) {
- property.setIsSwaAttachmentRef(true);
- property.setSchemaType(Constants.SWA_REF_QNAME);
- }
+ property.setInverseReferencePropertySetMethodName(SET_STR + propName);
+ }
+
+ property.setInverseReference(true, helper.isAnnotationPresent(propertyElement, XmlElement.class));
+ }
+
+ processXmlJavaTypeAdapter(property, info, cls);
+ if (helper.isAnnotationPresent(propertyElement, XmlAttachmentRef.class) && areEquals(property.getActualType(), JAVAX_ACTIVATION_DATAHANDLER)) {
+ property.setIsSwaAttachmentRef(true);
+ property.setSchemaType(Constants.SWA_REF_QNAME);
+ }
processXmlElement(property, info);
// JavaClass ptype = property.getActualType();
if (!(property.isSwaAttachmentRef()) && isMtomAttachment(property)) {
- property.setIsMtomAttachment(true);
- property.setSchemaType(Constants.BASE_64_BINARY_QNAME);
- }
- if (helper.isAnnotationPresent(property.getElement(), XmlMimeType.class)) {
- property.setMimeType(((XmlMimeType) helper.getAnnotation(property.getElement(), XmlMimeType.class)).value());
- }
- // set indicator for inlining binary data - setting this to true on a
- // non-binary data type won't have any affect
- if (helper.isAnnotationPresent(property.getElement(), XmlInlineBinaryData.class) || info.isBinaryDataToBeInlined()) {
- property.setisInlineBinaryData(true);
- }
-
- // Get schema-type info if specified and set it on the property for
- // later use:
- if (helper.isAnnotationPresent(property.getElement(), XmlSchemaType.class)) {
- XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(property.getElement(), XmlSchemaType.class);
- QName schemaTypeQname = new QName(schemaType.namespace(), schemaType.name());
- property.setSchemaType(schemaTypeQname);
- }
-
- if (helper.isAnnotationPresent(property.getElement(), XmlAttribute.class)) {
- property.setIsAttribute(true);
- property.setIsRequired(((XmlAttribute) helper.getAnnotation(property.getElement(), XmlAttribute.class)).required());
- }
-
- if (helper.isAnnotationPresent(property.getElement(), XmlAnyAttribute.class)) {
- if (info.isSetAnyAttributePropertyName() && !info.getAnyAttributePropertyName().equals(property.getPropertyName())) {
- throw org.eclipse.persistence.exceptions.JAXBException.multipleAnyAttributeMapping(cls.getName());
- }
+ property.setIsMtomAttachment(true);
+ property.setSchemaType(Constants.BASE_64_BINARY_QNAME);
+ }
+ if (helper.isAnnotationPresent(propertyElement, XmlMimeType.class)) {
+ property.setMimeType(((XmlMimeType) helper.getAnnotation(propertyElement, XmlMimeType.class)).value());
+ }
+ // set indicator for inlining binary data - setting this to true on a
+ // non-binary data type won't have any affect
+ if (helper.isAnnotationPresent(propertyElement, XmlInlineBinaryData.class) || info.isBinaryDataToBeInlined()) {
+ property.setisInlineBinaryData(true);
+ }
+
+ // Get schema-type info if specified and set it on the property for
+ // later use:
+ if (helper.isAnnotationPresent(propertyElement, XmlSchemaType.class)) {
+ XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(propertyElement, XmlSchemaType.class);
+ QName schemaTypeQname = new QName(schemaType.namespace(), schemaType.name());
+ property.setSchemaType(schemaTypeQname);
+ }
+
+ if (helper.isAnnotationPresent(propertyElement, XmlAttribute.class)) {
+ property.setIsAttribute(true);
+ property.setIsRequired(((XmlAttribute) helper.getAnnotation(propertyElement, XmlAttribute.class)).required());
+ }
+
+ if (helper.isAnnotationPresent(propertyElement, XmlAnyAttribute.class)) {
+ if (info.isSetAnyAttributePropertyName() && !info.getAnyAttributePropertyName().equals(property.getPropertyName())) {
+ throw org.eclipse.persistence.exceptions.JAXBException.multipleAnyAttributeMapping(cls.getName());
+ }
if (!helper.isMapType(property.getType())) {
throw org.eclipse.persistence.exceptions.JAXBException.anyAttributeOnNonMap(property.getPropertyName());
}
property.setIsAnyAttribute(true);
info.setAnyAttributePropertyName(property.getPropertyName());
- }
-
- // Make sure XmlElementWrapper annotation is on a collection or array
- if (helper.isAnnotationPresent(property.getElement(), XmlElementWrapper.class)) {
- XmlElementWrapper wrapper = (XmlElementWrapper) helper.getAnnotation(property.getElement(), XmlElementWrapper.class);
- org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper xmlEltWrapper = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper();
-
- String wrapperName = wrapper.name();
+ }
+
+ // Make sure XmlElementWrapper annotation is on a collection or array
+ if (helper.isAnnotationPresent(propertyElement, XmlElementWrapper.class)) {
+ XmlElementWrapper wrapper = (XmlElementWrapper) helper.getAnnotation(propertyElement, XmlElementWrapper.class);
+ org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper xmlEltWrapper = new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper();
+
+ String wrapperName = wrapper.name();
if (wrapperName.equals(XMLProcessor.DEFAULT)) {
wrapperName = info.getXmlNameTransformer().transformElementName(property.getPropertyName());
}
@@ -2615,67 +2664,67 @@ public class AnnotationsProcessor {
xmlEltWrapper.setNamespace(wrapper.namespace());
xmlEltWrapper.setNillable(wrapper.nillable());
xmlEltWrapper.setRequired(wrapper.required());
- property.setXmlElementWrapper(xmlEltWrapper);
- }
-
- if (helper.isAnnotationPresent(property.getElement(), XmlList.class)) {
- // Make sure XmlList annotation is on a collection or array
- if (!helper.isCollectionType(property.getType()) && !property.getType().isArray()) {
- throw JAXBException.invalidList(property.getPropertyName());
- }
- property.setIsXmlList(true);
- }
-
- if (helper.isAnnotationPresent(property.getElement(), XmlValue.class)) {
- property.setIsXmlValue(true);
- info.setXmlValueProperty(property);
- }
-
- if (helper.isAnnotationPresent(property.getElement(), XmlReadOnly.class)) {
- property.setReadOnly(true);
- }
- if (helper.isAnnotationPresent(property.getElement(), XmlWriteOnly.class)) {
- property.setWriteOnly(true);
- }
- if (helper.isAnnotationPresent(property.getElement(), XmlCDATA.class)) {
- property.setCdata(true);
- }
- if (helper.isAnnotationPresent(property.getElement(), XmlAccessMethods.class)) {
- XmlAccessMethods accessMethods = (XmlAccessMethods) helper.getAnnotation(property.getElement(), XmlAccessMethods.class);
- if (!(accessMethods.getMethodName().equals(EMPTY_STRING))) {
- property.setGetMethodName(accessMethods.getMethodName());
+ property.setXmlElementWrapper(xmlEltWrapper);
+ }
+
+ if (helper.isAnnotationPresent(propertyElement, XmlList.class)) {
+ // Make sure XmlList annotation is on a collection or array
+ if (!helper.isCollectionType(property.getType()) && !property.getType().isArray()) {
+ throw JAXBException.invalidList(property.getPropertyName());
}
+ property.setIsXmlList(true);
+ }
+
+ if (helper.isAnnotationPresent(propertyElement, XmlValue.class)) {
+ property.setIsXmlValue(true);
+ info.setXmlValueProperty(property);
+ }
+
+ if (helper.isAnnotationPresent(propertyElement, XmlReadOnly.class)) {
+ property.setReadOnly(true);
+ }
+ if (helper.isAnnotationPresent(propertyElement, XmlWriteOnly.class)) {
+ property.setWriteOnly(true);
+ }
+ if (helper.isAnnotationPresent(propertyElement, XmlCDATA.class)) {
+ property.setCdata(true);
+ }
+ if (helper.isAnnotationPresent(propertyElement, XmlAccessMethods.class)) {
+ XmlAccessMethods accessMethods = (XmlAccessMethods) helper.getAnnotation(propertyElement, XmlAccessMethods.class);
+ if (!(accessMethods.getMethodName().equals(EMPTY_STRING))) {
+ property.setGetMethodName(accessMethods.getMethodName());
+ }
if (!(accessMethods.setMethodName().equals(EMPTY_STRING))) {
property.setSetMethodName(accessMethods.setMethodName());
}
if (!(property.isMethodProperty())) {
property.setMethodProperty(true);
}
- }
-
- // handle user properties
- if (helper.isAnnotationPresent(property.getElement(), XmlProperties.class)) {
- XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(property.getElement(), XmlProperties.class);
- Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value());
- property.setUserProperties(propertiesMap);
- } else if (helper.isAnnotationPresent(property.getElement(), XmlProperty.class)) {
- XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(property.getElement(), XmlProperty.class);
- Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty });
- property.setUserProperties(propertiesMap);
- }
- // handle XmlKey
- if (helper.isAnnotationPresent(property.getElement(), XmlKey.class)) {
- info.addXmlKeyProperty(property);
- }
- // handle XmlJoinNode(s)
+ }
+
+ // handle user properties
+ if (helper.isAnnotationPresent(propertyElement, XmlProperties.class)) {
+ XmlProperties xmlProperties = (XmlProperties) helper.getAnnotation(propertyElement, XmlProperties.class);
+ Map<Object, Object> propertiesMap = createUserPropertiesMap(xmlProperties.value());
+ property.setUserProperties(propertiesMap);
+ } else if (helper.isAnnotationPresent(propertyElement, XmlProperty.class)) {
+ XmlProperty xmlProperty = (XmlProperty) helper.getAnnotation(propertyElement, XmlProperty.class);
+ Map<Object, Object> propertiesMap = createUserPropertiesMap(new XmlProperty[] { xmlProperty });
+ property.setUserProperties(propertiesMap);
+ }
+ // handle XmlKey
+ if (helper.isAnnotationPresent(propertyElement, XmlKey.class)) {
+ info.addXmlKeyProperty(property);
+ }
+ // handle XmlJoinNode(s)
processXmlJoinNodes(property);
- processXmlNullPolicy(property);
-
- // Handle XmlLocation
- JavaHasAnnotations elem = property.getElement();
- if (helper.isAnnotationPresent(elem, XmlLocation.class) || helper.isAnnotationPresent(elem, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) || helper.isAnnotationPresent(elem, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS)) {
- if (!helper.getJavaClass(Constants.LOCATOR_CLASS).isAssignableFrom(property.getType())) {
- throw JAXBException.invalidXmlLocation(property.getPropertyName(), property.getType().getName());
+ processXmlNullPolicy(property);
+
+ // Handle XmlLocation
+ JavaHasAnnotations elem = propertyElement;
+ if (helper.isAnnotationPresent(elem, XmlLocation.class) || helper.isAnnotationPresent(elem, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) || helper.isAnnotationPresent(elem, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS)) {
+ if (!helper.getJavaClass(Constants.LOCATOR_CLASS).isAssignableFrom(property.getType())) {
+ throw JAXBException.invalidXmlLocation(property.getPropertyName(), property.getType().getName());
}
property.setXmlLocation(true);
}
@@ -2683,18 +2732,18 @@ public class AnnotationsProcessor {
/**
* Process XmlJoinNode(s) for a given Property. An
- * org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNode(s) will be
- * created/populated using the annotation, and set on the Property for later
- * processing.
- *
- * It is assumed that for a single join node XmlJoinNode will be used, and
- * for multiple join nodes XmlJoinNodes will be used.
- *
- * @param property
- * Property that may contain @XmlJoinNodes/@XmlJoinNode
- */
- private void processXmlJoinNodes(Property property) {
- List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList;
+ * org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNode(s) will be
+ * created/populated using the annotation, and set on the Property for later
+ * processing.
+ *
+ * It is assumed that for a single join node XmlJoinNode will be used, and
+ * for multiple join nodes XmlJoinNodes will be used.
+ *
+ * @param property
+ * Property that may contain @XmlJoinNodes/@XmlJoinNode
+ */
+ private void processXmlJoinNodes(Property property) {
+ List<org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode> xmlJoinNodeList;
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode xmlJoinNode;
org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes xmlJoinNodes;
// handle XmlJoinNodes
@@ -2727,16 +2776,16 @@ public class AnnotationsProcessor {
/**
* Responsible for validating transformer settings on a given property.
* Validates that for field transformers either a transformer class OR
- * method name is set (not both) and that an xml-path is set. Validates that
- * for attribute transformers either a transformer class OR method name is
- * set (not both).
- *
- * @param property
- */
- private void processXmlTransformationProperty(Property property) {
- if (property.isSetXmlTransformation()) {
- XmlTransformation xmlTransformation = property.getXmlTransformation();
- // validate transformer(s)
+ * method name is set (not both) and that an xml-path is set. Validates that
+ * for attribute transformers either a transformer class OR method name is
+ * set (not both).
+ *
+ * @param property
+ */
+ private void validateXmlTransformationProperty(Property property) {
+ if (property.isSetXmlTransformation()) {
+ XmlTransformation xmlTransformation = property.getXmlTransformation();
+ // validate transformer(s)
if (xmlTransformation.isSetXmlReadTransformer()) {
// validate read transformer
XmlReadTransformer readTransformer = xmlTransformation.getXmlReadTransformer();
@@ -2779,13 +2828,13 @@ public class AnnotationsProcessor {
}
}
- /**
- * Compares a JavaModel JavaClass to a Class. Equality is based on the raw
- * name of the JavaClass compared to the canonical name of the Class.
- *
- * @param src
- * @param tgt
- * @return
+ /**
+ * Compares a JavaModel JavaClass to a Class. Equality is based on the raw
+ * name of the JavaClass compared to the canonical name of the Class.
+ *
+ * @param src
+ * @param tgt
+ * @return
*/
protected boolean areEquals(JavaClass src, Class tgt) {
if (src == null || tgt == null) {
@@ -2797,21 +2846,21 @@ public class AnnotationsProcessor {
private void processXmlNullPolicy(Property property) {
if (helper.isAnnotationPresent(property.getElement(), XmlNullPolicy.class)) {
XmlNullPolicy nullPolicy = (XmlNullPolicy) helper.getAnnotation(property.getElement(), XmlNullPolicy.class);
- org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy();
- policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
- policy.setIsSetPerformedForAbsentNode(nullPolicy.isSetPerformedForAbsentNode());
- policy.setXsiNilRepresentsNull(Boolean.valueOf(nullPolicy.xsiNilRepresentsNull()));
- policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
- property.setNullPolicy(policy);
-
+ org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy();
+ policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
+ policy.setIsSetPerformedForAbsentNode(nullPolicy.isSetPerformedForAbsentNode());
+ policy.setXsiNilRepresentsNull(nullPolicy.xsiNilRepresentsNull());
+ policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
+ property.setNullPolicy(policy);
+
} else if (helper.isAnnotationPresent(property.getElement(), XmlIsSetNullPolicy.class)) {
- XmlIsSetNullPolicy nullPolicy = (XmlIsSetNullPolicy) helper.getAnnotation(property.getElement(), XmlIsSetNullPolicy.class);
- org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy();
- policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
- policy.setXsiNilRepresentsNull(Boolean.valueOf(nullPolicy.xsiNilRepresentsNull()));
- policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
- policy.setIsSetMethodName(nullPolicy.isSetMethodName());
- for (XmlParameter next : nullPolicy.isSetParameters()) {
+ XmlIsSetNullPolicy nullPolicy = (XmlIsSetNullPolicy) helper.getAnnotation(property.getElement(), XmlIsSetNullPolicy.class);
+ org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy policy = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy();
+ policy.setEmptyNodeRepresentsNull(nullPolicy.emptyNodeRepresentsNull());
+ policy.setXsiNilRepresentsNull(nullPolicy.xsiNilRepresentsNull());
+ policy.setNullRepresentationForXml(org.eclipse.persistence.jaxb.xmlmodel.XmlMarshalNullRepresentation.valueOf(nullPolicy.nullRepresentationForXml().toString()));
+ policy.setIsSetMethodName(nullPolicy.isSetMethodName());
+ for (XmlParameter next : nullPolicy.isSetParameters()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter param = new org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy.IsSetParameter();
param.setValue(next.value());
param.setType(next.type().getName());
@@ -2821,15 +2870,15 @@ public class AnnotationsProcessor {
}
}
- /**
- * Compares a JavaModel JavaClass to a Class. Equality is based on the raw
- * name of the JavaClass compared to the canonical name of the Class.
- *
- * @param src
- * @param tgt
- * @return
- */
- protected boolean areEquals(JavaClass src, String tgtCanonicalName) {
+ /**
+ * Compares a JavaModel JavaClass to a Class. Equality is based on the raw
+ * name of the JavaClass compared to the canonical name of the Class.
+ *
+ * @param src
+ * @param tgtCanonicalName
+ * @return
+ */
+ protected boolean areEquals(JavaClass src, String tgtCanonicalName) {
if (src == null || tgtCanonicalName == null) {
return false;
}
@@ -2849,34 +2898,34 @@ public class AnnotationsProcessor {
// First collect all the getters and setters
ArrayList<JavaMethod> propertyMethods = new ArrayList<JavaMethod>();
for (JavaMethod next : new ArrayList<JavaMethod>(cls.getDeclaredMethods())) {
- if(!next.isSynthetic()){
- if (((next.getName().startsWith(GET_STR) && next.getName().length() > 3) || (next.getName().startsWith(IS_STR) && next.getName().length() > 2)) && next.getParameterTypes().length == 0 && next.getReturnType() != helper.getJavaClass(java.lang.Void.class)) {
- int modifiers = next.getModifiers();
-
- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic || hasJAXBAnnotations(next))) {
- propertyMethods.add(next);
- }
- } else if (next.getName().startsWith(SET_STR) && next.getName().length() > 3 && next.getParameterTypes().length == 1) {
- int modifiers = next.getModifiers();
- if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic || hasJAXBAnnotations(next))) {
- propertyMethods.add(next);
- }
- }
- }
- }
- // Next iterate over the getters and find their setter methods, add
- // whichever one is
+ if(!next.isSynthetic()){
+ if (((next.getName().startsWith(GET_STR) && next.getName().length() > 3) || (next.getName().startsWith(IS_STR) && next.getName().length() > 2)) && next.getParameterTypes().length == 0 && next.getReturnType() != helper.getJavaClass(java.lang.Void.class)) {
+ int modifiers = next.getModifiers();
+
+ if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic || hasJAXBAnnotations(next))) {
+ propertyMethods.add(next);
+ }
+ } else if (next.getName().startsWith(SET_STR) && next.getName().length() > 3 && next.getParameterTypes().length == 1) {
+ int modifiers = next.getModifiers();
+ if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && ((onlyPublic && Modifier.isPublic(next.getModifiers())) || !onlyPublic || hasJAXBAnnotations(next))) {
+ propertyMethods.add(next);
+ }
+ }
+ }
+ }
+ // Next iterate over the getters and find their setter methods, add
+ // whichever one is
// annotated to the properties list. If neither is, use the getter
-
- // keep track of property names to avoid processing the same property
- // twice (for getter and setter)
- ArrayList<String> propertyNames = new ArrayList<String>();
- for (int i = 0; i < propertyMethods.size(); i++) {
- boolean isPropertyTransient = false;
- JavaMethod nextMethod = propertyMethods.get(i);
- String propertyName = EMPTY_STRING;
-
- JavaMethod getMethod;
+
+ // keep track of property names to avoid processing the same property
+ // twice (for getter and setter)
+ List<String> propertyNames = new ArrayList<String>();
+ for (JavaMethod propertyMethod1 : propertyMethods) {
+ boolean isPropertyTransient = false;
+ JavaMethod nextMethod = propertyMethod1;
+ String propertyName = EMPTY_STRING;
+
+ JavaMethod getMethod;
JavaMethod setMethod;
JavaMethod propertyMethod = null;
@@ -2894,31 +2943,31 @@ public class AnnotationsProcessor {
// character, if necessary
propertyName = Introspector.decapitalize(propertyName);
- JavaClass[] paramTypes = { (JavaClass) getMethod.getReturnType() };
- setMethod = cls.getDeclaredMethod(setMethodName, paramTypes);
-
- if(setMethod == null) {
- //if there's no locally declared set method, check for an inherited
- //set method
- setMethod = cls.getMethod(setMethodName, paramTypes);
- }
- if(setMethod == null && !(hasJAXBAnnotations(getMethod))) {
- //if there's no corresponding setter, and not explicitly
- //annotated, don't process
- isPropertyTransient = true;
- }
-
- if (setMethod != null && hasJAXBAnnotations(setMethod)) {
- // use the set method if it exists and is annotated
- boolean isTransient = helper.isAnnotationPresent(setMethod, XmlTransient.class);
+ JavaClass[] paramTypes = { (JavaClass) getMethod.getReturnType() };
+ setMethod = cls.getDeclaredMethod(setMethodName, paramTypes);
+
+ if (setMethod == null) {
+ //if there's no locally declared set method, check for an inherited
+ //set method
+ setMethod = cls.getMethod(setMethodName, paramTypes);
+ }
+ if (setMethod == null && !(hasJAXBAnnotations(getMethod))) {
+ //if there's no corresponding setter, and not explicitly
+ //annotated, don't process
+ isPropertyTransient = true;
+ }
+
+ if (setMethod != null && hasJAXBAnnotations(setMethod)) {
+ // use the set method if it exists and is annotated
+ boolean isTransient = helper.isAnnotationPresent(setMethod, XmlTransient.class);
boolean isLocation = helper.isAnnotationPresent(setMethod, XmlLocation.class) ||
- helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
- helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
- propertyMethod = setMethod;
- if(isTransient) {
- isPropertyTransient = true;
- // XmlLocation can also be transient
- if (isLocation) {
+ helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
+ helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
+ propertyMethod = setMethod;
+ if (isTransient) {
+ isPropertyTransient = true;
+ // XmlLocation can also be transient
+ if (isLocation) {
propertyMethod = setMethod;
info.setLocationAware(true);
}
@@ -2926,13 +2975,13 @@ public class AnnotationsProcessor {
} else if ((onlyExplicit && hasJAXBAnnotations(getMethod)) || !onlyExplicit) {
boolean isTransient = helper.isAnnotationPresent(getMethod, XmlTransient.class);
boolean isLocation = helper.isAnnotationPresent(getMethod, XmlLocation.class) ||
- helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
- helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
- propertyMethod = getMethod;
- if(isTransient) {
- isPropertyTransient = true;
- // XmlLocation can also be transient
- if (isLocation) {
+ helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
+ helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
+ propertyMethod = getMethod;
+ if (isTransient) {
+ isPropertyTransient = true;
+ // XmlLocation can also be transient
+ if (isLocation) {
propertyMethod = getMethod;
info.setLocationAware(true);
}
@@ -2943,28 +2992,28 @@ public class AnnotationsProcessor {
} else {
propertyName = nextMethod.getName().substring(3);
setMethod = nextMethod;
-
- String getMethodName = GET_STR + propertyName;
-
- getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {});
- if (getMethod == null) {
- // try is instead of get
- getMethodName = IS_STR + propertyName;
- getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] {});
- }
-
- //may look for get method on parent class
- if(getMethod == null) {
- //look for inherited getMethod
- getMethod = cls.getMethod(GET_STR + propertyName, new JavaClass[]{});
- if(getMethod == null) {
- getMethod = cls.getMethod(IS_STR + propertyName, new JavaClass[]{});
- }
- }
- if(getMethod == null && !(hasJAXBAnnotations(setMethod))) {
- isPropertyTransient = true;
- }
- if (getMethod != null && hasJAXBAnnotations(getMethod)) {
+
+ String getMethodName = GET_STR + propertyName;
+
+ getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] { });
+ if (getMethod == null) {
+ // try is instead of get
+ getMethodName = IS_STR + propertyName;
+ getMethod = cls.getDeclaredMethod(getMethodName, new JavaClass[] { });
+ }
+
+ //may look for get method on parent class
+ if (getMethod == null) {
+ //look for inherited getMethod
+ getMethod = cls.getMethod(GET_STR + propertyName, new JavaClass[] { });
+ if (getMethod == null) {
+ getMethod = cls.getMethod(IS_STR + propertyName, new JavaClass[] { });
+ }
+ }
+ if (getMethod == null && !(hasJAXBAnnotations(setMethod))) {
+ isPropertyTransient = true;
+ }
+ if (getMethod != null && hasJAXBAnnotations(getMethod)) {
// use the set method if it exists and is annotated
boolean isTransient = helper.isAnnotationPresent(getMethod, XmlTransient.class);
boolean isLocation = helper.isAnnotationPresent(getMethod, XmlLocation.class) ||
@@ -3008,43 +3057,43 @@ public class AnnotationsProcessor {
ptype = (JavaClass) getMethod.getReturnType();
} else {
ptype = setMethod.getParameterTypes()[0];
- }
-
- if (!propertyNames.contains(propertyName)) {
- try {
- Property property = buildNewProperty(info, cls, propertyMethod, propertyName, ptype);
- propertyNames.add(propertyName);
- property.setTransient(isPropertyTransient);
-
- if (getMethod != null) {
- property.setOriginalGetMethodName(getMethod.getName());
- if (property.getGetMethodName() == null) {
- property.setGetMethodName(getMethod.getName());
- }
- }
- if (setMethod != null) {
- property.setOriginalSetMethodName(setMethod.getName());
- if (property.getSetMethodName() == null) {
- property.setSetMethodName(setMethod.getName());
- }
- }
- property.setMethodProperty(true);
-
- //boolean isTransient = helper.isAnnotationPresent(property.getElement(), XmlTransient.class);
- //boolean isLocation = helper.isAnnotationPresent(property.getElement(), XmlLocation.class) ||
- // helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
- // helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
- //if (!isTransient || (isTransient && isLocation)) {
- properties.add(property);
- //}
- } catch(JAXBException ex) {
- if(ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !isPropertyTransient) {
- throw ex;
- }
- }
- }
- }
-
+ }
+
+ if (!propertyNames.contains(propertyName)) {
+ try {
+ Property property = buildNewProperty(info, cls, propertyMethod, propertyName, ptype);
+ propertyNames.add(propertyName);
+ property.setTransient(isPropertyTransient);
+
+ if (getMethod != null) {
+ property.setOriginalGetMethodName(getMethod.getName());
+ if (property.getGetMethodName() == null) {
+ property.setGetMethodName(getMethod.getName());
+ }
+ }
+ if (setMethod != null) {
+ property.setOriginalSetMethodName(setMethod.getName());
+ if (property.getSetMethodName() == null) {
+ property.setSetMethodName(setMethod.getName());
+ }
+ }
+ property.setMethodProperty(true);
+
+ //boolean isTransient = helper.isAnnotationPresent(property.getElement(), XmlTransient.class);
+ //boolean isLocation = helper.isAnnotationPresent(property.getElement(), XmlLocation.class) ||
+ // helper.isAnnotationPresent(setMethod, CompilerHelper.XML_LOCATION_ANNOTATION_CLASS) ||
+ // helper.isAnnotationPresent(setMethod, CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_CLASS);
+ //if (!isTransient || (isTransient && isLocation)) {
+ properties.add(property);
+ //}
+ } catch (JAXBException ex) {
+ if (ex.getErrorCode() != JAXBException.INVALID_INTERFACE || !isPropertyTransient) {
+ throw ex;
+ }
+ }
+ }
+ }
+
properties = removeSuperclassProperties(cls, properties);
// default to alphabetical ordering
@@ -3059,13 +3108,13 @@ public class AnnotationsProcessor {
// Check for any get() methods that are overridden in the subclass.
// If we find any, remove the property, because it is already defined on
- // the superclass.
- JavaClass superClass = cls.getSuperclass();
- if (null != superClass) {
- TypeInfo superClassInfo = typeInfo.get(superClass.getQualifiedName());
- if (superClassInfo != null && !superClassInfo.isTransient()) {
- for (Property prop : properties) {
- for (Property superProp : superClassInfo.getProperties().values()) {
+ // the superclass.
+ JavaClass superClass = cls.getSuperclass();
+ if (null != superClass) {
+ TypeInfo superClassInfo = typeInfos.get(superClass.getQualifiedName());
+ if (superClassInfo != null && !superClassInfo.isTransient()) {
+ for (Property prop : properties) {
+ for (Property superProp : superClassInfo.getProperties().values()) {
if (superProp.getGetMethodName() != null && superProp.getGetMethodName().equals(prop.getGetMethodName()) && !superProp.isTransient()) {
revisedProperties.remove(prop);
}
@@ -3115,36 +3164,34 @@ public class AnnotationsProcessor {
return publicMethodProperties;
} else {
// add any non-duplicate method properties to the collection.
- // - in the case of a collision if one is annotated use it,
- // otherwise
- // use the field.
- HashMap<String, Property> fieldPropertyMap = getPropertyMapFromArrayList(publicFieldProperties);
- for (int i = 0; i < publicMethodProperties.size(); i++) {
- Property next = (Property) publicMethodProperties.get(i);
- Property fieldProp = fieldPropertyMap.get(next.getPropertyName());
- if ( fieldProp == null) {
- publicFieldProperties.add(next);
- } else if (fieldProp.isTransient()){
- //bug 346461 - if a public field is transient and the public methods are not
- // then use the method
- publicFieldProperties.remove(fieldProp);
- publicFieldProperties.add(next);
- }
- }
- return publicFieldProperties;
- }
- }
-
- public HashMap<String, Property> getPropertyMapFromArrayList(ArrayList<Property> props) {
- HashMap propMap = new HashMap(props.size());
-
- Iterator propIter = props.iterator();
- while (propIter.hasNext()) {
- Property next = (Property) propIter.next();
- propMap.put(next.getPropertyName(), next);
- }
- return propMap;
- }
+ // - in the case of a collision if one is annotated use it,
+ // otherwise
+ // use the field.
+ HashMap<String, Property> fieldPropertyMap = getPropertyMapFromArrayList(publicFieldProperties);
+ for (Property publicMethodProperty : publicMethodProperties) {
+ Property next = (Property) publicMethodProperty;
+ Property fieldProp = fieldPropertyMap.get(next.getPropertyName());
+ if (fieldProp == null) {
+ publicFieldProperties.add(next);
+ } else if (fieldProp.isTransient()) {
+ //bug 346461 - if a public field is transient and the public methods are not
+ // then use the method
+ publicFieldProperties.remove(fieldProp);
+ publicFieldProperties.add(next);
+ }
+ }
+ return publicFieldProperties;
+ }
+ }
+
+ public HashMap<String, Property> getPropertyMapFromArrayList(ArrayList<Property> props) {
+ HashMap propMap = new HashMap(props.size());
+
+ for (Object next : props) {
+ propMap.put(((Property)next).getPropertyName(), next);
+ }
+ return propMap;
+ }
public ArrayList getNoAccessTypePropertiesForClass(JavaClass cls, TypeInfo info) {
ArrayList<Property> list = new ArrayList<Property>();
@@ -3186,15 +3233,15 @@ public class AnnotationsProcessor {
return list;
}
- /**
- * Use name, namespace and type information to setup a user-defined schema
- * type. This method will typically be called when processing an
- *
- * @XmlSchemaType(s) annotation or xml-schema-type(s) metadata.
- *
- * @param name
- * @param namespace
- * @param jClassQualifiedName
+ /**
+ * Use name, namespace and type information to setup a user-defined schema
+ * type. This method will typically be called when processing an
+ *
+ * @XmlSchemaType(s) annotation or xml-schema-type(s) metadata.
+ *
+ * @param name
+ * @param namespace
+ * @param jClassQualifiedName
*/
public void processSchemaType(String name, String namespace, String jClassQualifiedName) {
this.userDefinedSchemaTypes.put(jClassQualifiedName, new QName(namespace, name));
@@ -3217,62 +3264,61 @@ public class AnnotationsProcessor {
Class restrictionClass = String.class;
QName restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass));
- if (helper.isAnnotationPresent(javaClass, XmlEnum.class)) {
- XmlEnum xmlEnum = (XmlEnum) helper.getAnnotation(javaClass, XmlEnum.class);
- restrictionClass = xmlEnum.value();
- JavaClass restrictionJavaClass= helper.getJavaClass(restrictionClass);
- boolean restrictionIsEnum = helper.isAnnotationPresent(restrictionJavaClass, XmlEnum.class);
-
- if(!restrictionIsEnum){
- if(helper.isBuiltInJavaType(restrictionJavaClass)){
- restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass));
- }else{
- TypeInfo restrictionInfo = typeInfo.get(restrictionJavaClass.getQualifiedName());
- if(restrictionInfo == null){
- JavaClass[] jClasses = new JavaClass[] { restrictionJavaClass };
- buildNewTypeInfo(jClasses);
- restrictionInfo = typeInfo.get(restrictionJavaClass.getQualifiedName());
- }else if(restrictionInfo != null && !restrictionInfo.isPostBuilt()){
- postBuildTypeInfo(new JavaClass[] { restrictionJavaClass });
- }
-
- Property xmlValueProp =restrictionInfo.getXmlValueProperty();
- if(xmlValueProp != null){
- restrictionJavaClass = xmlValueProp.getActualType();
- restrictionBase = getSchemaTypeFor(restrictionJavaClass);
- restrictionClass = helper.getClassForJavaClass(restrictionJavaClass);
- }
- }
- }else{
- while (restrictionIsEnum) {
-
- TypeInfo restrictionTypeInfo = processReferencedClass(restrictionJavaClass);
- restrictionBase = new QName(restrictionTypeInfo.getClassNamespace(), restrictionTypeInfo.getSchemaTypeName());
-
- xmlEnum = (XmlEnum) helper.getAnnotation(restrictionJavaClass, XmlEnum.class);
- restrictionClass = xmlEnum.value();
- restrictionJavaClass= helper.getJavaClass(restrictionClass);
- restrictionIsEnum = helper.isAnnotationPresent(restrictionJavaClass, XmlEnum.class);
- }
- }
- }
- info.setRestrictionBase(restrictionBase);
-
- for (Iterator<JavaField> fieldIt = javaClass.getDeclaredFields().iterator(); fieldIt.hasNext();) {
- JavaField field = fieldIt.next();
- if (field.isEnumConstant()) {
- Object enumValue = field.getName();
- if (helper.isAnnotationPresent(field, XmlEnumValue.class)) {
- enumValue = ((XmlEnumValue) helper.getAnnotation(field, XmlEnumValue.class)).value();
- }
- if(restrictionClass != null){
- try{
- enumValue = XMLConversionManager.getDefaultXMLManager().convertObject(enumValue, restrictionClass);
- }catch(ConversionException e){
- throw org.eclipse.persistence.exceptions.JAXBException.invalidEnumValue(enumValue, restrictionClass.getName(), e);
- }
-
- }
+ if (helper.isAnnotationPresent(javaClass, XmlEnum.class)) {
+ XmlEnum xmlEnum = (XmlEnum) helper.getAnnotation(javaClass, XmlEnum.class);
+ restrictionClass = xmlEnum.value();
+ JavaClass restrictionJavaClass= helper.getJavaClass(restrictionClass);
+ boolean restrictionIsEnum = helper.isAnnotationPresent(restrictionJavaClass, XmlEnum.class);
+
+ if(!restrictionIsEnum){
+ if(helper.isBuiltInJavaType(restrictionJavaClass)){
+ restrictionBase = getSchemaTypeFor(helper.getJavaClass(restrictionClass));
+ }else{
+ TypeInfo restrictionInfo = typeInfos.get(restrictionJavaClass.getQualifiedName());
+ if(restrictionInfo == null){
+ JavaClass[] jClasses = new JavaClass[] { restrictionJavaClass };
+ buildNewTypeInfo(jClasses);
+ restrictionInfo = typeInfos.get(restrictionJavaClass.getQualifiedName());
+ }else if(!restrictionInfo.isPostBuilt()){
+ postBuildTypeInfo(new JavaClass[] { restrictionJavaClass });
+ }
+
+ Property xmlValueProp = restrictionInfo.getXmlValueProperty();
+ if(xmlValueProp != null){
+ restrictionJavaClass = xmlValueProp.getActualType();
+ restrictionBase = getSchemaTypeFor(restrictionJavaClass);
+ restrictionClass = helper.getClassForJavaClass(restrictionJavaClass);
+ }
+ }
+ }else{
+ while (restrictionIsEnum) {
+
+ TypeInfo restrictionTypeInfo = processReferencedClass(restrictionJavaClass);
+ restrictionBase = new QName(restrictionTypeInfo.getClassNamespace(), restrictionTypeInfo.getSchemaTypeName());
+
+ xmlEnum = (XmlEnum) helper.getAnnotation(restrictionJavaClass, XmlEnum.class);
+ restrictionClass = xmlEnum.value();
+ restrictionJavaClass= helper.getJavaClass(restrictionClass);
+ restrictionIsEnum = helper.isAnnotationPresent(restrictionJavaClass, XmlEnum.class);
+ }
+ }
+ }
+ info.setRestrictionBase(restrictionBase);
+
+ for (JavaField field : (Iterable<JavaField>) javaClass.getDeclaredFields()) {
+ if (field.isEnumConstant()) {
+ Object enumValue = field.getName();
+ if (helper.isAnnotationPresent(field, XmlEnumValue.class)) {
+ enumValue = ((XmlEnumValue) helper.getAnnotation(field, XmlEnumValue.class)).value();
+ }
+ if (restrictionClass != null) {
+ try {
+ enumValue = XMLConversionManager.getDefaultXMLManager().convertObject(enumValue, restrictionClass);
+ } catch (ConversionException e) {
+ throw JAXBException.invalidEnumValue(enumValue, restrictionClass.getName(), e);
+ }
+
+ }
info.addJavaFieldToXmlEnumValuePair(field.getName(), enumValue);
}
}
@@ -3288,13 +3334,13 @@ public class AnnotationsProcessor {
public QName getSchemaTypeOrNullFor(JavaClass javaClass) {
if (javaClass == null) {
return null;
- }
-
- // check user defined types first
- QName schemaType = (QName) userDefinedSchemaTypes.get(javaClass.getQualifiedName());
- if (schemaType == null) {
- schemaType = (QName) helper.getXMLToJavaTypeMap().get(javaClass.getRawName());
- }
+ }
+
+ // check user defined types first
+ QName schemaType = userDefinedSchemaTypes.get(javaClass.getQualifiedName());
+ if (schemaType == null) {
+ schemaType = (QName) helper.getXMLToJavaTypeMap().get(javaClass.getRawName());
+ }
return schemaType;
}
@@ -3316,14 +3362,13 @@ public class AnnotationsProcessor {
packageNamespace = namespaceMapping;
} else if (namespaceMapping.equals(XMLProcessor.DEFAULT)) {
packageNamespace = this.defaultTargetNamespace;
- }
- info.setNamespace(packageNamespace);
- XmlNs[] xmlns = xmlSchema.xmlns();
- for (int i = 0; i < xmlns.length; i++) {
- XmlNs next = xmlns[i];
- info.getNamespaceResolver().put(next.prefix(), next.namespaceURI());
- }
- info.setAttributeFormQualified(xmlSchema.attributeFormDefault() == XmlNsForm.QUALIFIED);
+ }
+ info.setNamespace(packageNamespace);
+ XmlNs[] xmlns = xmlSchema.xmlns();
+ for (XmlNs next : xmlns) {
+ info.getNamespaceResolver().put(next.prefix(), next.namespaceURI());
+ }
+ info.setAttributeFormQualified(xmlSchema.attributeFormDefault() == XmlNsForm.QUALIFIED);
info.setElementFormQualified(xmlSchema.elementFormDefault() == XmlNsForm.QUALIFIED);
// reflectively load XmlSchema class to avoid dependency
@@ -3336,46 +3381,47 @@ public class AnnotationsProcessor {
location = null;
} else if (location.equals(EMPTY_STRING)) {
location = null;
- }
- }
- info.setLocation(location);
- } catch (Exception ex) {
- }
-
- } else {
- info.setNamespace(defaultTargetNamespace);
- }
- if (!info.isElementFormQualified() ){
- isDefaultNamespaceAllowed = false;
- }
- return info;
- }
-
- public HashMap<String, TypeInfo> getTypeInfo() {
- return typeInfo;
- }
-
- public ArrayList<JavaClass> getTypeInfoClasses() {
- return typeInfoClasses;
- }
-
- public HashMap<String, QName> getUserDefinedSchemaTypes() {
- return userDefinedSchemaTypes;
- }
-
+ }
+ }
+ info.setLocation(location);
+ } catch (Exception ignored) {
+ // ignored
+ }
+
+ } else {
+ info.setNamespace(defaultTargetNamespace);
+ }
+ if (!info.isElementFormQualified() ){
+ isDefaultNamespaceAllowed = false;
+ }
+ return info;
+ }
+
+ public Map<String, TypeInfo> getTypeInfos() {
+ return typeInfos;
+ }
+
+ public List<JavaClass> getTypeInfoClasses() {
+ return typeInfoClasses;
+ }
+
+ public Map<String, QName> getUserDefinedSchemaTypes() {
+ return userDefinedSchemaTypes;
+ }
+
public QName getQNameForProperty(Property property, String defaultName, JavaHasAnnotations element, NamespaceInfo namespaceInfo, TypeInfo info) {
String uri = info.getClassNamespace();
- String name = XMLProcessor.DEFAULT;
- String namespace = XMLProcessor.DEFAULT;
- QName qName = null;
-
- if(property.isMap()){
- isDefaultNamespaceAllowed = false;
- }
-
- if (helper.isAnnotationPresent(element, XmlAttribute.class)) {
- XmlAttribute xmlAttribute = (XmlAttribute) helper.getAnnotation(element, XmlAttribute.class);
- name = xmlAttribute.name();
+ String name = XMLProcessor.DEFAULT;
+ String namespace = XMLProcessor.DEFAULT;
+ QName qName = null;
+
+ if(property.isMap()){
+ isDefaultNamespaceAllowed = false;
+ }
+
+ if (helper.isAnnotationPresent(element, XmlAttribute.class)) {
+ XmlAttribute xmlAttribute = (XmlAttribute) helper.getAnnotation(element, XmlAttribute.class);
+ name = xmlAttribute.name();
namespace = xmlAttribute.namespace();
if (name.equals(XMLProcessor.DEFAULT)) {
@@ -3390,25 +3436,25 @@ public class AnnotationsProcessor {
if (!namespace.equals(XMLProcessor.DEFAULT)) {
qName = new QName(namespace, name);
isDefaultNamespaceAllowed = false;
- } else {
- if (namespaceInfo.isAttributeFormQualified()) {
- qName = new QName(uri, name);
- isDefaultNamespaceAllowed = false;
- } else {
- qName = new QName(name);
- }
+ } else {
+ if (namespaceInfo.isAttributeFormQualified()) {
+ qName = new QName(uri, name);
+ isDefaultNamespaceAllowed = false;
+ } else {
+ qName = new QName(name);
+ }
}
} else {
if (helper.isAnnotationPresent(element, XmlElement.class)) {
XmlElement xmlElement = (XmlElement) helper.getAnnotation(element, XmlElement.class);
name = xmlElement.name();
- namespace = xmlElement.namespace();
- }
- if (property.isMap() && helper.isAnnotationPresent(element, XmlElementWrapper.class)) {
- XmlElementWrapper xmlElementWrapper = (XmlElementWrapper) helper.getAnnotation(element, XmlElementWrapper.class);
- name = xmlElementWrapper.name();
- namespace = xmlElementWrapper.namespace();
- }
+ namespace = xmlElement.namespace();
+ }
+ if (property.isMap() && helper.isAnnotationPresent(element, XmlElementWrapper.class)) {
+ XmlElementWrapper xmlElementWrapper = (XmlElementWrapper) helper.getAnnotation(element, XmlElementWrapper.class);
+ name = xmlElementWrapper.name();
+ namespace = xmlElementWrapper.namespace();
+ }
if (name.equals(XMLProcessor.DEFAULT)) {
name = defaultName;
@@ -3433,20 +3479,20 @@ public class AnnotationsProcessor {
}
}
}
- return qName;
- }
-
- public HashMap<String, PackageInfo> getPackageToPackageInfoMappings() {
- return packageToPackageInfoMappings;
- }
-
- /**
- * Add a package name/NamespaceInfo entry to the map. This method will
- * lazy-load the map if necessary.
- *
- * @return
- */
- public void addPackageToNamespaceMapping(String packageName, NamespaceInfo nsInfo) {
+ return qName;
+ }
+
+ public Map<String, PackageInfo> getPackageToPackageInfoMappings() {
+ return packageToPackageInfoMappings;
+ }
+
+ /**
+ * Add a package name/NamespaceInfo entry to the map. This method will
+ * lazy-load the map if necessary.
+ *
+ * @return
+ */
+ public void addPackageToNamespaceMapping(String packageName, NamespaceInfo nsInfo) {
if (packageToPackageInfoMappings == null) {
packageToPackageInfoMappings = new HashMap<String, PackageInfo>();
}
@@ -3461,13 +3507,13 @@ public class AnnotationsProcessor {
public void addPackageToPackageInfoMapping(String packageName, PackageInfo packageInfo) {
if(packageToPackageInfoMappings == null) {
packageToPackageInfoMappings = new HashMap<String, PackageInfo>();
- }
- packageToPackageInfoMappings.put(packageName, packageInfo);
- }
-
- public PackageInfo getPackageInfoForPackage(JavaClass javaClass) {
- String packageName = javaClass.getPackageName();
- PackageInfo packageInfo = packageToPackageInfoMappings.get(packageName);
+ }
+ packageToPackageInfoMappings.put(packageName, packageInfo);
+ }
+
+ public PackageInfo getPackageInfoForPackage(JavaClass javaClass) {
+ String packageName = javaClass.getPackageName();
+ PackageInfo packageInfo = packageToPackageInfoMappings.get(packageName);
if (packageInfo == null) {
packageInfo = getPackageInfoForPackage(javaClass.getPackage(), packageName);
}
@@ -3477,13 +3523,13 @@ public class AnnotationsProcessor {
public PackageInfo getPackageInfoForPackage(JavaPackage pack, String packageName) {
PackageInfo packageInfo = packageToPackageInfoMappings.get(packageName);
if (packageInfo == null) {
- XmlSchema xmlSchema = (XmlSchema) helper.getAnnotation(pack, XmlSchema.class);
- packageInfo = new PackageInfo();
- NamespaceInfo namespaceInfo = processNamespaceInformation(xmlSchema);
-
- packageInfo.setNamespaceInfo(namespaceInfo);
-
- // if it's still null, generate based on package name
+ XmlSchema xmlSchema = (XmlSchema) helper.getAnnotation(pack, XmlSchema.class);
+ packageInfo = new PackageInfo();
+ NamespaceInfo namespaceInfo = processNamespaceInformation(xmlSchema);
+
+ packageInfo.setNamespaceInfo(namespaceInfo);
+
+ // if it's still null, generate based on package name
if (namespaceInfo.getNamespace() == null) {
namespaceInfo.setNamespace(EMPTY_STRING);
}
@@ -3496,13 +3542,13 @@ public class AnnotationsProcessor {
packageInfo.setAccessOrder(XmlAccessOrder.fromValue(xmlAccessorOrder.value().name()));
}
if (CompilerHelper.ACCESSOR_FACTORY_ANNOTATION_CLASS != null && helper.isAnnotationPresent(pack, CompilerHelper.ACCESSOR_FACTORY_ANNOTATION_CLASS)) {
- Annotation xmlAccessorFactory = helper.getAnnotation(pack, CompilerHelper.ACCESSOR_FACTORY_ANNOTATION_CLASS);
- Class xmlAccessorFactoryClass = null;
- try {
- xmlAccessorFactoryClass = (Class)PrivilegedAccessHelper.invokeMethod(CompilerHelper.ACCESSOR_FACTORY_VALUE_METHOD, xmlAccessorFactory, new Object[]{});
- packageInfo.setAccessorFactory(new AccessorFactoryWrapper(PrivilegedAccessHelper.newInstanceFromClass(xmlAccessorFactoryClass)));
- } catch (Exception ex) {
- throw JAXBException.errorInstantiatingAccessorFactory(xmlAccessorFactoryClass, ex);
+ Annotation xmlAccessorFactory = helper.getAnnotation(pack, CompilerHelper.ACCESSOR_FACTORY_ANNOTATION_CLASS);
+ Class xmlAccessorFactoryClass = null;
+ try {
+ xmlAccessorFactoryClass = (Class)PrivilegedAccessHelper.invokeMethod(CompilerHelper.ACCESSOR_FACTORY_VALUE_METHOD, xmlAccessorFactory, new Object[]{});
+ packageInfo.setAccessorFactory(new AccessorFactoryWrapper(PrivilegedAccessHelper.newInstanceFromClass(xmlAccessorFactoryClass)));
+ } catch (Exception ex) {
+ throw JAXBException.errorInstantiatingAccessorFactory(xmlAccessorFactoryClass, ex);
}
}else if (CompilerHelper.INTERNAL_ACCESSOR_FACTORY_ANNOTATION_CLASS != null && helper.isAnnotationPresent(pack, CompilerHelper.INTERNAL_ACCESSOR_FACTORY_ANNOTATION_CLASS)) {
Annotation xmlAccessorFactory = helper.getAnnotation(pack, CompilerHelper.INTERNAL_ACCESSOR_FACTORY_ANNOTATION_CLASS);
@@ -3510,13 +3556,13 @@ public class AnnotationsProcessor {
try {
xmlAccessorFactoryClass = (Class)PrivilegedAccessHelper.invokeMethod(CompilerHelper.INTERNAL_ACCESSOR_FACTORY_VALUE_METHOD, xmlAccessorFactory, new Object[]{});
packageInfo.setAccessorFactory(new AccessorFactoryWrapper(PrivilegedAccessHelper.newInstanceFromClass(xmlAccessorFactoryClass)));
- } catch (Exception ex) {
- throw JAXBException.errorInstantiatingAccessorFactory(xmlAccessorFactoryClass, ex);
- }
- }
- packageToPackageInfoMappings.put(packageName, packageInfo);
- }
- return packageInfo;
+ } catch (Exception ex) {
+ throw JAXBException.errorInstantiatingAccessorFactory(xmlAccessorFactoryClass, ex);
+ }
+ }
+ packageToPackageInfoMappings.put(packageName, packageInfo);
+ }
+ return packageInfo;
}
public NamespaceInfo findInfoForNamespace(String namespace) {
@@ -3525,21 +3571,21 @@ public class AnnotationsProcessor {
if(nextUri == null) {
nextUri = Constants.EMPTY_STRING;
}
- if(namespace == null) {
- namespace = Constants.EMPTY_STRING;
- }
-
- if(nextUri.equals(namespace)) {
- return next.getNamespaceInfo();
- }
- }
- return null;
- }
-
- private void checkForCallbackMethods() {
- JavaClass unmarshallerCls = helper.getJavaClass(Unmarshaller.class);
- JavaClass marshallerCls = helper.getJavaClass(Marshaller.class);
- JavaClass objectCls = helper.getJavaClass(Object.class);
+ if(namespace == null) {
+ namespace = Constants.EMPTY_STRING;
+ }
+
+ if(nextUri.equals(namespace)) {
+ return next.getNamespaceInfo();
+ }
+ }
+ return null;
+ }
+
+ void checkForCallbackMethods() {
+ JavaClass unmarshallerCls = helper.getJavaClass(Unmarshaller.class);
+ JavaClass marshallerCls = helper.getJavaClass(Marshaller.class);
+ JavaClass objectCls = helper.getJavaClass(Object.class);
JavaClass[] unmarshalParams = new JavaClass[] { unmarshallerCls, objectCls };
JavaClass[] marshalParams = new JavaClass[] { marshallerCls };
@@ -3594,51 +3640,51 @@ public class AnnotationsProcessor {
}
marshalCallbacks.put(next.getQualifiedName(), marshalCallback);
}
- }
- }
-
- public HashMap<String, MarshalCallback> getMarshalCallbacks() {
- return this.marshalCallbacks;
- }
-
- public HashMap<String, UnmarshalCallback> getUnmarshalCallbacks() {
- return this.unmarshalCallbacks;
- }
-
- private void findAndProcessObjectFactory(JavaClass cls){
- //need to make sure objectfactory gets processed.
- try{
- String className =cls.getPackageName() + ".ObjectFactory";
- findAndProcessObjectFactory(className);
- }catch(JAXBException e){}
- }
-
- void findAndProcessObjectFactory(String objectFactoryClassName){
- //need to make sure objectfactory gets processed.
- try{
- if(objectFactoryClassNames.contains(objectFactoryClassName)){
- return;
- }
- JavaClass javaClass = helper.getJavaClass(objectFactoryClassName);
- if (isXmlRegistry(javaClass)) {
- JavaClass[] processed = this.processObjectFactory(javaClass, new ArrayList());
- preBuildTypeInfo(processed);
- buildTypeInfo(processed);
- updateGlobalElements(processed);
- }
- }catch(JAXBException e){}
- }
-
- public JavaClass[] processObjectFactory(JavaClass objectFactoryClass, ArrayList<JavaClass> classes) {
-
- String className = objectFactoryClass.getName();
- if(objectFactoryClassNames.contains(className)){
- return new JavaClass[0];
- }
- objectFactoryClassNames.add(className);
- // if there is an xml-registry from XML for this JavaClass, create a map
- // of method names to XmlElementDecl objects to simplify processing
- // later on in this method
+ }
+ }
+
+ public Map<String, MarshalCallback> getMarshalCallbacks() {
+ return this.marshalCallbacks;
+ }
+
+ public Map<String, UnmarshalCallback> getUnmarshalCallbacks() {
+ return this.unmarshalCallbacks;
+ }
+
+ private void findAndProcessObjectFactory(JavaClass cls){
+ //need to make sure objectfactory gets processed.
+ try {
+ String className =cls.getPackageName() + ".ObjectFactory";
+ findAndProcessObjectFactory(className);
+ } catch (JAXBException ignored) { /* ignored */}
+ }
+
+ void findAndProcessObjectFactory(String objectFactoryClassName){
+ //need to make sure objectfactory gets processed.
+ try {
+ if(objectFactoryClassNames.contains(objectFactoryClassName)){
+ return;
+ }
+ JavaClass javaClass = helper.getJavaClass(objectFactoryClassName);
+ if (isXmlRegistry(javaClass)) {
+ JavaClass[] processed = this.processObjectFactory(javaClass, new ArrayList<JavaClass>());
+ preBuildTypeInfo(processed);
+ buildTypeInfo(processed);
+ updateGlobalElements(processed);
+ }
+ } catch (JAXBException ignored){ /* ignored */ }
+ }
+
+ public JavaClass[] processObjectFactory(JavaClass objectFactoryClass, List<JavaClass> classes) {
+
+ String className = objectFactoryClass.getName();
+ if(objectFactoryClassNames.contains(className)){
+ return new JavaClass[0];
+ }
+ objectFactoryClassNames.add(className);
+ // if there is an xml-registry from XML for this JavaClass, create a map
+ // of method names to XmlElementDecl objects to simplify processing
+ // later on in this method
Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls = new HashMap<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl>();
org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg = xmlRegistries.get(objectFactoryClass.getQualifiedName());
if (xmlReg != null) {
@@ -3654,45 +3700,45 @@ public class AnnotationsProcessor {
PackageInfo packageInfo = getPackageInfoForPackage(objectFactoryClass);
while (methodsIter.hasNext()) {
JavaMethod next = (JavaMethod) methodsIter.next();
- if (next.getName().startsWith(CREATE)) {
- JavaClass type = next.getReturnType();
- if (JAVAX_XML_BIND_JAXBELEMENT.equals(type.getName())) {
- Object[] actualTypeArguments = type.getActualTypeArguments().toArray();
- if (actualTypeArguments.length == 0) {
- type = helper.OBJECT_CLASS;
- } else {
- type = (JavaClass) actualTypeArguments[0];
- }
- type = processXmlElementDecl(type, next, packageInfo, elemDecls);
- }else if (helper.JAXBELEMENT_CLASS.isAssignableFrom(type)) {
- this.factoryMethods.put(type.getRawName(), next);
- type = processXmlElementDecl(type, next, packageInfo, elemDecls);
- } else {
- this.factoryMethods.put(type.getRawName(), next);
- }
- if (!helper.isBuiltInJavaType(type) && !helper.classExistsInArray(type, classes)) {
- classes.add(type);
+ if (next.getName().startsWith(CREATE)) {
+ JavaClass type = next.getReturnType();
+ if (JAVAX_XML_BIND_JAXBELEMENT.equals(type.getName())) {
+ Object[] actualTypeArguments = type.getActualTypeArguments().toArray();
+ if (actualTypeArguments.length == 0) {
+ type = helper.OBJECT_CLASS;
+ } else {
+ type = (JavaClass) actualTypeArguments[0];
+ }
+ type = processXmlElementDecl(type, next, packageInfo, elemDecls);
+ }else if (helper.JAXBELEMENT_CLASS.isAssignableFrom(type)) {
+ this.factoryMethods.put(type.getRawName(), next);
+ type = processXmlElementDecl(type, next, packageInfo, elemDecls);
+ } else {
+ this.factoryMethods.put(type.getRawName(), next);
+ }
+ if (!helper.isBuiltInJavaType(type) && !helper.classExistsInArray(type, classes)) {
+ classes.add(type);
}
}
- }
-
- if (classes.size() > 0) {
- classesToProcessPropertyTypes.addAll(classes);
- return classes.toArray(new JavaClass[classes.size()]);
- } else {
- return new JavaClass[0];
- }
- }
-
- private JavaClass processXmlElementDecl(JavaClass type, JavaMethod next, PackageInfo packageInfo, Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls){
- JavaClass returnType = type;
- // if there's an XmlElementDecl for this method from XML, use it
- // - otherwise look for an annotation
- org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlEltDecl = elemDecls.get(next.getName());
- if (( xmlEltDecl != null) || helper.isAnnotationPresent(next, XmlElementDecl.class)) {
- QName qname;
- QName substitutionHead = null;
- String url;
+ }
+
+ if (classes.size() > 0) {
+ classesToProcessPropertyTypes.addAll(classes);
+ return classes.toArray(new JavaClass[classes.size()]);
+ } else {
+ return new JavaClass[0];
+ }
+ }
+
+ private JavaClass processXmlElementDecl(JavaClass type, JavaMethod next, PackageInfo packageInfo, Map<String, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl> elemDecls){
+ JavaClass returnType = type;
+ // if there's an XmlElementDecl for this method from XML, use it
+ // - otherwise look for an annotation
+ org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry.XmlElementDecl xmlEltDecl = elemDecls.get(next.getName());
+ if (( xmlEltDecl != null) || helper.isAnnotationPresent(next, XmlElementDecl.class)) {
+ QName qname;
+ QName substitutionHead = null;
+ String url;
String localName;
String defaultValue = null;
Class scopeClass = javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class;
@@ -3738,13 +3784,13 @@ public class AnnotationsProcessor {
substitutionHead = new QName(subHeadNamespace, subHeadLocal);
}
if (!(elementDecl.defaultValue().length() == 1 && elementDecl.defaultValue().startsWith(ELEMENT_DECL_DEFAULT))) {
- defaultValue = elementDecl.defaultValue();
- }
- }
-
- if (XMLProcessor.DEFAULT.equals(url)) {
- url = packageInfo.getNamespace();
- }
+ defaultValue = elementDecl.defaultValue();
+ }
+ }
+
+ if (XMLProcessor.DEFAULT.equals(url)) {
+ url = packageInfo.getNamespace();
+ }
if(Constants.EMPTY_STRING.equals(url)) {
isDefaultNamespaceAllowed = false;
qname = new QName(localName);
@@ -3772,57 +3818,57 @@ public class AnnotationsProcessor {
if (helper.isAnnotationPresent(next, XmlJavaTypeAdapter.class)) {
XmlJavaTypeAdapter typeAdapter = (XmlJavaTypeAdapter) helper.getAnnotation(next, XmlJavaTypeAdapter.class);
Class typeAdapterClass = typeAdapter.value();
- declaration.setJavaTypeAdapterClass(typeAdapterClass);
-
- Class declJavaType = CompilerHelper.getTypeFromAdapterClass(typeAdapterClass);
- JavaClass adaptedType = helper.getJavaClass(declJavaType);
- declaration.setJavaType(adaptedType);
- declaration.setAdaptedJavaType(type);
- returnType = adaptedType;
+ declaration.setJavaTypeAdapterClass(typeAdapterClass);
+
+ Class declJavaType = CompilerHelper.getTypeFromAdapterClass(typeAdapterClass);
+ JavaClass adaptedType = helper.getJavaClass(declJavaType);
+ declaration.setJavaType(adaptedType);
+ declaration.setAdaptedJavaType(type);
+ returnType = adaptedType;
}
if (helper.isAnnotationPresent(next, XmlMimeType.class)) {
XmlMimeType mimeType = (XmlMimeType)helper.getAnnotation(next, XmlMimeType.class);
declaration.setXmlMimeType(mimeType.value());
}
- if (helper.isAnnotationPresent(next, XmlAttachmentRef.class)) {
- declaration.setXmlAttachmentRef(true);
- }
- HashMap<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
- if (elements == null) {
- elements = new HashMap<QName, ElementDeclaration>();
- this.elementDeclarations.put(scopeClass.getName(), elements);
- }
- if(elements.containsKey(qname)){
- throw JAXBException.duplicateElementName(qname);
- }
-
- elements.put(qname, declaration);
- }
- return returnType;
- }
-
- /**
- * Lazy load and return the map of global elements.
- *
- * @return
- */
- public HashMap<QName, ElementDeclaration> getGlobalElements() {
- return this.elementDeclarations.get(XmlElementDecl.GLOBAL.class.getName());
- }
-
+ if (helper.isAnnotationPresent(next, XmlAttachmentRef.class)) {
+ declaration.setXmlAttachmentRef(true);
+ }
+ Map<QName, ElementDeclaration> elements = getElementDeclarationsForScope(scopeClass.getName());
+ if (elements == null) {
+ elements = new HashMap<QName, ElementDeclaration>();
+ this.elementDeclarations.put(scopeClass.getName(), elements);
+ }
+ if(elements.containsKey(qname)){
+ throw JAXBException.duplicateElementName(qname);
+ }
+
+ elements.put(qname, declaration);
+ }
+ return returnType;
+ }
+
+ /**
+ * Lazy load and return the map of global elements.
+ *
+ * @return
+ */
+ public Map<QName, ElementDeclaration> getGlobalElements() {
+ return this.elementDeclarations.get(XmlElementDecl.GLOBAL.class.getName());
+ }
+
public void updateGlobalElements(JavaClass[] classesToProcess) {
// Once all the global element declarations have been created, make sure
// that any ones that have
// a substitution head set are added to the list of substitutable
// elements on the declaration for that
// head.
-
- // Look for XmlRootElement declarations
- for (JavaClass javaClass : classesToProcess) {
- TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
- if (info == null) {
- continue;
- }
+
+ // Look for XmlRootElement declarations
+ for (JavaClass javaClass : classesToProcess) {
+ TypeInfo info = typeInfos.get(javaClass.getQualifiedName());
+ if (info == null) {
+ continue;
+ }
if (!info.isTransient() && info.isSetXmlRootElement()) {
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement();
NamespaceInfo namespaceInfo;
@@ -3860,15 +3906,13 @@ public class AnnotationsProcessor {
declaration.setIsXmlRootElement(true);
addGlobalElement(rootElemName, declaration);
this.xmlRootElements.put(javaClass.getQualifiedName(), declaration);
- }
- }
-
- Iterator<QName> elementQnames = this.getGlobalElements().keySet().iterator();
- while (elementQnames.hasNext()) {
- QName next = elementQnames.next();
- ElementDeclaration nextDeclaration = this.getGlobalElements().get(next);
- QName substitutionHead = nextDeclaration.getSubstitutionHead();
- while (substitutionHead != null) {
+ }
+ }
+
+ for (QName next : this.getGlobalElements().keySet()) {
+ ElementDeclaration nextDeclaration = this.getGlobalElements().get(next);
+ QName substitutionHead = nextDeclaration.getSubstitutionHead();
+ while (substitutionHead != null) {
ElementDeclaration rootDeclaration = this.getGlobalElements().get(substitutionHead);
rootDeclaration.addSubstitutableElement(nextDeclaration);
if (rootDeclaration.getSubstitutionHead() != null && rootDeclaration.getSubstitutionHead().equals(substitutionHead)) {
@@ -3898,19 +3942,18 @@ public class AnnotationsProcessor {
* annotations.
*/
private boolean hasJAXBAnnotations(JavaHasAnnotations elem) {
- if(elem == null){
- return false;
- }
- Collection annotations = elem.getAnnotations();
- if (annotations == null || annotations.size() == 0) {
- return false;
- }
- Iterator annotationsIter = annotations.iterator();
- while (annotationsIter.hasNext()) {
- String nextName = ((JavaAnnotation) annotationsIter.next()).getName();
- if (nextName.startsWith(JAVAX_XML_BIND_ANNOTATION)
- || nextName.startsWith(OXM_ANNOTATIONS)
- || nextName.equals(CompilerHelper.XML_LOCATION_ANNOTATION_NAME)
+ if(elem == null){
+ return false;
+ }
+ List annotations = (List<JavaAnnotation>) elem.getAnnotations();
+ if (annotations == null || annotations.isEmpty()) {
+ return false;
+ }
+ for (Object annotation : annotations) {
+ String nextName = ((JavaAnnotation) annotation).getName();
+ if (nextName.startsWith(JAVAX_XML_BIND_ANNOTATION)
+ || nextName.startsWith(OXM_ANNOTATIONS)
+ || nextName.equals(CompilerHelper.XML_LOCATION_ANNOTATION_NAME)
|| nextName.equals(CompilerHelper.INTERNAL_XML_LOCATION_ANNOTATION_NAME)) {
return true;
}
@@ -3941,13 +3984,13 @@ public class AnnotationsProcessor {
private void validateXmlValueFieldOrProperty(JavaClass cls, Property property) {
JavaClass ptype = property.getActualType();
- String propName = property.getPropertyName();
- JavaClass parent = cls.getSuperclass();
- while (parent != null && !(parent.getQualifiedName().equals(JAVA_LANG_OBJECT))) {
- TypeInfo parentTypeInfo = typeInfo.get(parent.getQualifiedName());
- if(hasElementMappedProperties(parentTypeInfo)) {
- throw JAXBException.propertyOrFieldCannotBeXmlValue(propName);
- }
+ String propName = property.getPropertyName();
+ JavaClass parent = cls.getSuperclass();
+ while (parent != null && !(parent.getQualifiedName().equals(JAVA_LANG_OBJECT))) {
+ TypeInfo parentTypeInfo = typeInfos.get(parent.getQualifiedName());
+ if(hasElementMappedProperties(parentTypeInfo)) {
+ throw JAXBException.propertyOrFieldCannotBeXmlValue(propName);
+ }
parent = parent.getSuperclass();
}
@@ -3969,26 +4012,26 @@ public class AnnotationsProcessor {
return false;
}
- private void validateXmlAttributeFieldOrProperty(TypeInfo tInfo, Property property) {
- // Check that @XmlAttribute references a Java type that maps to text in XML
- JavaClass ptype = property.getActualType();
- TypeInfo refInfo = typeInfo.get(ptype.getQualifiedName());
- if (refInfo != null) {
- if (!refInfo.isPostBuilt()) {
- postBuildTypeInfo(new JavaClass[] { ptype });
+ private void validateXmlAttributeFieldOrProperty(TypeInfo tInfo, Property property) {
+ // Check that @XmlAttribute references a Java type that maps to text in XML
+ JavaClass ptype = property.getActualType();
+ TypeInfo refInfo = typeInfos.get(ptype.getQualifiedName());
+ if (refInfo != null) {
+ if (!refInfo.isPostBuilt()) {
+ postBuildTypeInfo(new JavaClass[] { ptype });
}
if (!refInfo.isEnumerationType()) {
JavaClass parent = ptype.getSuperclass();
boolean hasMapped = false;
while (parent != null) {
hasMapped = hasTextMapping(refInfo);
- if (hasMapped || parent.getQualifiedName().equals(JAVA_LANG_OBJECT)) {
- break;
- }
- refInfo = typeInfo.get(parent.getQualifiedName());
- parent = parent.getSuperclass();
- }
- if (!hasMapped) {
+ if (hasMapped || parent.getQualifiedName().equals(JAVA_LANG_OBJECT)) {
+ break;
+ }
+ refInfo = typeInfos.get(parent.getQualifiedName());
+ parent = parent.getSuperclass();
+ }
+ if (!hasMapped) {
String propName = property.getPropertyName();
String typeName = tInfo.getJavaClassName();
String refTypeName = refInfo.getJavaClassName();
@@ -4000,29 +4043,29 @@ public class AnnotationsProcessor {
private boolean hasTextMapping(TypeInfo tInfo) {
Collection<Property> props = tInfo.getProperties().values();
- for (Property property : props) {
- if (property.isAttribute()) {
- JavaClass ptype = property.getActualType();
- TypeInfo refInfo = typeInfo.get(ptype.getQualifiedName());
- if (refInfo != null && refInfo != tInfo) {
- return hasTextMapping(refInfo);
- }
+ for (Property property : props) {
+ if (property.isAttribute()) {
+ JavaClass ptype = property.getActualType();
+ TypeInfo refInfo = typeInfos.get(ptype.getQualifiedName());
+ if (refInfo != null && refInfo != tInfo) {
+ return hasTextMapping(refInfo);
+ }
}
}
boolean hasXmlId = (tInfo.getIDProperty() != null && !tInfo.getIDProperty().isTransient());
- boolean hasXmlValue = (tInfo.getXmlValueProperty() != null && !tInfo.getXmlValueProperty().isTransient());
- if (hasXmlValue) {
- // Ensure there is an @XmlValue property and nothing else
- hasXmlValue = CompilerHelper.isSimpleType(tInfo);
- }
-
- return (hasXmlValue || hasXmlId);
- }
-
- private Class generateWrapperForMapClass(JavaClass mapClass, JavaClass keyClass, JavaClass valueClass, TypeMappingInfo typeMappingInfo) {
- String packageName = JAXB_DEV;
- NamespaceResolver combinedNamespaceResolver = new NamespaceResolver();
+ boolean hasXmlValue = (tInfo.getXmlValueProperty() != null && !tInfo.getXmlValueProperty().isTransient());
+ if (hasXmlValue) {
+ // Ensure there is an @XmlValue property and nothing else
+ hasXmlValue = CompilerHelper.isSimpleType(tInfo);
+ }
+
+ return (hasXmlValue || hasXmlId);
+ }
+
+ private Class generateWrapperForMapClass(JavaClass mapClass, JavaClass keyClass, JavaClass valueClass, TypeMappingInfo typeMappingInfo) {
+ String packageName = JAXB_DEV;
+ NamespaceResolver combinedNamespaceResolver = new NamespaceResolver();
if (!helper.isBuiltInJavaType(keyClass)) {
String keyPackageName = keyClass.getPackageName();
packageName = packageName + DOT_CHR + keyPackageName;
@@ -4103,45 +4146,45 @@ public class AnnotationsProcessor {
String fieldSig = L + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;";
FieldVisitor fv = cw.visitField(Opcodes.ACC_PUBLIC, "entry", L + mapType.getInternalName() + SEMI_COLON, fieldSig, null);
AnnotationVisitor av = fv.visitAnnotation(Type.getDescriptor(XmlElement.class), true);
- if (typeMappingInfo != null) {
- Annotation[] annotations = typeMappingInfo.getAnnotations();
- if (annotations != null) {
- for (int i = 0; i < annotations.length; i++) {
- Annotation nextAnnotation = annotations[i];
- if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) {
- String annotationClassName = nextAnnotation.annotationType().getName();
- av = fv.visitAnnotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON, true);
- for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) {
- try {
- Object nextValue = next.invoke(nextAnnotation, new Object[] {});
- if (nextValue instanceof Class) {
- Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
- nextValue = nextType;
- }
- av.visit(next.getName(), nextValue);
- } catch (InvocationTargetException ex) {
- // ignore the invocation target exception here.
- } catch (IllegalAccessException ex) {
- }
- }
- av.visitEnd();
+ if (typeMappingInfo != null) {
+ Annotation[] annotations = typeMappingInfo.getAnnotations();
+ if (annotations != null) {
+ for (Annotation nextAnnotation : annotations) {
+ if (nextAnnotation != null && !(nextAnnotation instanceof XmlElement) && !(nextAnnotation instanceof XmlJavaTypeAdapter)) {
+ String annotationClassName = nextAnnotation.annotationType().getName();
+ av = fv.visitAnnotation(L + annotationClassName.replace(DOT_CHR, SLASH_CHR) + SEMI_COLON, true);
+ for (Method next : nextAnnotation.annotationType().getDeclaredMethods()) {
+ try {
+ Object nextValue = next.invoke(nextAnnotation, new Object[] { });
+ if (nextValue instanceof Class) {
+ Type nextType = Type.getType(L + ((Class) nextValue).getName().replace(DOT_CHR, SLASH_CHR) + SEMI_COLON);
+ nextValue = nextType;
+ }
+ av.visit(next.getName(), nextValue);
+ } catch (InvocationTargetException ignored) {
+ // ignore the invocation target exception here.
+ } catch (IllegalAccessException ignored) {
+ // ignore the illegal access exception here.
+ }
+ }
+ av.visitEnd();
}
}
- }
- }
- fv.visitEnd();
-
- MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/MapValue", "<init>", "()V", false);
- mv.visitInsn(Opcodes.RETURN);
- mv.visitMaxs(1, 1);
- mv.visitEnd();
-
- // Write: @XmlTransitent public void setItem(???)
- String methodSig = "(L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;)V";
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setItem", "(L" + mapType.getInternalName() + ";)V", methodSig, null);
- // TODO: Verify that we really want to put @XmlTranient on setItem
+ }
+ }
+ fv.visitEnd();
+
+ MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
+ mv.visitVarInsn(Opcodes.ALOAD, 0);
+ mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/many/MapValue", "<init>", "()V");
+ mv.visitInsn(Opcodes.RETURN);
+ mv.visitMaxs(1, 1);
+ mv.visitEnd();
+
+ // Write: @XmlTransient public void setItem(???)
+ String methodSig = "(L" + mapType.getInternalName() + "<L" + internalKeyName + ";L" + internalValueName + ";>;)V";
+ mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setItem", "(L" + mapType.getInternalName() + ";)V", methodSig, null);
+ // TODO: Verify that we really want to put @XmlTranient on setItem
// method
mv.visitAnnotation("Ljavax/xml/bind/annotation/XmlTransient;", true);
Label l0 = new Label();
@@ -4288,17 +4331,17 @@ public class AnnotationsProcessor {
if (typeMappingInfo != null && xmlElementType != null) {
componentClass = helper.getJavaClass(xmlElementType);
- } else{
- Collection args = collectionClass.getActualTypeArguments();
- if(args.size() >0 ){
- componentClass = ((JavaClass) args.toArray()[0]);
- }else{
- componentClass = helper.getJavaClass(Object.class);
- }
- }
-
- boolean multiDimensional = false;
- if (componentClass.isPrimitive()) {
+ } else{
+ Collection args = collectionClass.getActualTypeArguments();
+ if(args.size() >0 ){
+ componentClass = ((JavaClass) args.toArray()[0]);
+ }else{
+ componentClass = helper.getJavaClass(Object.class);
+ }
+ }
+
+ boolean multiDimensional = false;
+ if (componentClass.isPrimitive()) {
Class primitiveClass = getPrimitiveClass(componentClass.getRawName());
componentClass = helper.getJavaClass(getObjectClass(primitiveClass));
} else if(helper.getJavaClass(Collection.class).isAssignableFrom(componentClass)) {
@@ -4415,72 +4458,72 @@ public class AnnotationsProcessor {
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(superType), "<init>", "()V", false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
- mv.visitEnd();
-
- if(!componentType.isPrimitive() && ArrayValue.class.isAssignableFrom(superType)){
-
- //@Override
- //public Object getItem() {
- // if(null == adaptedValue) {
- // return null;
- // }
- // int len = adaptedValue.size();
- // Float[] array = new Float[len];
- // adaptedValue.toArray(array);
- // return array;
- // }
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getItem", "()Ljava/lang/Object;", null, null);
- mv.visitCode();
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
- Label l0 = new Label();
- mv.visitJumpInsn(Opcodes.IFNONNULL, l0);
- mv.visitInsn(Opcodes.ACONST_NULL);
- mv.visitInsn(Opcodes.ARETURN);
- mv.visitLabel(l0);
- mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
- mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "size", "()I", true);
- mv.visitVarInsn(Opcodes.ISTORE, 1);
- mv.visitVarInsn(Opcodes.ILOAD, 1);
- mv.visitTypeInsn(Opcodes.ANEWARRAY, componentClassNameSeparatedBySlash);
- mv.visitVarInsn(Opcodes.ASTORE, 2);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;", true);
- mv.visitInsn(Opcodes.POP);
-
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitInsn(Opcodes.ARETURN);
- mv.visitMaxs(2, 3);
- mv.visitEnd();
-
-
- //@Override
- //public void setItem(Object array) {
- // Float[] floatArray = (Float[])array;
- // adaptedValue = (Collection<T>) Arrays.asList(floatArray);
- //}
- mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setItem", "(Ljava/lang/Object;)V", null, null);
- mv.visitCode();
- mv.visitVarInsn(Opcodes.ALOAD, 1);
- mv.visitTypeInsn(Opcodes.CHECKCAST, "[L"+componentClassNameSeparatedBySlash+";");
- mv.visitVarInsn(Opcodes.ASTORE, 2);
- mv.visitVarInsn(Opcodes.ALOAD, 0);
- mv.visitVarInsn(Opcodes.ALOAD, 2);
- mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
- mv.visitFieldInsn(Opcodes.PUTFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
- mv.visitInsn(Opcodes.RETURN);
- mv.visitMaxs(2, 3);
- mv.visitEnd();
- }
-
-
- // @XmlElement(name="item", nillable=true)
- // public Collection<COMPONENT_TYPE> getAdaptedValue() {
- // return super.getAdaptedValue();
+ mv.visitEnd();
+
+ if(!componentType.isPrimitive() && ArrayValue.class.isAssignableFrom(superType)){
+
+ //@Override
+ //public Object getItem() {
+ // if(null == adaptedValue) {
+ // return null;
+ // }
+ // int len = adaptedValue.size();
+ // Float[] array = new Float[len];
+ // adaptedValue.toArray(array);
+ // return array;
+ // }
+ mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getItem", "()Ljava/lang/Object;", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(Opcodes.ALOAD, 0);
+ mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
+ Label l0 = new Label();
+ mv.visitJumpInsn(Opcodes.IFNONNULL, l0);
+ mv.visitInsn(Opcodes.ACONST_NULL);
+ mv.visitInsn(Opcodes.ARETURN);
+ mv.visitLabel(l0);
+ mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
+ mv.visitVarInsn(Opcodes.ALOAD, 0);
+ mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
+ mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "size", "()I", true);
+ mv.visitVarInsn(Opcodes.ISTORE, 1);
+ mv.visitVarInsn(Opcodes.ILOAD, 1);
+ mv.visitTypeInsn(Opcodes.ANEWARRAY, componentClassNameSeparatedBySlash);
+ mv.visitVarInsn(Opcodes.ASTORE, 2);
+ mv.visitVarInsn(Opcodes.ALOAD, 0);
+ mv.visitFieldInsn(Opcodes.GETFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
+ mv.visitVarInsn(Opcodes.ALOAD, 2);
+ mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;");
+ mv.visitInsn(Opcodes.POP);
+
+ mv.visitVarInsn(Opcodes.ALOAD, 2);
+ mv.visitInsn(Opcodes.ARETURN);
+ mv.visitMaxs(2, 3);
+ mv.visitEnd();
+
+
+ //@Override
+ //public void setItem(Object array) {
+ // Float[] floatArray = (Float[])array;
+ // adaptedValue = (Collection<T>) Arrays.asList(floatArray);
+ //}
+ mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setItem", "(Ljava/lang/Object;)V", null, null);
+ mv.visitCode();
+ mv.visitVarInsn(Opcodes.ALOAD, 1);
+ mv.visitTypeInsn(Opcodes.CHECKCAST, "[L"+componentClassNameSeparatedBySlash+";");
+ mv.visitVarInsn(Opcodes.ASTORE, 2);
+ mv.visitVarInsn(Opcodes.ALOAD, 0);
+ mv.visitVarInsn(Opcodes.ALOAD, 2);
+ mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", false);
+ mv.visitFieldInsn(Opcodes.PUTFIELD, classNameSeparatedBySlash, "adaptedValue", "Ljava/util/Collection;");
+ mv.visitInsn(Opcodes.RETURN);
+ mv.visitMaxs(2, 3);
+ mv.visitEnd();
+ }
+
+
+ // @XmlElement(name="item", nillable=true)
+ // public Collection<COMPONENT_TYPE> getAdaptedValue() {
+ // return super.getAdaptedValue();
// }
// OR
// @XmlValue
@@ -4593,12 +4636,11 @@ public class AnnotationsProcessor {
private Class generateClassFromBytes(String className, byte[] classBytes) {
JaxbClassLoader loader = (JaxbClassLoader) helper.getClassLoader();
Class generatedClass = loader.generateClass(className, classBytes);
- return generatedClass;
- }
-
- // Made static final for performance reasons.
- /**
- * Inner class used for ordering a list of Properties alphabetically by
+ return generatedClass;
+ }
+
+ /**
+ * Inner class used for ordering a list of Properties alphabetically by
* property name.
*
*/
@@ -4606,19 +4648,19 @@ public class AnnotationsProcessor {
public int compare(Property p1, Property p2) {
return p1.getPropertyName().compareTo(p2.getPropertyName());
}
- }
-
- private String getNextAvailableClassName(String suggestedName) {
+ }
+
+ private String getNextAvailableClassName(String suggestedName) {
int counter = 1;
return getNextAvailableClassName(suggestedName, suggestedName, counter);
}
-
- private String getNextAvailableClassName(String suggestedBaseName, String suggestedName, int counter) {
-
- Iterator<Class> iter = typeMappingInfoToGeneratedClasses.values().iterator();
- while (iter.hasNext()) {
- Class nextClass = iter.next();
- if (nextClass.getName().equals(suggestedName)) {
+
+ private String getNextAvailableClassName(String suggestedBaseName, String suggestedName, int counter) {
+
+ Iterator<Class> iter = typeMappingInfosToGeneratedClasses.values().iterator();
+ while (iter.hasNext()) {
+ Class nextClass = iter.next();
+ if (nextClass.getName().equals(suggestedName)) {
counter = counter + 1;
return getNextAvailableClassName(suggestedBaseName, suggestedBaseName + counter, counter);
}
@@ -4650,67 +4692,67 @@ public class AnnotationsProcessor {
return generatedClassesToArrayClasses;
}
- /**
- * Convenience method for returning all of the TypeInfo objects for a given
- * package name.
- *
- * This method is inefficient as we need to iterate over the entire typeinfo
- * map for each call. We should eventually store the TypeInfos in a Map
- * based on package name, i.e.:
- *
- * Map<String, Map<String, TypeInfo>>
- *
- * @param packageName
- * @return List of TypeInfo objects for a given package name
- */
- public Map<String, TypeInfo> getTypeInfosForPackage(String packageName) {
- Map<String, TypeInfo> typeInfos = new HashMap<String, TypeInfo>();
- ArrayList<JavaClass> jClasses = getTypeInfoClasses();
- for (JavaClass jClass : jClasses) {
- if (jClass.getPackageName().equals(packageName)) {
- String key = jClass.getQualifiedName();
- typeInfos.put(key, typeInfo.get(key));
- }
- }
- return typeInfos;
+ /**
+ * Convenience method for returning all of the TypeInfo objects for a given
+ * package name.
+ *
+ * This method is inefficient as we need to iterate over the entire typeinfo
+ * map for each call. We should eventually store the TypeInfos in a Map
+ * based on package name, i.e.:
+ *
+ * Map<String, Map<String, TypeInfo>>
+ *
+ * @param packageName
+ * @return List of TypeInfo objects for a given package name
+ */
+ public Map<String, TypeInfo> getTypeInfosForPackage(String packageName) {
+ Map<String, TypeInfo> typeInfos = new HashMap<String, TypeInfo>();
+ List<JavaClass> jClasses = getTypeInfoClasses();
+ for (JavaClass jClass : jClasses) {
+ if (jClass.getPackageName().equals(packageName)) {
+ String key = jClass.getQualifiedName();
+ typeInfos.put(key, this.typeInfos.get(key));
+ }
+ }
+ return typeInfos;
}
- /**
- * Set namespace override info from XML bindings file. This will typically
- * be called from the XMLProcessor.
- *
- * @param packageToNamespaceMappings
- */
- public void setPackageToNamespaceMappings(HashMap<String, NamespaceInfo> packageToNamespaceMappings) {
- //this.packageToNamespaceMappings = packageToNamespaceMappings;
- }
-
- public void setPackageToPackageInfoMappings(HashMap<String, PackageInfo> packageToPackageInfoMappings) {
- this.packageToPackageInfoMappings = packageToPackageInfoMappings;
- }
+ /**
+ * Set namespace override info from XML bindings file. This will typically
+ * be called from the XMLProcessor.
+ *
+ * @param packageToNamespaceMappings
+ */
+ public void setPackageToNamespaceMappings(HashMap<String, NamespaceInfo> packageToNamespaceMappings) {
+ //this.packageToNamespaceMappings = packageToNamespaceMappings;
+ }
+
+ public void setPackageToPackageInfoMappings(HashMap<String, PackageInfo> packageToPackageInfoMappings) {
+ this.packageToPackageInfoMappings = packageToPackageInfoMappings;
+ }
public SchemaTypeInfo addClass(JavaClass javaClass) {
if (javaClass == null) {
return null;
} else if (helper.isAnnotationPresent(javaClass, XmlTransient.class)) {
- return null;
- }
-
- if (typeInfo == null) {
- // this is the first class. Initialize all the properties
- this.typeInfoClasses = new ArrayList<JavaClass>();
- this.typeInfo = new HashMap<String, TypeInfo>();
- this.typeQNames = new ArrayList<QName>();
- this.userDefinedSchemaTypes = new HashMap<String, QName>();
- this.packageToPackageInfoMappings = new HashMap<String, PackageInfo>();
- }
-
- JavaClass[] jClasses = new JavaClass[] { javaClass };
- buildNewTypeInfo(jClasses);
- TypeInfo info = typeInfo.get(javaClass.getQualifiedName());
-
- PackageInfo packageInfo;
- String packageName = javaClass.getPackageName();
+ return null;
+ }
+
+ if (typeInfos == null) {
+ // this is the first class. Initialize all the properties
+ this.typeInfoClasses = new ArrayList<JavaClass>();
+ this.typeInfos = new HashMap<String, TypeInfo>();
+ this.typeQNames = new ArrayList<QName>();
+ this.userDefinedSchemaTypes = new HashMap<String, QName>();
+ this.packageToPackageInfoMappings = new HashMap<String, PackageInfo>();
+ }
+
+ JavaClass[] jClasses = new JavaClass[] { javaClass };
+ buildNewTypeInfo(jClasses);
+ TypeInfo info = typeInfos.get(javaClass.getQualifiedName());
+
+ PackageInfo packageInfo;
+ String packageName = javaClass.getPackageName();
packageInfo = this.packageToPackageInfoMappings.get(packageName);
SchemaTypeInfo schemaInfo = new SchemaTypeInfo();
@@ -4741,13 +4783,13 @@ public class AnnotationsProcessor {
return schemaInfo;
}
- /**
- * Convenience method which class pre and postBuildTypeInfo for a given set
- * of JavaClasses.
- *
- * @param javaClasses
- */
- public void buildNewTypeInfo(JavaClass[] javaClasses) {
+ /**
+ * Convenience method which class pre and postBuildTypeInfo for a given set
+ * of JavaClasses.
+ *
+ * @param javaClasses
+ */
+ public void buildNewTypeInfo(JavaClass[] javaClasses) {
preBuildTypeInfo(javaClasses);
javaClasses = postBuildTypeInfo(javaClasses);
for(JavaClass next:javaClasses) {
@@ -4755,17 +4797,17 @@ public class AnnotationsProcessor {
}
}
- /**
- * Pre-process a descriptor customizer. Here, the given JavaClass is checked
- * for the existence of an @XmlCustomizer annotation.
- *
- * Note that the post processing of the descriptor customizers will take
- * place in MappingsGenerator's generateProject method, after the
- * descriptors and mappings have been generated.
- *
- * @param jClass
- * @param tInfo
- * @see XmlCustomizer
+ /**
+ * Pre-process a descriptor customizer. Here, the given JavaClass is checked
+ * for the existence of an @XmlCustomizer annotation.
+ *
+ * Note that the post processing of the descriptor customizers will take
+ * place in MappingsGenerator's generateProject method, after the
+ * descriptors and mappings have been generated.
+ *
+ * @param jClass
+ * @param tInfo
+ * @see XmlCustomizer
* @see MappingsGenerator
*/
private void preProcessCustomizer(JavaClass jClass, TypeInfo tInfo) {
@@ -4774,25 +4816,25 @@ public class AnnotationsProcessor {
tInfo.setXmlCustomizer(xmlCustomizer.value().getName());
}
}
-
- /**
- * Lazy load the metadata logger.
- *
- * @return
- */
- private JAXBMetadataLogger getLogger() {
+
+ /**
+ * Lazy load the metadata logger.
+ *
+ * @return
+ */
+ private JAXBMetadataLogger getLogger() {
if (logger == null) {
logger = new JAXBMetadataLogger();
}
return logger;
}
-
- /**
- * Return the Helper object set on this processor.
- *
- * @return
- */
- Helper getHelper() {
+
+ /**
+ * Return the Helper object set on this processor.
+ *
+ * @return
+ */
+ Helper getHelper() {
return this.helper;
}
@@ -4801,50 +4843,50 @@ public class AnnotationsProcessor {
}
public List<ElementDeclaration> getLocalElements() {
- return this.localElements;
- }
-
- public Map<TypeMappingInfo, Class> getTypeMappingInfoToGeneratedClasses() {
- return this.typeMappingInfoToGeneratedClasses;
- }
-
- public Map<TypeMappingInfo, Class> getTypeMappingInfoToAdapterClasses() {
+ return this.localElements;
+ }
+
+ public Map<TypeMappingInfo, Class> getTypeMappingInfosToGeneratedClasses() {
+ return this.typeMappingInfosToGeneratedClasses;
+ }
+
+ public Map<TypeMappingInfo, Class> getTypeMappingInfoToAdapterClasses() {
return this.typeMappingInfoToAdapterClasses;
}
-
- /**
- * Add an XmlRegistry to ObjectFactory class name pair to the map.
- *
- * @param factoryClassName
- * ObjectFactory class name
- * @param xmlReg
- * org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry instance
- */
- public void addXmlRegistry(String factoryClassName, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg) {
- this.xmlRegistries.put(factoryClassName, xmlReg);
+
+ /**
+ * Add an XmlRegistry to ObjectFactory class name pair to the map.
+ *
+ * @param factoryClassName
+ * ObjectFactory class name
+ * @param xmlReg
+ * org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry instance
+ */
+ public void addXmlRegistry(String factoryClassName, org.eclipse.persistence.jaxb.xmlmodel.XmlRegistry xmlReg) {
+ this.xmlRegistries.put(factoryClassName, xmlReg);
}
- /**
- * Convenience method for determining if a given JavaClass should be
- * processed as an ObjectFactory class.
- *
- * @param javaClass
- * @return true if the JavaClass is annotated with @XmlRegistry or the map
- * of XmlRegistries contains a key equal to the JavaClass' qualified
- * name
- */
- private boolean isXmlRegistry(JavaClass javaClass) {
- if (javaClass == null) {
+ /**
+ * Convenience method for determining if a given JavaClass should be
+ * processed as an ObjectFactory class.
+ *
+ * @param javaClass
+ * @return true if the JavaClass is annotated with @XmlRegistry or the map
+ * of XmlRegistries contains a key equal to the JavaClass' qualified
+ * name
+ */
+ private boolean isXmlRegistry(JavaClass javaClass) {
+ if (javaClass == null) {
return false;
}
- return (helper.isAnnotationPresent(javaClass, XmlRegistry.class) || xmlRegistries.get(javaClass.getQualifiedName()) != null);
- }
-
- public Map<TypeMappingInfo, QName> getTypeMappingInfoToSchemaType() {
- return this.typeMappingInfoToSchemaType;
- }
-
- String getDefaultTargetNamespace() {
+ return (helper.isAnnotationPresent(javaClass, XmlRegistry.class) || xmlRegistries.get(javaClass.getQualifiedName()) != null);
+ }
+
+ public Map<TypeMappingInfo, QName> getTypeMappingInfosToSchemaTypes() {
+ return this.typeMappingInfosToSchemaTypes;
+ }
+
+ String getDefaultTargetNamespace() {
return this.defaultTargetNamespace;
}
@@ -4853,21 +4895,21 @@ public class AnnotationsProcessor {
}
public void setDefaultNamespaceAllowed(boolean isDefaultNamespaceAllowed) {
- this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed;
- }
-
- HashMap<QName, ElementDeclaration> getElementDeclarationsForScope(String scopeClassName) {
- return this.elementDeclarations.get(scopeClassName);
- }
-
+ this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed;
+ }
+
+ Map<QName, ElementDeclaration> getElementDeclarationsForScope(String scopeClassName) {
+ return this.elementDeclarations.get(scopeClassName);
+ }
+
private void addGlobalElement(QName key, ElementDeclaration declaration){
- getGlobalElements().put(key, declaration);
- classesToProcessPropertyTypes.add(declaration.getJavaType());
- }
-
- private Map<Object, Object> createUserPropertiesMap(XmlProperty[] properties) {
- Map<Object, Object> propMap = new HashMap<Object, Object>();
- for (XmlProperty prop : properties) {
+ getGlobalElements().put(key, declaration);
+ classesToProcessPropertyTypes.add(declaration.getJavaType());
+ }
+
+ private Map<Object, Object> createUserPropertiesMap(XmlProperty[] properties) {
+ Map<Object, Object> propMap = new HashMap<Object, Object>();
+ for (XmlProperty prop : properties) {
Object pvalue = prop.value();
if (!(prop.valueType() == String.class)) {
pvalue = XMLConversionManager.getDefaultXMLManager().convertObject(prop.value(), prop.valueType());
@@ -4877,15 +4919,15 @@ public class AnnotationsProcessor {
return propMap;
}
- /**
- * Indicates if a given Property represents an MTOM attachment. Will return
- * true if the given Property's actual type is one of:
- *
- * - DataHandler - byte[] - Byte[] - Image - Source - MimeMultipart
- *
- * @param property
- * @return
- */
+ /**
+ * Indicates if a given Property represents an MTOM attachment. Will return
+ * true if the given Property's actual type is one of:
+ *
+ * - DataHandler - byte[] - Byte[] - Image - Source - MimeMultipart
+ *
+ * @param property
+ * @return
+ */
public boolean isMtomAttachment(Property property) {
JavaClass ptype = property.getActualType();
return (areEquals(ptype, JAVAX_ACTIVATION_DATAHANDLER) || areEquals(ptype, byte[].class) || areEquals(ptype, Image.class) || areEquals(ptype, Source.class) || areEquals(ptype, JAVAX_MAIL_INTERNET_MIMEMULTIPART));
@@ -4895,38 +4937,38 @@ public class AnnotationsProcessor {
return this.hasSwaRef;
}
- public void setHasSwaRef(boolean swaRef) {
- this.hasSwaRef = swaRef;
- }
-
- public List getReferencedByTransformer(){
- return referencedByTransformer;
- }
-
- /**
- * Indicates whether this AnnotationsProcessor has been configured to enable
- * processing of XmlAccessorFactory annotations.
- *
- * @see com.sun.xml.bind.XmlAccessorFactory
- */
- public boolean isXmlAccessorFactorySupport() {
+ public void setHasSwaRef(boolean swaRef) {
+ this.hasSwaRef = swaRef;
+ }
+
+ public List getReferencedByTransformer(){
+ return referencedByTransformer;
+ }
+
+ /**
+ * Indicates whether this AnnotationsProcessor has been configured to enable
+ * processing of XmlAccessorFactory annotations.
+ *
+ * @see com.sun.xml.bind.XmlAccessorFactory
+ */
+ public boolean isXmlAccessorFactorySupport() {
return xmlAccessorFactorySupport;
}
-
- /**
- * Sets whether this AnnotationsProcessor should process XmlAccessorFactory annotations.
- *
- * @see com.sun.xml.bind.XmlAccessorFactory
- */
- public void setXmlAccessorFactorySupport(boolean value) {
+
+ /**
+ * Sets whether this AnnotationsProcessor should process XmlAccessorFactory annotations.
+ *
+ * @see com.sun.xml.bind.XmlAccessorFactory
+ */
+ public void setXmlAccessorFactorySupport(boolean value) {
this.xmlAccessorFactorySupport = value;
}
- public void setHasXmlBindings(boolean b) {
- this.hasXmlBindings = true;
- }
-
- public boolean hasXmlBindings() {
- return this.hasXmlBindings;
- }
-}
+ public void setHasXmlBindings(boolean b) {
+ this.hasXmlBindings = true;
+ }
+
+ public boolean hasXmlBindings() {
+ return this.hasXmlBindings;
+ }
+} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/CompilerHelper.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/CompilerHelper.java
index 31e2471..b072c2a 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/CompilerHelper.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/CompilerHelper.java
@@ -460,13 +460,13 @@ public class CompilerHelper {
throw org.eclipse.persistence.exceptions.JAXBException.couldNotCreateContextForXmlModel();
}
}
- return xmlBindingsModelContext;
- }
-
- public static JavaClass getNextMappedSuperClass(JavaClass cls, HashMap<String, TypeInfo> typeInfo, Helper helper) {
- JavaClass superClass = cls.getSuperclass();
-
- if(superClass == null || helper.isBuiltInJavaType(cls) || superClass.getRawName().equals("java.lang.Object")){
+ return xmlBindingsModelContext;
+ }
+
+ public static JavaClass getNextMappedSuperClass(JavaClass cls, Map<String, TypeInfo> typeInfo, Helper helper) {
+ JavaClass superClass = cls.getSuperclass();
+
+ if(superClass == null || helper.isBuiltInJavaType(cls) || superClass.getRawName().equals("java.lang.Object")){
return null;
}
TypeInfo parentTypeInfo = typeInfo.get(superClass.getQualifiedName());
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/ElementDeclaration.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/ElementDeclaration.java
index 1b6ec21..571791b 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/ElementDeclaration.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/ElementDeclaration.java
@@ -287,13 +287,13 @@ public class ElementDeclaration {
public TypeMappingInfo getTypeMappingInfo() {
return this.typeMappingInfo;
}
-
- /**
- * Set the TypeMappingInfo object if this ElementDeclaration was created from a TypeMappingInfo
- * @param The TypeMappingInfo object used to create this ElementDeclaration
- */
- public void setTypeMappingInfo(TypeMappingInfo info) {
- this.typeMappingInfo = info;
+
+ /**
+ * Set the TypeMappingInfo object if this ElementDeclaration was created from a TypeMappingInfo
+ * @param info The TypeMappingInfo object used to create this ElementDeclaration
+ */
+ public void setTypeMappingInfo(TypeMappingInfo info) {
+ this.typeMappingInfo = info;
}
/**
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/EnumTypeInfo.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/EnumTypeInfo.java
index ab4ebd7..d6ec55d 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/EnumTypeInfo.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/EnumTypeInfo.java
@@ -26,13 +26,13 @@ import org.eclipse.persistence.jaxb.javamodel.JavaClass;
* <p><b>Responsibilities:</b><ul>
* <li>Hold onto the restriction base type for schema generation</li>
* <li>Hold onto a map of Object Enum values to String values for Mapping generation</li>
- * </ul>
- *
- * @see org.eclipse.persistence.jaxb.compiler.TypeInfo
- * @see org.eclipse.persistence.jaxb.AnnotationsProcessor
- * @author mmacivor
- *
- */
+ * </ul>
+ *
+ * @see org.eclipse.persistence.jaxb.compiler.TypeInfo
+ * @see org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor
+ * @author mmacivor
+ *
+ */
public class EnumTypeInfo extends TypeInfo {
private String m_className;
private QName m_restrictionBase;
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Generator.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Generator.java
index 65f3963..068d275 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Generator.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Generator.java
@@ -14,28 +14,29 @@ package org.eclipse.persistence.jaxb.compiler;
import java.io.File;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.xml.bind.SchemaOutputResolver;
-import javax.xml.namespace.QName;
-
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.xml.XMLConstants;
+import javax.xml.bind.SchemaOutputResolver;
+import javax.xml.namespace.QName;
+
import org.eclipse.persistence.core.sessions.CoreProject;
import org.eclipse.persistence.internal.oxm.Constants;
import org.eclipse.persistence.internal.oxm.mappings.Descriptor;
import org.eclipse.persistence.internal.oxm.schema.SchemaModelProject;
import org.eclipse.persistence.internal.oxm.schema.model.Schema;
import org.eclipse.persistence.jaxb.TypeMappingInfo;
-import org.eclipse.persistence.jaxb.javamodel.Helper;
-import org.eclipse.persistence.jaxb.javamodel.JavaClass;
-import org.eclipse.persistence.jaxb.javamodel.JavaModelInput;
-import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings;
-import org.eclipse.persistence.oxm.NamespaceResolver;
-import org.eclipse.persistence.oxm.XMLContext;
+import org.eclipse.persistence.jaxb.javamodel.Helper;
+import org.eclipse.persistence.jaxb.javamodel.JavaClass;
+import org.eclipse.persistence.jaxb.javamodel.JavaModelInput;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelInputImpl;
+import org.eclipse.persistence.jaxb.xmlmodel.XmlBindings;
+import org.eclipse.persistence.oxm.NamespaceResolver;
+import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.sessions.Project;
@@ -73,12 +74,13 @@ public class Generator {
* instance's JavaModel. Annotations are processed here as well.
*
* @param jModelInput
- */
- public Generator(JavaModelInput jModelInput) {
- helper = new Helper(jModelInput.getJavaModel());
- annotationsProcessor = new AnnotationsProcessor(helper);
- schemaGenerator = new SchemaGenerator(helper);
- mappingsGenerator = new MappingsGenerator(helper);
+ */
+ public Generator(JavaModelInput jModelInput) {
+ helper = new Helper(jModelInput.getJavaModel());
+ if (jModelInput instanceof JavaModelInputImpl) helper.setFacets(((JavaModelInputImpl) jModelInput).isFacets());
+ annotationsProcessor = new AnnotationsProcessor(helper);
+ schemaGenerator = new SchemaGenerator(helper);
+ mappingsGenerator = new MappingsGenerator(helper);
annotationsProcessor.processClassesAndProperties(jModelInput.getJavaClasses(), null);
}
@@ -97,13 +99,13 @@ public class Generator {
helper = new Helper(jModelInput.getJavaModel());
annotationsProcessor = new AnnotationsProcessor(helper);
annotationsProcessor.setXmlAccessorFactorySupport(enableXmlAccessorFactory);
- annotationsProcessor.setDefaultTargetNamespace(defaultTargetNamespace);
- schemaGenerator = new SchemaGenerator(helper);
- mappingsGenerator = new MappingsGenerator(helper);
- if (xmlBindings != null && xmlBindings.size() > 0) {
- new XMLProcessor(xmlBindings).processXML(annotationsProcessor, jModelInput, null, null);
- } else {
- annotationsProcessor.processClassesAndProperties(jModelInput.getJavaClasses(), null);
+ annotationsProcessor.setDefaultTargetNamespace(defaultTargetNamespace);
+ schemaGenerator = new SchemaGenerator(helper);
+ mappingsGenerator = new MappingsGenerator(helper);
+ if (xmlBindings != null && !xmlBindings.isEmpty()) {
+ new XMLProcessor(xmlBindings).processXML(annotationsProcessor, jModelInput, null, null);
+ } else {
+ annotationsProcessor.processClassesAndProperties(jModelInput.getJavaClasses(), null);
}
}
@@ -129,25 +131,29 @@ public class Generator {
* declared in the bindings will be amalgamated with any classes in the JavaModelInput.
*
* If xmlBindings is null or empty, AnnotationsProcessor will be used to process
- * annotations as per usual.
- *
- * @param jModelInput
- * @param javaClassToType
- * @param xmlBindings map of XmlBindings keyed on package name
- * @param cLoader
- */
+ * annotations as per usual.
+ *
+ * @param jModelInput
+ * @param defaultTargetNamespace
+ * @param enableXmlAccessorFactory
+ * @param javaClasses
+ * @param typeMappingInfos
+ * @param typeToTypeMappingInfo
+ * @param xmlBindings map of XmlBindings keyed on package name
+ * @param cLoader
+ */
public Generator(JavaModelInput jModelInput, TypeMappingInfo[] typeMappingInfos, JavaClass[] javaClasses, Map<Type, TypeMappingInfo> typeToTypeMappingInfo, Map<String, XmlBindings> xmlBindings, ClassLoader cLoader, String defaultTargetNamespace, boolean enableXmlAccessorFactory) {
helper = new Helper(jModelInput.getJavaModel());
annotationsProcessor = new AnnotationsProcessor(helper);
annotationsProcessor.setXmlAccessorFactorySupport(enableXmlAccessorFactory);
annotationsProcessor.setDefaultTargetNamespace(defaultTargetNamespace);
- schemaGenerator = new SchemaGenerator(helper);
- mappingsGenerator = new MappingsGenerator(helper);
- this.typeToTypeMappingInfo = typeToTypeMappingInfo;
- if (xmlBindings != null && xmlBindings.size() > 0) {
- new XMLProcessor(xmlBindings).processXML(annotationsProcessor, jModelInput, typeMappingInfos, javaClasses);
- } else {
- annotationsProcessor.processClassesAndProperties(javaClasses, typeMappingInfos);
+ schemaGenerator = new SchemaGenerator(helper);
+ mappingsGenerator = new MappingsGenerator(helper);
+ this.typeToTypeMappingInfo = typeToTypeMappingInfo;
+ if (xmlBindings != null && !xmlBindings.isEmpty()) {
+ new XMLProcessor(xmlBindings).processXML(annotationsProcessor, jModelInput, typeMappingInfos, javaClasses);
+ } else {
+ annotationsProcessor.processClassesAndProperties(javaClasses, typeMappingInfos);
}
}
@@ -163,78 +169,68 @@ public class Generator {
}
/**
- *
- */
- public boolean hasMarshalCallbacks() {
- return getMarshalCallbacks()!=null && getMarshalCallbacks().size()>0;
- }
-
- public boolean hasUnmarshalCallbacks() {
- return getUnmarshalCallbacks()!=null && getUnmarshalCallbacks().size()>0;
- }
-
- /**
- * INTERNAL:
- *
- * @param javaClass
- * @return
- */
- public SchemaTypeInfo addClass(JavaClass javaClass) {
- return annotationsProcessor.addClass(javaClass);
- }
-
- public CoreProject generateProject() throws Exception {
- mappingsGenerator.getClassToGeneratedClasses().putAll(annotationsProcessor.getArrayClassesToGeneratedClasses());
- CoreProject p = mappingsGenerator.generateProject(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfo(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getLocalElements(), annotationsProcessor.getTypeMappingInfoToGeneratedClasses(), annotationsProcessor.getTypeMappingInfoToAdapterClasses(),annotationsProcessor.isDefaultNamespaceAllowed());
- annotationsProcessor.getArrayClassesToGeneratedClasses().putAll(mappingsGenerator.getClassToGeneratedClasses());
- return p;
- }
-
- public java.util.Collection<Schema> generateSchema() {
- schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfo(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), null, annotationsProcessor.getArrayClassesToGeneratedClasses());
- return schemaGenerator.getAllSchemas();
- }
-
- public HashMap<String, SchemaTypeInfo> generateSchemaFiles(String schemaPath, Map<QName, Type> additionalGlobalElements) throws FileNotFoundException {
- // process any additional global elements
- processAdditionalElements(additionalGlobalElements, annotationsProcessor);
-
- schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfo(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getArrayClassesToGeneratedClasses());
- CoreProject proj = new SchemaModelProject();
- XMLContext context = new XMLContext((Project)proj);
- XMLMarshaller marshaller = context.createMarshaller();
+ *
+ */
+ public boolean hasMarshalCallbacks() {
+ return getMarshalCallbacks()!=null && !getMarshalCallbacks().isEmpty();
+ }
+
+ public boolean hasUnmarshalCallbacks() {
+ return getUnmarshalCallbacks()!=null && !getUnmarshalCallbacks().isEmpty();
+ }
+
+ public CoreProject generateProject() throws Exception {
+ mappingsGenerator.getClassToGeneratedClasses().putAll(annotationsProcessor.getArrayClassesToGeneratedClasses());
+ CoreProject p = mappingsGenerator.generateProject(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfos(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getLocalElements(), annotationsProcessor.getTypeMappingInfosToGeneratedClasses(), annotationsProcessor.getTypeMappingInfoToAdapterClasses(),annotationsProcessor.isDefaultNamespaceAllowed());
+ annotationsProcessor.getArrayClassesToGeneratedClasses().putAll(mappingsGenerator.getClassToGeneratedClasses());
+ return p;
+ }
+
+ public java.util.Collection<Schema> generateSchema() {
+ schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfos(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), null, annotationsProcessor.getArrayClassesToGeneratedClasses());
+ return schemaGenerator.getAllSchemas();
+ }
+
+ public Map<String, SchemaTypeInfo> generateSchemaFiles(String schemaPath, Map<QName, Type> additionalGlobalElements) throws FileNotFoundException {
+ // process any additional global elements
+ processAdditionalElements(additionalGlobalElements, annotationsProcessor);
+
+ schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfos(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getArrayClassesToGeneratedClasses());
+ CoreProject proj = new SchemaModelProject();
+ XMLContext context = new XMLContext((Project)proj);
+ XMLMarshaller marshaller = context.createMarshaller();
Descriptor schemaDescriptor = (Descriptor)proj.getDescriptor(Schema.class);
java.util.Collection<Schema> schemas = schemaGenerator.getAllSchemas();
- for(Schema schema : schemas) {
- File file = new File(schemaPath + "/" + schema.getName());
- NamespaceResolver schemaNamespaces = schema.getNamespaceResolver();
- schemaNamespaces.put(Constants.SCHEMA_PREFIX, "http://www.w3.org/2001/XMLSchema");
- schemaDescriptor.setNamespaceResolver(schemaNamespaces);
- marshaller.marshal(schema, new FileOutputStream(file));
- }
- return schemaGenerator.getSchemaTypeInfo();
- }
-
- public HashMap<String, SchemaTypeInfo> generateSchemaFiles(SchemaOutputResolver outputResolver, Map<QName, Type> additionalGlobalElements) {
- // process any additional global elements
- processAdditionalElements(additionalGlobalElements, annotationsProcessor);
-
- schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfo(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getArrayClassesToGeneratedClasses(), outputResolver);
- CoreProject proj = new SchemaModelProject();
- XMLContext context = new XMLContext((Project)proj);
- XMLMarshaller marshaller = context.createMarshaller();
+ for(Schema schema : schemas) {
+ File file = new File(schemaPath + "/" + schema.getName());
+ NamespaceResolver schemaNamespaces = schema.getNamespaceResolver();
+ schemaNamespaces.put(Constants.SCHEMA_PREFIX, XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ schemaDescriptor.setNamespaceResolver(schemaNamespaces);
+ marshaller.marshal(schema, new FileOutputStream(file));
+ }
+ return schemaGenerator.getSchemaTypeInfo();
+ }
+
+ public Map<String, SchemaTypeInfo> generateSchemaFiles(SchemaOutputResolver outputResolver, Map<QName, Type> additionalGlobalElements) {
+ // process any additional global elements
+ processAdditionalElements(additionalGlobalElements, annotationsProcessor);
+
+ schemaGenerator.generateSchema(annotationsProcessor.getTypeInfoClasses(), annotationsProcessor.getTypeInfos(), annotationsProcessor.getUserDefinedSchemaTypes(), annotationsProcessor.getPackageToPackageInfoMappings(), annotationsProcessor.getGlobalElements(), annotationsProcessor.getArrayClassesToGeneratedClasses(), outputResolver);
+ CoreProject proj = new SchemaModelProject();
+ XMLContext context = new XMLContext((Project)proj);
+ XMLMarshaller marshaller = context.createMarshaller();
Descriptor schemaDescriptor = (Descriptor)proj.getDescriptor(Schema.class);
java.util.Collection<Schema> schemas = schemaGenerator.getAllSchemas();
- for(Schema schema : schemas) {
- try {
- NamespaceResolver schemaNamespaces = schema.getNamespaceResolver();
- schemaNamespaces.put(Constants.SCHEMA_PREFIX, "http://www.w3.org/2001/XMLSchema");
- schemaDescriptor.setNamespaceResolver(schemaNamespaces);
- // make sure we don't call into the provided output resolver more than once
- javax.xml.transform.Result target;
+ for(Schema schema : schemas) {
+ try {
+ NamespaceResolver schemaNamespaces = schema.getNamespaceResolver();
+ schemaNamespaces.put(Constants.SCHEMA_PREFIX, XMLConstants.W3C_XML_SCHEMA_NS_URI);
+ schemaDescriptor.setNamespaceResolver(schemaNamespaces);
+ // make sure we don't call into the provided output resolver more than once
+ javax.xml.transform.Result target;
if (schema.hasResult()) {
target = schema.getResult();
} else {
@@ -267,14 +263,14 @@ public class Generator {
TypeMappingInfo tmi = null;
if(this.typeToTypeMappingInfo != null) {
tmi = this.typeToTypeMappingInfo.get(type);
- }
-
- if(tmi != null) {
- if(annotationsProcessor.getTypeMappingInfoToGeneratedClasses().get(tmi) != null) {
- type = annotationsProcessor.getTypeMappingInfoToGeneratedClasses().get(tmi);
- }
- }
- JavaClass jClass = null;
+ }
+
+ if(tmi != null) {
+ if(annotationsProcessor.getTypeMappingInfosToGeneratedClasses().get(tmi) != null) {
+ type = annotationsProcessor.getTypeMappingInfosToGeneratedClasses().get(tmi);
+ }
+ }
+ JavaClass jClass = null;
if (type instanceof Class) {
Class tClass = (Class) type;
jClass = helper.getJavaClass(tClass);
@@ -285,17 +281,17 @@ public class Generator {
annotationsProcessor.getGlobalElements().put(key, declaration);
}
}
- }
- }
-
- public java.util.HashMap getUnmarshalCallbacks() {
- return annotationsProcessor.getUnmarshalCallbacks();
- }
-
- public java.util.HashMap getMarshalCallbacks() {
- return annotationsProcessor.getMarshalCallbacks();
- }
-
+ }
+ }
+
+ public Map getUnmarshalCallbacks() {
+ return annotationsProcessor.getUnmarshalCallbacks();
+ }
+
+ public Map getMarshalCallbacks() {
+ return annotationsProcessor.getMarshalCallbacks();
+ }
+
public MappingsGenerator getMappingsGenerator() {
return this.mappingsGenerator;
}
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/MappingsGenerator.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/MappingsGenerator.java
index 0a4598a..80b4d4d 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/MappingsGenerator.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/MappingsGenerator.java
@@ -179,25 +179,25 @@ public class MappingsGenerator {
private static final String ATT = "@";
private static final String TXT = "/text()";
private static String OBJECT_CLASS_NAME = "java.lang.Object";
- public static final QName RESERVED_QNAME = new QName("urn:ECLIPSELINK_RESERVEDURI", "RESERVEDNAME");
-
- String outputDir = ".";
- private HashMap<String, QName> userDefinedSchemaTypes;
- private Helper helper;
- private JavaClass jotArrayList;
- private JavaClass jotHashSet;
- private JavaClass jotHashMap;
- private JavaClass jotLinkedList;
- private JavaClass jotTreeSet;
- private HashMap<String, PackageInfo> packageToPackageInfoMappings;
- private HashMap<String, TypeInfo> typeInfo;
- private HashMap<QName, Class> qNamesToGeneratedClasses;
- private HashMap<String, Class> classToGeneratedClasses;
- private HashMap<QName, Class> qNamesToDeclaredClasses;
- private HashMap<QName, ElementDeclaration> globalElements;
- private List<ElementDeclaration> localElements;
- private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses;
- private Map<MapEntryGeneratedKey, Class> generatedMapEntryClasses;
+ public static final QName RESERVED_QNAME = new QName("urn:ECLIPSELINK_RESERVEDURI", "RESERVEDNAME");
+
+ String outputDir = ".";
+ private Map<String, QName> userDefinedSchemaTypes;
+ private Helper helper;
+ private JavaClass jotArrayList;
+ private JavaClass jotHashSet;
+ private JavaClass jotHashMap;
+ private JavaClass jotLinkedList;
+ private JavaClass jotTreeSet;
+ private Map<String, PackageInfo> packageToPackageInfoMappings;
+ private Map<String, TypeInfo> typeInfo;
+ private Map<QName, Class> qNamesToGeneratedClasses;
+ private Map<String, Class> classToGeneratedClasses;
+ private Map<QName, Class> qNamesToDeclaredClasses;
+ private Map<QName, ElementDeclaration> globalElements;
+ private List<ElementDeclaration> localElements;
+ private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses;
+ private Map<MapEntryGeneratedKey, Class> generatedMapEntryClasses;
private CoreProject project;
private NamespaceResolver globalNamespaceResolver;
private boolean isDefaultNamespaceAllowed;
@@ -214,13 +214,13 @@ public class MappingsGenerator {
qNamesToDeclaredClasses = new HashMap<QName, Class>();
classToGeneratedClasses = new HashMap<String, Class>();
globalNamespaceResolver = new org.eclipse.persistence.oxm.NamespaceResolver();
- isDefaultNamespaceAllowed = true;
- }
-
- public CoreProject generateProject(ArrayList<JavaClass> typeInfoClasses, HashMap<String, TypeInfo> typeInfo, HashMap<String, QName> userDefinedSchemaTypes, HashMap<String, PackageInfo> packageToPackageInfoMappings, HashMap<QName, ElementDeclaration> globalElements, List<ElementDeclaration> localElements, Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClass, Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses, boolean isDefaultNamespaceAllowed) throws Exception {
- this.typeInfo = typeInfo;
- this.userDefinedSchemaTypes = userDefinedSchemaTypes;
- this.packageToPackageInfoMappings = packageToPackageInfoMappings;
+ isDefaultNamespaceAllowed = true;
+ }
+
+ public CoreProject generateProject(List<JavaClass> typeInfoClasses, Map<String, TypeInfo> typeInfo, Map<String, QName> userDefinedSchemaTypes, Map<String, PackageInfo> packageToPackageInfoMappings, Map<QName, ElementDeclaration> globalElements, List<ElementDeclaration> localElements, Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClass, Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses, boolean isDefaultNamespaceAllowed) throws Exception {
+ this.typeInfo = typeInfo;
+ this.userDefinedSchemaTypes = userDefinedSchemaTypes;
+ this.packageToPackageInfoMappings = packageToPackageInfoMappings;
this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed;
this.globalElements = globalElements;
this.localElements = localElements;
@@ -1915,13 +1915,13 @@ public class MappingsGenerator {
/**
* Compares a JavaModel JavaClass to a Class. Equality is based on
* the raw name of the JavaClass compared to the canonical
- * name of the Class.
- *
- * @param src
- * @param tgt
- * @return
- */
- protected boolean areEquals(JavaClass src, String tgtCanonicalName) {
+ * name of the Class.
+ *
+ * @param src
+ * @param tgtCanonicalName
+ * @return
+ */
+ protected boolean areEquals(JavaClass src, String tgtCanonicalName) {
if (src == null || tgtCanonicalName == null) {
return false;
}
@@ -3230,20 +3230,20 @@ public class MappingsGenerator {
//byte[] classBytes = new byte[]{};
Class generatedClass = getJaxbClassLoader().generateClass(className, classBytes);
- return generatedClass;
- }
-
- public HashMap<QName, Class> getQNamesToGeneratedClasses() {
- return qNamesToGeneratedClasses;
- }
-
- public HashMap<String, Class> getClassToGeneratedClasses() {
- return classToGeneratedClasses;
- }
- public HashMap<QName, Class> getQNamesToDeclaredClasses() {
- return qNamesToDeclaredClasses;
- }
-
+ return generatedClass;
+ }
+
+ public Map<QName, Class> getQNamesToGeneratedClasses() {
+ return qNamesToGeneratedClasses;
+ }
+
+ public Map<String, Class> getClassToGeneratedClasses() {
+ return classToGeneratedClasses;
+ }
+ public Map<QName, Class> getQNamesToDeclaredClasses() {
+ return qNamesToDeclaredClasses;
+ }
+
private Map<MapEntryGeneratedKey, Class> getGeneratedMapEntryClasses() {
if(generatedMapEntryClasses == null){
generatedMapEntryClasses = new HashMap<MapEntryGeneratedKey, Class>();
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Property.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Property.java
index eaff553..9afa0f9 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Property.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/Property.java
@@ -24,12 +24,13 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
-import javax.xml.namespace.QName;
-
-import org.eclipse.persistence.jaxb.javamodel.reflection.JavaClassImpl;
-import org.eclipse.persistence.internal.oxm.mappings.Field;
-import org.eclipse.persistence.internal.oxm.XPathFragment;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+import javax.xml.namespace.QName;
+
+import org.eclipse.persistence.jaxb.compiler.facets.Facet;
+import org.eclipse.persistence.jaxb.javamodel.reflection.JavaClassImpl;
+import org.eclipse.persistence.internal.oxm.mappings.Field;
+import org.eclipse.persistence.internal.oxm.XPathFragment;
import org.eclipse.persistence.jaxb.javamodel.Helper;
import org.eclipse.persistence.jaxb.javamodel.JavaClass;
import org.eclipse.persistence.jaxb.javamodel.JavaHasAnnotations;
@@ -75,13 +76,14 @@ public class Property implements Cloneable {
private JavaClass genericType;
private boolean isAttribute = false;
private boolean isAnyAttribute = false;
- private boolean isAnyElement = false;
- private Helper helper;
- private Map<Object, Object> userProperties;
-
- //Original get and set methods for this property
- //Used to keep track of overrides
- private String originalGetMethodName;
+ private boolean isAnyElement = false;
+ private Helper helper;
+ private Map<Object, Object> userProperties;
+ private List<Facet> facets = new ArrayList<Facet>();
+
+ //Original get and set methods for this property
+ //Used to keep track of overrides
+ private String originalGetMethodName;
private String originalSetMethodName;
private String getMethodName;
@@ -119,14 +121,12 @@ public class Property implements Cloneable {
// XmlAnyElement specific attributes
private boolean lax;
private String domHandlerClassName;
- private String variableAttributeName;
- private String variableClassName;
- private boolean variableNodeAttribute;
-
-
-
- // XmlMap specific attributes
- private JavaClass keyType;
+ private String variableAttributeName;
+ private String variableClassName;
+ private boolean variableNodeAttribute;
+
+ // XmlMap specific attributes
+ private JavaClass keyType;
private JavaClass valueType;
public static final String DEFAULT_KEY_NAME = "key";
public static final String DEFAULT_VALUE_NAME = "value";
@@ -152,14 +152,17 @@ public class Property implements Cloneable {
private static final String MARSHAL_METHOD_NAME = "marshal";
private static JavaClass XML_ADAPTER_CLASS;
- private static JavaClass OBJECT_CLASS;
-
- private boolean isTyped;
-
-
- public Property() {}
-
- public Property(Helper helper) {
+ private static JavaClass OBJECT_CLASS;
+
+ private boolean isTyped;
+ private Integer minOccurs;
+ private Integer maxOccurs;
+ private boolean notNullAnnotated;
+
+
+ public Property() {}
+
+ public Property(Helper helper) {
this.helper = helper;
// let's init static fields
@@ -1487,8 +1490,38 @@ public class Property implements Cloneable {
}
public void setTyped(boolean isTyped) {
- this.isTyped = isTyped;
- }
-
-
-}
+ this.isTyped = isTyped;
+ }
+
+ public List<Facet> getFacets() {
+ return facets;
+ }
+
+ public void addFacet(Facet facet) {
+ facets.add(facet);
+ }
+
+ public void setMinOccurs(int minOccurs) {
+ this.minOccurs = minOccurs;
+ }
+
+ public Integer getMinOccurs() {
+ return minOccurs;
+ }
+
+ public void setMaxOccurs(int maxOccurs) {
+ this.maxOccurs = maxOccurs;
+ }
+
+ public Integer getMaxOccurs() {
+ return maxOccurs;
+ }
+
+ public void setNotNullAnnotated(boolean notNullAnnotated) {
+ this.notNullAnnotated = notNullAnnotated;
+ }
+
+ public boolean isNotNullAnnotated() {
+ return notNullAnnotated;
+ }
+} \ No newline at end of file
diff --git a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/SchemaGenerator.java b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/SchemaGenerator.java
index e62a757..8cc5a70 100644
--- a/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/SchemaGenerator.java
+++ b/moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/compiler/SchemaGenerator.java
@@ -3,9 +3,9 @@
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
- * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
- * and the Eclipse Distribution License is available at
- * http://www.eclipse.org/org/documents/edl-v10.php.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
@@ -18,22 +18,26 @@ import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.xml.bind.SchemaOutputResolver;
-import javax.xml.bind.annotation.XmlElementDecl.GLOBAL;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.xml.bind.SchemaOutputResolver;
+import javax.xml.bind.annotation.XmlElementDecl.GLOBAL;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.namespace.QName;
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-
-import org.eclipse.persistence.exceptions.JAXBException;
-import org.eclipse.persistence.internal.core.helper.CoreClassConstants;
-import org.eclipse.persistence.internal.jaxb.many.MapValue;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+
+import org.eclipse.persistence.exceptions.BeanValidationException;
+import org.eclipse.persistence.exceptions.JAXBException;
+import org.eclipse.persistence.internal.core.helper.CoreClassConstants;
+import org.eclipse.persistence.internal.jaxb.many.MapValue;
import org.eclipse.persistence.internal.oxm.Constants;
import org.eclipse.persistence.internal.oxm.Namespace;
import org.eclipse.persistence.internal.oxm.XPathFragment;
@@ -45,23 +49,32 @@ import org.eclipse.persistence.internal.oxm.schema.model.Attribute;
import org.eclipse.persistence.internal.oxm.schema.model.Choice;
import org.eclipse.persistence.internal.oxm.schema.model.ComplexContent;
import org.eclipse.persistence.internal.oxm.schema.model.ComplexType;
-import org.eclipse.persistence.internal.oxm.schema.model.Element;
-import org.eclipse.persistence.internal.oxm.schema.model.Extension;
-import org.eclipse.persistence.internal.oxm.schema.model.Import;
-import org.eclipse.persistence.internal.oxm.schema.model.List;
-import org.eclipse.persistence.internal.oxm.schema.model.Occurs;
-import org.eclipse.persistence.internal.oxm.schema.model.Restriction;
-import org.eclipse.persistence.internal.oxm.schema.model.Schema;
+import org.eclipse.persistence.internal.oxm.schema.model.Element;
+import org.eclipse.persistence.internal.oxm.schema.model.Extension;
+import org.eclipse.persistence.internal.oxm.schema.model.Import;
+import org.eclipse.persistence.internal.oxm.schema.model.Occurs;
+import org.eclipse.persistence.internal.oxm.schema.model.Restriction;
+import org.eclipse.persistence.internal.oxm.schema.model.Schema;
import org.eclipse.persistence.internal.oxm.schema.model.Sequence;
import org.eclipse.persistence.internal.oxm.schema.model.SimpleComponent;
import org.eclipse.persistence.internal.oxm.schema.model.SimpleContent;
import org.eclipse.persistence.internal.oxm.schema.model.SimpleType;
-import org.eclipse.persistence.internal.oxm.schema.model.TypeDefParticle;
-import org.eclipse.persistence.internal.oxm.schema.model.TypeDefParticleOwner;
-import org.eclipse.persistence.internal.sessions.AbstractSession;
-import org.eclipse.persistence.jaxb.javamodel.Helper;
-import org.eclipse.persistence.jaxb.javamodel.JavaClass;
-import org.eclipse.persistence.jaxb.javamodel.JavaMethod;
+import org.eclipse.persistence.internal.oxm.schema.model.TypeDefParticle;
+import org.eclipse.persistence.internal.oxm.schema.model.TypeDefParticleOwner;
+import org.eclipse.persistence.internal.sessions.AbstractSession;
+import org.eclipse.persistence.jaxb.compiler.facets.DecimalMaxFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.DecimalMinFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.DigitsFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.Facet;
+import org.eclipse.persistence.jaxb.compiler.facets.FacetVisitor;
+import org.eclipse.persistence.jaxb.compiler.facets.MaxFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.MinFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.PatternFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.PatternListFacet;
+import org.eclipse.persistence.jaxb.compiler.facets.SizeFacet;
+import org.eclipse.persistence.jaxb.javamodel.Helper;
+import org.eclipse.persistence.jaxb.javamodel.JavaClass;
+import org.eclipse.persistence.jaxb.javamodel.JavaMethod;
import org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper;
import org.eclipse.persistence.jaxb.xmlmodel.XmlVirtualAccessMethodsSchema;
import org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode;
@@ -69,13 +82,13 @@ import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransform
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLField;
import org.eclipse.persistence.sessions.Session;
-
-/**
- * INTERNAL:
- * <p><b>Purpose:</b>To generate Schema objects based on a map of TypeInfo objects, and some
- * additional information gathered by the AnnotationsProcessing phase.
- * <p><b>Responsibilities:</b><ul>
- * <li>Create and maintain a collection of Schema objects based on the provided TypeInfo objects</li>
+
+/**
+ * INTERNAL:
+ * <p><b>Purpose:</b>To generate Schema objects based on a map of TypeInfo objects, and some
+ * additional information gathered by the AnnotationsProcessing phase.
+ * <p><b>Responsibilities:</b><ul>
+ * <li>Create and maintain a collection of Schema objects based on the provided TypeInfo objects</li>
* <li>Add additional global elements to the schema based on an optional map (for WS integration)</li>
* <li>Should create a schema for each namespace encountered during generation.</li>
* </ul>
@@ -86,25 +99,24 @@ import org.eclipse.persistence.sessions.Session;
* @see org.eclipse.persistence.jaxb.compiler.AnnotationsProcessor
* @see org.eclipse.persistence.jaxb.compiler.Generator
* @since Oracle TopLink 11.1.1.0.0
- * @author mmacivor
- */
-public class SchemaGenerator {
- private HashMap<String, Schema> schemaForNamespace;
- private java.util.List<Schema> allSchemas;
- private Schema schema;
- private int schemaCount;
- private Helper helper;
- private HashMap<String, TypeInfo> typeInfo;
- private HashMap<String, PackageInfo> packageToPackageInfoMappings;
- private HashMap<String, SchemaTypeInfo> schemaTypeInfo;
- private HashMap<String, QName> userDefinedSchemaTypes;
- private Map<String, Class> arrayClassesToGeneratedClasses;
-
- private static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler";
- private static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart";
- private static final String SWA_REF_IMPORT = "http://ws-i.org/profiles/basic/1.1/swaref.xsd";
- private static final String BUILD_FIELD_VALUE_METHOD = "buildFieldValue";
-
+ * @author mmacivor
+ */
+public class SchemaGenerator {
+ private Map<String, Schema> schemaForNamespace;
+ private List<Schema> allSchemas;
+ private int schemaCount;
+ private Helper helper;
+ private Map<String, TypeInfo> typeInfo;
+ private Map<String, PackageInfo> packageToPackageInfoMappings;
+ private Map<String, SchemaTypeInfo> schemaTypeInfo;
+ private Map<String, QName> userDefinedSchemaTypes;
+ private Map<String, Class> arrayClassesToGeneratedClasses;
+
+ private static final String JAVAX_ACTIVATION_DATAHANDLER = "javax.activation.DataHandler";
+ private static final String JAVAX_MAIL_INTERNET_MIMEMULTIPART = "javax.mail.internet.MimeMultipart";
+ private static final String SWA_REF_IMPORT = "http://ws-i.org/profiles/basic/1.1/swaref.xsd";
+ private static final String BUILD_FIELD_VALUE_METHOD = "buildFieldValue";
+
private static final String COLON = ":";
private static final String ATT = "@";
private static final String EMPTY_STRING = "";
@@ -119,23 +131,25 @@ public class SchemaGenerator {
private static final String IDREF = "IDREF";
private static final Character DOT_CHAR = '.';
private static final Character SLASH = '/';
- private static final Character SLASHES = '\\';
-
- private SchemaOutputResolver outputResolver;
-
- public SchemaGenerator(Helper helper) {
- this.helper = helper;
- }
-
- public Schema generateSchema(ArrayList<JavaClass> typeInfoClasses, HashMap<String, TypeInfo> typeInfo, HashMap<String, QName> userDefinedSchemaTypes, HashMap<String, PackageInfo> packageToPackageInfoMappings, HashMap<QName, ElementDeclaration> additionalGlobalElements, Map<String, Class> arrayClassesToGeneratedClasses, SchemaOutputResolver outputResolver) {
- this.outputResolver = outputResolver;
- return generateSchema(typeInfoClasses, typeInfo, userDefinedSchemaTypes, packageToPackageInfoMappings, additionalGlobalElements, arrayClassesToGeneratedClasses);
- }
-
- public Schema generateSchema(ArrayList<JavaClass> typeInfoClasses, HashMap<String, TypeInfo> typeInfo, HashMap<String, QName> userDefinedSchemaTypes, HashMap<String, PackageInfo> packageToPackageInfoMappings, HashMap<QName, ElementDeclaration> additionalGlobalElements, Map<String, Class> arrayClassesToGeneratedClasses) {
- this.typeInfo = typeInfo;
- this.userDefinedSchemaTypes = userDefinedSchemaTypes;
- this.packageToPackageInfoMappings = packageToPackageInfoMappings;
+ private static final Character SLASHES = '\\';
+
+ private SchemaOutputResolver outputResolver;
+ private boolean facets;
+
+ public SchemaGenerator(Helper helper) {
+ this.helper = helper;
+ this.facets = helper.isFacets();
+ }
+
+ public void generateSchema(List<JavaClass> typeInfoClasses, Map<String, TypeInfo> typeInfo, Map<String, QName> userDefinedSchemaTypes, Map<String, PackageInfo> packageToPackageInfoMappings, Map<QName, ElementDeclaration> additionalGlobalElements, Map<String, Class> arrayClassesToGeneratedClasses, SchemaOutputResolver outputResolver) {
+ this.outputResolver = outputResolver;
+ generateSchema(typeInfoClasses, typeInfo, userDefinedSchemaTypes, packageToPackageInfoMappings, additionalGlobalElements, arrayClassesToGeneratedClasses);
+ }
+
+ public void generateSchema(List<JavaClass> typeInfoClasses, Map<String, TypeInfo> typeInfo, Map<String, QName> userDefinedSchemaTypes, Map<String, PackageInfo> packageToPackageInfoMappings, Map<QName, ElementDeclaration> additionalGlobalElements, Map<String, Class> arrayClassesToGeneratedClasses) {
+ this.typeInfo = typeInfo;
+ this.userDefinedSchemaTypes = userDefinedSchemaTypes;
+ this.packageToPackageInfoMappings = packageToPackageInfoMappings;
this.schemaCount = 1;
this.schemaTypeInfo = new HashMap<String, SchemaTypeInfo>(typeInfo.size());
this.arrayClassesToGeneratedClasses = arrayClassesToGeneratedClasses;
@@ -144,20 +158,19 @@ public class SchemaGenerator {
addSchemaComponents(javaClass);
}
populateSchemaTypes();
- if (additionalGlobalElements != null) {
- addGlobalElements(additionalGlobalElements);
- }
- return schema;
- }
-
- public void addSchemaComponents(JavaClass myClass) {
- // first check for type
- String myClassName = myClass.getQualifiedName();
- Element rootElement = null;
- TypeInfo info = (TypeInfo) typeInfo.get(myClassName);
- if (info.isTransient() || info.getClassNamespace().equals(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
- return;
- }
+ if (additionalGlobalElements != null) {
+ addGlobalElements(additionalGlobalElements);
+ }
+ }
+
+ public void addSchemaComponents(JavaClass myClass) {
+ // first check for type
+ String myClassName = myClass.getQualifiedName();
+ Element rootElement = null;
+ TypeInfo info = typeInfo.get(myClassName);
+ if (info.isTransient() || info.getClassNamespace().equals(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
+ return;
+ }
SchemaTypeInfo schemaTypeInfo = new SchemaTypeInfo();
schemaTypeInfo.setSchemaTypeName(new QName(info.getClassNamespace(), info.getSchemaTypeName()));
this.schemaTypeInfo.put(myClass.getQualifiedName(), schemaTypeInfo);
@@ -175,17 +188,17 @@ public class SchemaGenerator {
if (info.isSetXmlRootElement()) {
//Create the root element and add it to the schema
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement xmlRE = info.getXmlRootElement();
- rootElement = new Element();
- String elementName = xmlRE.getName();
- if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) {
- try{
- elementName = info.getXmlNameTransformer().transformRootElementName(myClassName);
- }catch (Exception ex){
- throw org.eclipse.persistence.exceptions.JAXBException.exceptionDuringNameTransformation(myClassName, info.getXmlNameTransformer().getClass().getName(), ex);
- }
- }
- rootElement.setName(elementName);
- String rootNamespace = xmlRE.getNamespace();
+ rootElement = new Element();
+ String elementName = xmlRE.getName();
+ if (elementName.equals(XMLProcessor.DEFAULT) || elementName.equals(EMPTY_STRING)) {
+ try{
+ elementName = info.getXmlNameTransformer().transformRootElementName(myClassName);
+ }catch (Exception ex){
+ throw org.eclipse.persistence.exceptions.JAXBException.exceptionDuringNameTransformation(myClassName, info.getXmlNameTransformer().getClass().getName(), ex);
+ }
+ }
+ rootElement.setName(elementName);
+ String rootNamespace = xmlRE.getNamespace();
if (rootNamespace.equals(XMLProcessor.DEFAULT)) {
Schema rootElementSchema = getSchemaForNamespace(namespaceInfo.getNamespace());
if (rootElementSchema != null) {
@@ -198,66 +211,66 @@ public class SchemaGenerator {
if (rootElementSchema != null) {
rootElementSchema.addTopLevelElement(rootElement);
}
- schemaTypeInfo.getGlobalElementDeclarations().add(new QName(rootNamespace, elementName));
- }
-
- // handle root-level imports/includes [schema = the type's schema]
- Schema rootSchema = getSchemaForNamespace(rootNamespace);
- addImportIfRequired(rootSchema, schema, schema.getTargetNamespace());
-
+ schemaTypeInfo.getGlobalElementDeclarations().add(new QName(rootNamespace, elementName));
+ }
+
+ // handle root-level imports/includes [schema = the type's schema]
+ Schema rootSchema = getSchemaForNamespace(rootNamespace);
+ addImportIfRequired(rootSchema, schema, schema.getTargetNamespace());
+
// setup a prefix, if necessary
if (rootSchema != null && !info.getClassNamespace().equals(EMPTY_STRING)) {
pfx = getOrGeneratePrefixForNamespace(info.getClassNamespace(), rootSchema);
pfx += COLON;
- }
- }
-
-
-
- if (CompilerHelper.isSimpleType(info)){
-
- SimpleType type = new SimpleType();
- //simple type case, we just need the name and namespace info
- if (typeName.equals(EMPTY_STRING)) {
+ }
+ }
+
+
+
+ if (CompilerHelper.isSimpleType(info)){
+
+ SimpleType type = new SimpleType();
+ //simple type case, we just need the name and namespace info
+ if (typeName.equals(EMPTY_STRING)) {
//In this case, it should be a type under
//A root elem or locally defined whenever used
- if (rootElement != null) {
- rootElement.setSimpleType(type);
- }
- } else {
- type.setName(typeName);
- schema.addTopLevelSimpleTypes(type);
- if (rootElement != null) {
+ if (rootElement != null) {
+ rootElement.setSimpleType(type);
+ }
+ } else {
+ type.setName(typeName);
+ schema.addTopLevelSimpleTypes(type);
+ if (rootElement != null) {
rootElement.setType(pfx + type.getName());
}
}
//Figure out schema type and set it as Restriction
QName restrictionType = null;
Restriction restriction = new Restriction();
- if (info.isEnumerationType()) {
- restrictionType = ((EnumTypeInfo) info).getRestrictionBase();
- restriction.setEnumerationFacets(this.getEnumerationFacetsFor((EnumTypeInfo) info));
-
- String prefix = null;
- if (restrictionType.getNamespaceURI() != null && !restrictionType.getNamespaceURI().equals(EMPTY_STRING)) {
- if (restrictionType.getNamespaceURI().equals(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
- prefix = Constants.SCHEMA_PREFIX;
- } else {
- prefix = getPrefixForNamespace(schema, restrictionType.getNamespaceURI());
+ if (info.isEnumerationType()) {
+ restrictionType = ((EnumTypeInfo) info).getRestrictionBase();
+ restriction.setEnumerationFacets(this.getEnumerationFacetsFor((EnumTypeInfo) info));
+
+ String prefix = null;
+ if (restrictionType.getNamespaceURI() != null && !EMPTY_STRING.equals(restrictionType.getNamespaceURI())) {
+ if (javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(restrictionType.getNamespaceURI())) {
+ prefix = Constants.SCHEMA_PREFIX;
+ } else {
+ prefix = getPrefixForNamespace(schema, restrictionType.getNamespaceURI());
}
}
- String extensionTypeName = restrictionType.getLocalPart();
- if (prefix != null) {
- extensionTypeName = prefix + COLON + extensionTypeName;
- }
- restriction.setBaseType(extensionTypeName);
-
- type.setRestriction(restriction);
- } else {
- valueField= info.getXmlValueProperty();
- JavaClass javaType = valueField.getActualType();
- QName baseType = getSchemaTypeFor(javaType);
- String prefix = null;
+ String extensionTypeName = restrictionType.getLocalPart();
+ if (prefix != null) {
+ extensionTypeName = prefix + COLON + extensionTypeName;
+ }
+ restriction.setBaseType(extensionTypeName);
+
+ type.setRestriction(restriction);
+ } else {
+ valueField= info.getXmlValueProperty();
+ JavaClass javaType = valueField.getActualType();
+ QName baseType = getSchemaTypeFor(javaType);
+ String prefix = null;
if (baseType.getNamespaceURI() != null && !baseType.getNamespaceURI().equals(EMPTY_STRING)) {
if (baseType.getNamespaceURI().equals(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
prefix = Constants.SCHEMA_PREFIX;
@@ -268,29 +281,29 @@ public class SchemaGenerator {
String baseTypeName = baseType.getLocalPart();
if (prefix != null) {
baseTypeName = prefix + COLON + baseTypeName;
- }
- if (valueField.isXmlList() || (valueField.getGenericType() != null)) {
- //generate a list instead of a restriction
- List list = new List();
- list.setItemType(baseTypeName);
- type.setList(list);
- } else {
- if (helper.isAnnotationPresent(valueField.getElement(), XmlSchemaType.class)) {
- XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(valueField.getElement(), XmlSchemaType.class);
- baseType = new QName(schemaType.namespace(), schemaType.name());
- }
- restriction.setBaseType(baseTypeName);
- type.setRestriction(restriction);
+ }
+ if (valueField.isXmlList() || (valueField.getGenericType() != null)) {
+ //generate a list instead of a restriction
+ org.eclipse.persistence.internal.oxm.schema.model.List list = new org.eclipse.persistence.internal.oxm.schema.model.List();
+ list.setItemType(baseTypeName);
+ type.setList(list);
+ } else {
+ if (helper.isAnnotationPresent(valueField.getElement(), XmlSchemaType.class)) {
+ XmlSchemaType schemaType = (XmlSchemaType) helper.getAnnotation(valueField.getElement(), XmlSchemaType.class);
+ baseType = new QName(schemaType.namespace(), schemaType.name()); // TODO: This assignment seems like a bug, probably this should be "baseTypeName" ?
+ }
+ restriction.setBaseType(baseTypeName);
+ type.setRestriction(restriction);
}
}
info.setSimpleType(type);
- } else if ((valueField = this.getXmlValueFieldForSimpleContent(info)) != null) {
- ComplexType type = new ComplexType();
- SimpleContent content = new SimpleContent();
- if (typeName.equals(EMPTY_STRING)) {
- if (rootElement != null) {
- rootElement.setComplexType(type);
- }
+ } else if ((valueField = this.getXmlValueFieldForSimpleContent(info)) != null) {
+ ComplexType type = new ComplexType();
+ SimpleContent content = new SimpleContent();
+ if (EMPTY_STRING.equals(typeName)) {
+ if (rootElement != null) {
+ rootElement.setComplexType(type);
+ }
info.setComplexType(type);
} else {
type.setName(typeName);
@@ -326,13 +339,13 @@ public class SchemaGenerator {
TypeDefParticle compositor = null;
if(type.getComplexContent() != null && type.getComplexContent().getExtension() != null) {
compositor = type.getComplexContent().getExtension().getTypeDefParticle();
- } else {
- compositor = type.getTypeDefParticle();
- }
- if (typeName.equals(EMPTY_STRING)) {
- if (rootElement != null) {
- rootElement.setComplexType(type);
- }
+ } else {
+ compositor = type.getTypeDefParticle();
+ }
+ if (EMPTY_STRING.equals(typeName)) {
+ if (rootElement != null) {
+ rootElement.setComplexType(type);
+ }
info.setComplexType(type);
info.setCompositor(compositor);
} else {
@@ -347,13 +360,13 @@ public class SchemaGenerator {
}
}
- private ComplexType createComplexTypeForClass(JavaClass myClass, TypeInfo info) {
-
- Schema schema = getSchemaForNamespace(info.getClassNamespace());
-
- ComplexType type = new ComplexType();
- JavaClass superClass = CompilerHelper.getNextMappedSuperClass(myClass, this.typeInfo, this.helper);
- // Handle abstract class
+ private ComplexType createComplexTypeForClass(JavaClass myClass, TypeInfo info) {
+
+ Schema schema = getSchemaForNamespace(info.getClassNamespace());
+
+ ComplexType type = new ComplexType();
+ JavaClass superClass = CompilerHelper.getNextMappedSuperClass(myClass, this.typeInfo, this.helper);
+ // Handle abstract class
if (myClass.isAbstract()) {
type.setAbstractValue(true);
}
@@ -367,36 +380,36 @@ public class SchemaGenerator {
String parentPrefix = getPrefixForNamespace(schema, parentTypeInfo.getClassNamespace());
if (parentPrefix != null) {
extension.setBaseType(parentPrefix + COLON + parentTypeInfo.getSchemaTypeName());
- } else {
- extension.setBaseType(parentTypeInfo.getSchemaTypeName());
- }
-
- if(CompilerHelper.isSimpleType(parentTypeInfo)){
- SimpleContent content = new SimpleContent();
- content.setExtension(extension);
- type.setSimpleContent(content);
- return type;
- }else{
- ComplexContent content = new ComplexContent();
- content.setExtension(extension);
- type.setComplexContent(content);
- }
-
- }
- }
-
- TypeDefParticle compositor = null;
- String[] propOrder = null;
- if (info.isSetPropOrder()) {
- propOrder = info.getPropOrder();
- }
-
- if (propOrder != null && propOrder.length == 0) {
- // Note that the spec requires an 'all' to be generated
- // in cases where propOrder == 0, however, the TCK
- // requires the extension case to use sequences
- if (info.hasElementRefs()) {
- // generate a sequence to satisfy TCK
+ } else {
+ extension.setBaseType(parentTypeInfo.getSchemaTypeName());
+ }
+
+ if(CompilerHelper.isSimpleType(parentTypeInfo)){
+ SimpleContent content = new SimpleContent();
+ content.setExtension(extension);
+ type.setSimpleContent(content);
+ return type;
+ }else{
+ ComplexContent content = new ComplexContent();
+ content.setExtension(extension);
+ type.setComplexContent(content);
+ }
+
+ }
+ }
+
+ TypeDefParticle compositor = null;
+ String[] propOrder = null;
+ if (info.isSetPropOrder()) {
+ propOrder = info.getPropOrder();
+ }
+
+ if (propOrder != null && propOrder.length == 0) {
+ // Note that the spec requires an 'all' to be generated
+ // in cases where propOrder == 0, however, the TCK
+ // requires the extension case to use sequences
+ if (info.hasElementRefs()) {
+ // generate a sequence to satisfy TCK
compositor = new Sequence();
if (extension != null) {
extension.setSequence((Sequence) compositor);
@@ -421,30 +434,30 @@ public class SchemaGenerator {
}
return type;
}
- public void addToSchemaType(TypeInfo ownerTypeInfo, java.util.List<Property> properties, TypeDefParticle compositor, ComplexType type, Schema workingSchema) {
- //If there are no properties we don't want a sequence/choice or all tag written out
- if (properties.size() == 0) {
- type.setAll(null);
- type.setSequence(null);
- type.setChoice(null);
- ownerTypeInfo.setCompositor(null);
- return;
- }
-
- boolean extAnyAdded = false;
+ public void addToSchemaType(TypeInfo ownerTypeInfo, java.util.List<Property> properties, TypeDefParticle compositor, ComplexType type, Schema workingSchema) {
+ //If there are no properties we don't want a sequence/choice or all tag written out
+ if (properties.size() == 0) {
+ type.setAll(null);
+ type.setSequence(null);
+ type.setChoice(null);
+ ownerTypeInfo.setCompositor(null);
+ return;
+ }
+
+ boolean extAnyAdded = false;
// generate schema components for each property
for (Property next : properties) {
if (next == null) { continue; }
Schema currentSchema = workingSchema;
- TypeDefParticle parentCompositor = compositor;
- boolean isChoice = (parentCompositor instanceof Choice);
- ComplexType parentType = type;
- // ignore transient and inverse reference/non-writeable properties
- if(!next.isTransient() && !(next.isInverseReference() && !next.isWriteableInverseReference())){
- // handle xml extensions
- if (next.isVirtual()) {
- boolean extSchemaAny = false;
+ TypeDefParticle parentCompositor = compositor;
+ boolean isChoice = (parentCompositor instanceof Choice);
+ ComplexType parentType = type;
+ // ignore transient and inverse reference/non-writeable properties
+ if(!next.isTransient() && !(next.isInverseReference() && !next.isWriteableInverseReference())){
+ // handle xml extensions
+ if (next.isVirtual()) {
+ boolean extSchemaAny = false;
if (ownerTypeInfo.getXmlVirtualAccessMethods().getSchema() != null) {
extSchemaAny = ownerTypeInfo.getXmlVirtualAccessMethods().getSchema().equals(XmlVirtualAccessMethodsSchema.ANY);
}
@@ -474,13 +487,13 @@ public class SchemaGenerator {
// deal with xml-path case
if (next.getXmlPath() != null) {
// create schema components based on the XmlPath
- AddToSchemaResult xpr = addXPathToSchema(next, parentCompositor, currentSchema, isChoice, type);
- // if the returned object or schema component is null there is nothing to do
- if (xpr == null || ((parentCompositor = xpr.particle) == null && xpr.simpleContentType == null)) {