From 8e180c232dd261c587554734d5416e5c3d0b161f Mon Sep 17 00:00:00 2001 From: Dmitry Katsubo Date: Fri, 24 Feb 2012 16:55:58 +0100 Subject: [PATCH] Commit of initial code by Bjarne Hansen. --- .gitignore | 3 + .settings/org.eclipse.jdt.core.prefs | 5 + .settings/org.eclipse.jdt.ui.prefs | 4 + LICENSE.txt | 165 +++++ README.md | 192 +++++ eclipse-code-fomatting-rules.xml | 291 ++++++++ pom.xml | 86 +++ samples/sample1/pom.xml | 50 ++ .../main/java/generated/ObjectFactory.java | 40 ++ .../src/main/java/generated/Order.java | 55 ++ samples/sample1/xsd/sample.xsd | 22 + .../addon/xew/XmlElementWrapperPlugin.java | 679 ++++++++++++++++++ 12 files changed, 1592 insertions(+) create mode 100644 .gitignore create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.jdt.ui.prefs create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 eclipse-code-fomatting-rules.xml create mode 100644 pom.xml create mode 100644 samples/sample1/pom.xml create mode 100644 samples/sample1/src/main/java/generated/ObjectFactory.java create mode 100644 samples/sample1/src/main/java/generated/Order.java create mode 100644 samples/sample1/xsd/sample.xsd create mode 100644 src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..be0d0ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +/.project +/.classpath diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..5e976d1 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +#Fri Feb 24 15:47:34 CET 2012 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..2eafcd0 --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,4 @@ +#Fri Feb 24 15:46:49 CET 2012 +eclipse.preferences.version=1 +formatter_profile=_Eclipse (Common) +formatter_settings_version=12 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..65c5ca8 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c1c2234 --- /dev/null +++ b/README.md @@ -0,0 +1,192 @@ +# JAXB @XmlElementWrapper Plugin + +## Description + +This JAXB plugin utilizes the power of `@XmlElementWrapper` annotation. Originally `xjc` trends to create wrapper classes which are the containers for collections. This plugin goes through all properties to find ones which can be represented in the model in more optimal way. + +## The problem origin in details + +To illustrate the problem let's take the following XSD: + + + + + + + + + + + + + + + + + + + + + +From this XSD by default `xjc` will generate two classes: + + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { "items" }) + @XmlRootElement(name = "order") + public class Order { + + @XmlElement(required = true) + protected Items items; + + public Items getItems() { + return items; + } + + public void setItems(Items value) { + this.items = value; + } + } + +and + + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { "item" }) + @XmlRootElement(name = "items") + public class Items { + + @XmlElement(required = true) + protected List item; + + public List getItem() { + if (item == null) { + item = new ArrayList(); + } + return this.item; + } + } + +So to access a particular item one need to write a but clumsy code `order.getItems().getItems().get(itemIndex)`. The solution is to use `@XmlElementWrapper` which cures exactly this case. The result will be only one class with direct access to items: + + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { "items" }) + @XmlRootElement(name = "order") + public class Order { + + @XmlElementWrapper(name = "items", required = true) + @XmlElement(name = "item") + protected List items; + + public List getItems() { + if (items == null) { + items = new ArrayList(); + } + return items; + } + + public void setItems(List items) { + this.items = items; + } + } + +## Usage + +The plugin is used together with the `xjc` from the command line or from an Ant task or via `maven-jaxb2-plugin`. + +The following options are applicable for plugin: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptionComment
-XxewActivate the XML Element Wrapper plugin
-Xxew:include filenameSpecify a filename with candidate classes to include in the compilation.
-Xxew:exclude filenameSpecify a filename with candidate classes to exclude from the compilation.
-Xxew:summary filenameSpecify a filename to contain summary information on the compilation.
-Xxew:collection FQCNSpecify the class name of the collection type to use.
-Xxew:instantiate [lazy|early]Specify when the collection class should be instantiated.
-Xxew:deleteDelete candidate classes having been replaced during compilation.
+ +### Ant task + +To use the plugin from Ant you will need something like the following in your build file: + + + + + + + + + + + + + + + + +### Maven + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.8.1 + + + generate-sources + + generate + + + true + ${project.build.sourceDirectory} + xsd + false + false + + true + + -no-header + -Xxew + -Xxew:instantiate lazy + -Xxew:delete + + + + com.github.jaxb-xew-plugin + jaxb-xew-plugin + 1.0 + + + + + + + +You can find more examples of this plugin in `samples` directory. diff --git a/eclipse-code-fomatting-rules.xml b/eclipse-code-fomatting-rules.xml new file mode 100644 index 0000000..d00a9bb --- /dev/null +++ b/eclipse-code-fomatting-rules.xml @@ -0,0 +1,291 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6cf4bcf --- /dev/null +++ b/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + com.github.jaxb-xew-plugin + jaxb-xew-plugin + jar + 1.0-SNAPSHOT + + + org.sonatype.oss + oss-parent + 7 + + + JAXB @XmlElementWrapper Plugin + 2012 + This JAXB plugin utilizes the power of @XmlElementWrapper annotation. Originally xjc trends to create wrapper classes which are the containers for collections. This plugin goes through all properties to find ones which can be represented in the model in more optimal way. + + + https://github.com/dmak/jaxb-xew-plugin + scm:git:https://github.com/dmak/jaxb-xew-plugin.git + scm:git:https://dmak@github.com/dmak/jaxb-xew-plugin.git + + + + GitHub + https://github.com/dmak/jaxb-xew-plugin/issues + + + + + LGPLv3 License + http://www.gnu.org/licenses/lgpl-3.0.html + + + + + + Bjarne Hansen + bjarne@conspicio.dk + + developer + + + + Dmitry Katsubo + dmitry.katsubo@gmail.com + http://www.linkedin.com/in/dkatsubo + http://www.epo.org/ + + developer + + + + + + + com.sun.xml.ws + jaxws-tools + 2.2.5 + + + junit + junit + 4.8.2 + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + + diff --git a/samples/sample1/pom.xml b/samples/sample1/pom.xml new file mode 100644 index 0000000..029b1c4 --- /dev/null +++ b/samples/sample1/pom.xml @@ -0,0 +1,50 @@ + + + + 4.0.0 + + com.github.jaxb-xew-plugin + sample1 + jar + 1.0.0-SNAPSHOT + + + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.8.1 + + + generate-sources + + generate + + + true + ${project.build.sourceDirectory} + xsd + false + false + + true + + -no-header + -Xxew + -Xxew:instantiate lazy + -Xxew:delete + + + + com.github.jaxb-xew-plugin + jaxb-xew-plugin + 1.0 + + + + + + + + + diff --git a/samples/sample1/src/main/java/generated/ObjectFactory.java b/samples/sample1/src/main/java/generated/ObjectFactory.java new file mode 100644 index 0000000..2fbb042 --- /dev/null +++ b/samples/sample1/src/main/java/generated/ObjectFactory.java @@ -0,0 +1,40 @@ + +package generated; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the generated package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Order } + * + */ + public Order createOrder() { + return new Order(); + } + +} diff --git a/samples/sample1/src/main/java/generated/Order.java b/samples/sample1/src/main/java/generated/Order.java new file mode 100644 index 0000000..ee5f63e --- /dev/null +++ b/samples/sample1/src/main/java/generated/Order.java @@ -0,0 +1,55 @@ + +package generated; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element ref="{}items"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "items" +}) +@XmlRootElement(name = "order") +public class Order { + + @XmlElementWrapper(name = "items", required = true) + @XmlElement(name = "item") + protected List items; + + public List getItems() { + if (items == null) { + items = new ArrayList(); + } + return items; + } + + public void setItems(List items) { + this.items = items; + } + +} diff --git a/samples/sample1/xsd/sample.xsd b/samples/sample1/xsd/sample.xsd new file mode 100644 index 0000000..22fa351 --- /dev/null +++ b/samples/sample1/xsd/sample.xsd @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java b/src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java new file mode 100644 index 0000000..00505f7 --- /dev/null +++ b/src/main/java/com/sun/tools/xjc/addon/xew/XmlElementWrapperPlugin.java @@ -0,0 +1,679 @@ +package com.sun.tools.xjc.addon.xew; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; + +import org.xml.sax.ErrorHandler; + + + +import com.sun.codemodel.JAnnotationUse; +import com.sun.codemodel.JClass; +import com.sun.codemodel.JDefinedClass; +import com.sun.codemodel.JExpr; +import com.sun.codemodel.JFieldVar; +import com.sun.codemodel.JMethod; +import com.sun.codemodel.JMod; +import com.sun.codemodel.JPackage; +import com.sun.tools.xjc.BadCommandLineException; +import com.sun.tools.xjc.Options; +import com.sun.tools.xjc.Plugin; +import com.sun.tools.xjc.model.CClassInfo; +import com.sun.tools.xjc.model.CClassInfoParent; +import com.sun.tools.xjc.model.CElementPropertyInfo; +import com.sun.tools.xjc.model.CPropertyInfo; +import com.sun.tools.xjc.model.CTypeInfo; +import com.sun.tools.xjc.model.Model; +import com.sun.tools.xjc.outline.ClassOutline; +import com.sun.tools.xjc.outline.FieldOutline; +import com.sun.tools.xjc.outline.Outline; +import com.sun.tools.xjc.outline.PackageOutline; +import com.sun.xml.bind.v2.model.core.ClassInfo; + +public class XmlElementWrapperPlugin extends Plugin +{ + + protected Map candidates = null; + protected File includeFile = null; + protected Set include = null; + protected File excludeFile = null; + protected Set exclude = null; + protected File summaryFile = null; + protected PrintWriter summary = null; + protected boolean debugMode = false; + protected boolean verbose = false; + @SuppressWarnings("unchecked") + protected Class interfaceClass = java.util.List.class; + @SuppressWarnings("unchecked") + protected Class collectionClass = java.util.ArrayList.class; + protected Instantiation instantiation = Instantiation.EARLY; + protected boolean deleteCandidates = false; + protected String factoryClassName = "ObjectFactory"; + protected String debugClassName = "JAXBDebug"; + + public XmlElementWrapperPlugin() + { + } + + @Override + public String getOptionName() + { + return "Xxew"; + } + + @Override + public String getUsage() + { + return " -Xxew: Replace collection types with fields having the @XmlElementWrapper and @XmlElement annotations."; + } + + @Override + public void onActivated(Options opts) throws BadCommandLineException + { + debugMode = opts.debugMode; + verbose = opts.verbose; + + // If we are in debug mode, report... + writeDebug("JAXB Compilation started (onActivated):"); + writeDebug("\tbuildId :\t" + Options.getBuildID()); + writeDebug("\tdefaultPackage :\t" + opts.defaultPackage); + writeDebug("\tdefaultPackage2:\t" + opts.defaultPackage2); + writeDebug("\tquiet :\t" + opts.quiet); + writeDebug("\tdebug :\t" + opts.debugMode); + writeDebug("\ttargetDir :\t" + opts.targetDir); + writeDebug("\tverbose :\t" + opts.verbose); + writeDebug("\tGrammars :\t" + opts.getGrammars().length); + for (int i = 0; i < opts.getGrammars().length; i++) + writeDebug("\t [" + i + "]: " + opts.getGrammars()[i].getSystemId()); + } + + @Override + public int parseArgument(Options opt, String[] args, int i) throws BadCommandLineException, + IOException + { + + int recognized = 0; + String filename; + + String arg = args[i]; + writeDebug("Argument[" + i + "] = " + arg); + + if (arg.startsWith("-delete")) + { + recognized++; + deleteCandidates = true; + } + else if (arg.startsWith("-include")) + { + recognized++; + include = new HashSet(); + + if (arg.length() > 8) + { + filename = arg.substring(8).trim(); + } + else + { + filename = args[i + 1]; + recognized++; + } + includeFile = new File(filename); + readCandidates(includeFile, include); + } + else if (arg.startsWith("-exclude")) + { + recognized++; + exclude = new HashSet(); + + if (arg.length() > 8) + { + filename = arg.substring(8).trim(); + } + else + { + filename = args[i + 1]; + recognized++; + } + excludeFile = new File(filename); + readCandidates(excludeFile, exclude); + } + else if (arg.startsWith("-summary")) + { + recognized++; + if (arg.length() > 8) + { + filename = arg.substring(8).trim(); + } + else + { + filename = args[i + 1]; + recognized++; + } + + summaryFile = new File(filename); + summary = new PrintWriter(new FileOutputStream(summaryFile)); + } + else if (arg.startsWith("-collection")) + { + String ccn; + + recognized++; + if (arg.length() > 11) + { + ccn = arg.substring(11).trim(); + } + else + { + ccn = args[i + 1]; + recognized++; + } + try + { + collectionClass = Class.forName(ccn); + } + catch (ClassNotFoundException e) + { + throw new BadCommandLineException("-collection " + ccn + ": Class not found."); + } + } + else if (arg.startsWith("-instantiate")) + { + String instantiate; + recognized++; + + if (arg.length() > 12) + { + instantiate = arg.substring(12).trim().toUpperCase(); + } + else + { + instantiate = args[i + 1].trim().toUpperCase(); + recognized++; + } + instantiation = Instantiation.valueOf(instantiate); + } + else + { + //throw new BadCommandLineException("Invalid argument " + arg); + } + + + + return recognized; + } + + + @Override + public void postProcessModel(Model model, ErrorHandler errorHandler) + { + super.postProcessModel(model, errorHandler); + } + + @Override + public boolean run(Outline model, Options opt, ErrorHandler errorHandler) + { + int candidateCount = 0; + int modificationCount = 0; + int deletionCount = 0; + + JDefinedClass implementationClass; + Candidate candidate; + String fieldName; + String typeName; + Collection methodsToRemove; + + writeDebug("JAXB Process Model (run)..."); + + // Write summary information on the option for this compilation. + writeSummary(" "); + writeSummary("Compilation:"); + writeSummary("\tDate :\t-"); + writeSummary("\tVersion :\t-"); + writeSummary("\tJAXB version :\t" + Options.getBuildID()); + writeSummary("\tInclude file :\t" + (includeFile == null ? "" : includeFile)); + writeSummary("\tExclude file :\t" + (excludeFile == null ? "" : excludeFile)); + writeSummary("\tSummary file :\t" + (summaryFile == null ? "" : summaryFile)); + writeSummary("\tInstantiate :\t" + instantiation); + writeSummary("\tCollection :\t" + collectionClass); + writeSummary("\tInterface :\t" + interfaceClass); + writeSummary("\tDelete :\t" + deleteCandidates); + writeSummary(" "); + + // Find candidate classes for transformation. + // Candidates are classes having exactly one field which is a collection. + candidates = findCandidateClasses(model.getModel(), errorHandler); + + // Write information on candidate classes to summary file. + writeSummary("Candidates:"); + for (Candidate c : candidates.values()) + { + if (isIncluded(c)) + { + writeSummary("\t[+] " + getIncludeOrExcludeReason(c) + ":\t" + c.getClassName()); + candidateCount++; + } + else + writeSummary("\t[-]: " + getIncludeOrExcludeReason(c) + ":\t" + c.getClassName()); + } + writeSummary("\t" + candidateCount + " candidate(s) being considered."); + writeSummary(" "); + + // Visit all classes generated by JAXB. + writeSummary("Modifications:"); + for (ClassOutline classOutline : model.getClasses()) + { + // Get the implementation class for the current class. + implementationClass = classOutline.implClass; + + // Visit all fields in this class. + for (FieldOutline field : classOutline.getDeclaredFields()) + { + + // Extract the field name and type of the current field. + fieldName = field.getPropertyInfo().getName(false); + typeName = field.getRawType().fullName(); + + // Check to see if the current field references one of the candidate classes. + candidate = candidates.get(typeName); + + if (candidate != null && isIncluded(candidate)) + { + // We have a candidate field to be replaced with a wrapped version. Report finding to + // summary file. + writeSummary("\t" + classOutline.target.getName() + "#" + fieldName + "\t" + typeName); + modificationCount++; + + // Create the new interface and collection classes using the specified interface and + // collection classes (configuration) with an element type corresponding to + // the element type from the collection present in the candidate class (narrowing). + JDefinedClass candidateClass = model.getClazz(candidate.getClassInfo()).implClass; + List itemNarrowing = ((JClass) candidateClass.fields().get( + candidate.getFieldName()).type()).getTypeParameters(); + JClass newInterfaceClass = implementationClass.owner().ref(interfaceClass).narrow( + itemNarrowing); + JClass newCollectionClass = implementationClass.owner().ref(collectionClass).narrow( + itemNarrowing); + + // Remove original field which refers to the inner class. + JFieldVar implField = implementationClass.fields().get(fieldName); + implementationClass.removeField(implField); + + // Add new wrapped version of the field using the original field name. + // CODE: protected I fieldName; + implField = implementationClass.field(JMod.PROTECTED, newInterfaceClass, fieldName); + + // If instantiation is specified to be "early", add code for creating new instance of the + // collection class. + if (instantiation == Instantiation.EARLY) + { + writeDebug("Applying EARLY instantiation..."); + // CODE: ... fieldName = new C(); + implField.init(JExpr._new(newCollectionClass)); + } + + // Annotate the new field with the @XmlElementWrapper annotation using the original field + // name as name. + JAnnotationUse annotation = implField.annotate(XmlElementWrapper.class); + annotation.param("name", XmlElementWrapperPlugin.elementName(field.getPropertyInfo()) == null ? fieldName : XmlElementWrapperPlugin.elementName(field.getPropertyInfo())); + writeDebug("XmlElementWrapper(name=" + (XmlElementWrapperPlugin.elementName(field.getPropertyInfo()) == null ? fieldName : XmlElementWrapperPlugin.elementName(field.getPropertyInfo())) + ")"); + + // Annotate the new field with the @XmlElement annotation using the field name from the + // wrapped type as name. + annotation = implField.annotate(XmlElement.class); + annotation.param("name", candidate.getWrappedSchemaTypeName() == null ? candidate.getFieldName() : candidate.getWrappedSchemaTypeName()); + writeDebug("XmlElement(name=" + (candidate.getWrappedSchemaTypeName() == null ? candidate.getFieldName() : candidate.getWrappedSchemaTypeName()) + ")"); + + // Find original getter and setter methods to remove. + methodsToRemove = new ArrayList(); + for (JMethod m : implementationClass.methods()) + if (m.name().equals("set" + firstUpper(fieldName)) + || m.name().equals("get" + firstUpper(fieldName))) methodsToRemove.add(m); + + // Remove original getter and setter methods. + for (JMethod m : methodsToRemove) + implementationClass.methods().remove(m); + + // Add a new getter method returning the (wrapped) field added. + // CODE: public I getFieldname() { ... }; + JMethod method = implementationClass.method(JMod.PUBLIC, newInterfaceClass, "get" + + firstUpper(fieldName)); + + if (instantiation == Instantiation.LAZY) + { + writeDebug("Applying LAZY instantiation..."); + // CODE: if (fieldName == null) fieldName = new C(); + method.body()._if(JExpr.ref(fieldName).eq(JExpr._null()))._then().assign( + JExpr.ref(fieldName), JExpr._new(newCollectionClass)); + } + + // CODE: return "fieldName"; + method.body()._return(JExpr.ref(fieldName)); + } + } + } + writeSummary("\t" + modificationCount + " modification(s) to original code."); + writeSummary(" "); + + writeSummary("Deletions:"); + if (deleteCandidates) + { + + // REMOVED: + // Get the default package from options. + // This code was used earlier to only get the factory class from the default package. + // pkg = model.getModel().codeModel._package(opt.defaultPackage); + // JDefinedClass factoryClass = pkg._getClass(factoryClassName); + + JPackage pkg; + + // Get the factory class from the default package. + JDefinedClass factoryClass; + JDefinedClass candidateClass; + + // Visit all candidate classes. + for (Candidate c : candidates.values()) + { + // Only consider candidates that are actually included... + if (isIncluded(c)) + { + // Get the defined class for candidate class. + candidateClass = model.getClazz(c.getClassInfo()).implClass; + + // ADDED: + // This code was added to locate the ObjectFactory inside the package of the candidate class. + pkg = candidateClass._package(); + factoryClass = pkg._getClass(factoryClassName); + + // Remove methods referencing the candidate class from the ObjectFactory. + methodsToRemove = new ArrayList(); + for (JMethod m : factoryClass.methods()) + if (m.type().compareTo(candidateClass) == 0) methodsToRemove.add(m); + + for (JMethod m : methodsToRemove) + { + writeSummary("\tRemoving method " + m.type().fullName() + " " + m.name() + " from " + + factoryClass.fullName()); + factoryClass.methods().remove(m); + deletionCount++; + } + + // Remove the candidate from the class or package it is defined in. + if (candidateClass.parentContainer().isClass()) + { + // The candidate class is an inner class. Remove the class from its parent class. + JDefinedClass parent = (JDefinedClass) candidateClass.parentContainer(); + writeSummary("\tRemoving class " + candidateClass.fullName() + " from class " + + parent.fullName()); + Iterator itor = parent.classes(); + while (itor.hasNext()) + if (itor.next().equals(candidateClass)) + { + itor.remove(); + break; + } + deletionCount++; + } + else + { + // The candidate class in in a package. Remove the class from the package. + JPackage parent = (JPackage) candidateClass.parentContainer(); + writeSummary("\tRemoving class " + candidateClass.fullName() + " from package " + + parent.name()); + parent.remove(candidateClass); + deletionCount++; + } + } + } + } + writeSummary("\t" + deletionCount + " deletion(s) from original code."); + writeSummary(" "); + + try + { + writeDebug("Closing summary..."); + closeSummary(); + } + catch (IOException e) + { + // TODO BJH: How would this type of exception be reported? Should it just be ignored? + } + writeDebug("Done"); + return true; + } + + protected boolean isIncluded(Candidate candidate) + { + // + // A candidate is included if, ... + // 1. No includes and no excludes have been specified + // 2. Includes have been specified and canditate is included, and no excludes have been + // specified. + // 3. No includes have been specified and excludes have been specified and candidate is not in + // excludes. + // 4. Both includes and excludes have been specified and candidate is in includes and not in + // excludes. + // + if (!hasIncludes() && !hasExcludes()) + return true; // [+] (default) + else if (hasIncludes() && !hasExcludes()) + return include.contains(candidate.getClassName()); // [+/-] (included) + else if (!hasIncludes() && hasExcludes()) + return !exclude.contains(candidate.getClassName()); // [+/-] (excluded) + else + return include.contains(candidate.getClassName()) + && !exclude.contains(candidate.getClassName()); // [+/-] (override) + } + + protected String getIncludeOrExcludeReason(Candidate candidate) + { + if (!hasIncludes() && !hasExcludes()) + return "(default)"; // [+] (default) + else if (hasIncludes() && !hasExcludes()) + return "(included)"; + else if (!hasIncludes() && hasExcludes()) + return "(excluded)"; + else + return "(override)"; + } + + protected boolean hasIncludes() + { + return include != null; + } + + protected boolean hasExcludes() + { + return exclude != null; + } + + /** + * + * @param file + * @param candidates + * @throws IOException + */ + protected void readCandidates(File file, Set candidates) throws IOException + { + LineNumberReader input; + String line; + + input = new LineNumberReader(new FileReader(file)); + while ((line = input.readLine()) != null) + { + line = line.trim(); + + // Lines starting with # are considered comments. + if (!line.startsWith("#")) candidates.add(line); + } + input.close(); + } + + /** + * + * @param s + * @return + */ + protected String firstUpper(String s) + { + if (s == null) return null; + if (s.length() == 0) return ""; + return s.substring(0, 1).toUpperCase() + s.substring(1); + } + + /** + * + * @param model + * @param errorHandler + * @return + */ + protected Map findCandidateClasses(Model model, ErrorHandler errorHandler) + { + Map candidates = new HashMap(); + + // Visit all beans created by JAXB processing. + for (CClassInfo classInfo : model.beans().values()) + { + String className = classInfo.fullName(); + + // The candidate class must have exactly one property. + if (classInfo.getProperties().size() == 1) + { + CPropertyInfo property = classInfo.getProperties().get(0); + + // The property must be a collection + if (property.isCollection()) + { + if (property.ref().size() == 1) + { + // We have a candidate class. + Candidate candidate = new Candidate(classInfo); + candidates.put(className, candidate); + writeDebug("Candidate found: " + candidate.getClassName() + ", " + candidate.getFieldName() + ", [" + candidate.getFieldTypeName() + "]"); + } + } + } + } + return candidates; + } + + protected void writeSummary(String s) + { + if (summary != null) + { + summary.println(s); + if (verbose) System.out.println(s); + } + else if (verbose) System.out.println(s); + } + + protected void closeSummary() throws IOException + { + if (summary != null) summary.close(); + } + + protected void writeDebug(String s) + { + if (debugMode) System.out.println("DEBUG:" + s); + } + + protected static String elementName(CPropertyInfo property) + { + try + { + if (property instanceof CElementPropertyInfo) + { + return ((CElementPropertyInfo) property).getTypes().get(0).getTagName().getLocalPart(); + } + else + return null; + } + catch (Exception ex) + { + return null; + } + } + + enum Instantiation + { + EARLY, LAZY + } + + /** + * + * @author bjh + * + */ + class Candidate + { + protected CClassInfo classInfo; + protected CPropertyInfo propertyInfo; + protected CTypeInfo propertyTypeInfo; + + protected JDefinedClass implClass; + protected JFieldVar field; + protected String wrappedSchemaTypeName = null; + + public Candidate(CClassInfo classInfo) + { + this.classInfo = classInfo; + this.propertyInfo = classInfo.getProperties().get(0); + this.propertyTypeInfo = propertyInfo.ref().iterator().next(); + this.wrappedSchemaTypeName = XmlElementWrapperPlugin.elementName(propertyInfo); + } + + public CClassInfo getClassInfo() + { + return classInfo; + } + + public CPropertyInfo getPropertyInfo() + { + return propertyInfo; + } + + public CTypeInfo getPropertyTypeInfo() + { + return propertyTypeInfo; + } + + public String getClassName() + { + return classInfo.fullName(); + } + + public String getFieldName() + { + return getPropertyInfo().getName(false); + } + + public String getFieldTypeName() + { + return propertyTypeInfo.getType().fullName(); + } + + public String getWrappedSchemaTypeName() + { + return wrappedSchemaTypeName; + } + } + + public static void main(String[] args) + { + + } +}