From 72c6f20ffd77fe3e4183cc1f687bdca724fd6547 Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Mon, 22 May 2023 22:00:49 +0200 Subject: [PATCH 1/2] Add plexus 13 parent --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index 267dc1f5d..47c614301 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,12 @@ 4.0.0 + + org.codehaus.plexus + plexus + 13 + + org.codehaus.modello modello 2.1.2-SNAPSHOT From 0e3c0b1e8edcc753f251397a5f79246939613dc3 Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Mon, 22 May 2023 22:00:59 +0200 Subject: [PATCH 2/2] Reformat using spotless --- modello-core/pom.xml | 10 +- .../java/org/codehaus/modello/Modello.java | 38 +- .../java/org/codehaus/modello/ModelloCli.java | 82 +- .../codehaus/modello/ModelloException.java | 14 +- .../modello/ModelloParameterConstants.java | 10 +- .../modello/ModelloRuntimeException.java | 14 +- .../modello/core/AbstractModelloCore.java | 23 +- .../core/DefaultGeneratorPluginManager.java | 26 +- .../core/DefaultMetadataPluginManager.java | 26 +- .../modello/core/DefaultModelloCore.java | 240 +- .../modello/core/GeneratorPluginManager.java | 11 +- .../modello/core/MetadataPluginManager.java | 11 +- .../codehaus/modello/core/ModelloCore.java | 29 +- .../codehaus/modello/core/io/ModelReader.java | 587 ++-- .../metadata/AbstractMetadataPlugin.java | 28 +- .../modello/metadata/AssociationMetadata.java | 5 +- .../modello/metadata/ClassMetadata.java | 5 +- .../modello/metadata/FieldMetadata.java | 5 +- .../modello/metadata/InterfaceMetadata.java | 5 +- .../codehaus/modello/metadata/Metadata.java | 4 +- .../modello/metadata/MetadataPlugin.java | 23 +- .../modello/metadata/ModelMetadata.java | 5 +- .../codehaus/modello/model/BaseElement.java | 135 +- .../codehaus/modello/model/CodeSegment.java | 19 +- .../org/codehaus/modello/model/Model.java | 372 +-- .../modello/model/ModelAssociation.java | 151 +- .../codehaus/modello/model/ModelClass.java | 180 +- .../codehaus/modello/model/ModelDefault.java | 115 +- .../codehaus/modello/model/ModelField.java | 162 +- .../modello/model/ModelInterface.java | 34 +- .../org/codehaus/modello/model/ModelType.java | 153 +- .../model/ModelValidationException.java | 9 +- .../org/codehaus/modello/model/Version.java | 149 +- .../modello/model/VersionDefinition.java | 40 +- .../codehaus/modello/model/VersionRange.java | 72 +- .../codehaus/modello/model/VersionUtil.java | 10 +- .../plugin/AbstractModelloGenerator.java | 224 +- .../modello/plugin/AbstractPluginManager.java | 37 +- .../modello/plugin/ModelloGenerator.java | 10 +- .../model/ModelAssociationMetadata.java | 4 +- .../plugin/model/ModelClassMetadata.java | 23 +- .../plugin/model/ModelFieldMetadata.java | 4 +- .../plugin/model/ModelInterfaceMetadata.java | 4 +- .../plugin/model/ModelMetadataPlugin.java | 33 +- .../plugin/model/ModelModelMetadata.java | 4 +- .../modello/core/DefaultModelloCoreTest.java | 72 +- .../modello/core/io/ModelReaderTest.java | 136 +- .../modello/model/VersionDefinitionTest.java | 35 +- .../codehaus/modello/model/VersionTest.java | 83 +- modello-maven-plugin/pom.xml | 15 +- .../maven/AbstractModelloGeneratorMojo.java | 238 +- .../AbstractModelloSourceGeneratorMojo.java | 43 +- .../modello/maven/ModelloConvertersMojo.java | 9 +- .../modello/maven/ModelloDom4jReaderMojo.java | 9 +- .../modello/maven/ModelloDom4jWriterMojo.java | 9 +- .../modello/maven/ModelloGenerateMojo.java | 30 +- .../modello/maven/ModelloJDOMWriterMojo.java | 9 +- .../ModelloJacksonExtendedReaderMojo.java | 10 +- .../maven/ModelloJacksonReaderMojo.java | 29 +- .../maven/ModelloJacksonWriterMojo.java | 29 +- .../modello/maven/ModelloJavaMojo.java | 9 +- .../maven/ModelloJsonSchemaGeneratorMojo.java | 25 +- .../modello/maven/ModelloSaxWriterMojo.java | 9 +- .../ModelloSnakeYamlExtendedReaderMojo.java | 10 +- .../maven/ModelloSnakeYamlReaderMojo.java | 9 +- .../maven/ModelloSnakeYamlWriterMojo.java | 9 +- .../modello/maven/ModelloStaxReaderMojo.java | 9 +- .../modello/maven/ModelloStaxWriterMojo.java | 9 +- .../modello/maven/ModelloVelocityMojo.java | 42 +- .../modello/maven/ModelloXdocMojo.java | 53 +- .../maven/ModelloXpp3ExtendedReaderMojo.java | 10 +- .../maven/ModelloXpp3ExtendedWriterMojo.java | 21 +- .../modello/maven/ModelloXpp3ReaderMojo.java | 9 +- .../modello/maven/ModelloXpp3WriterMojo.java | 9 +- .../modello/maven/ModelloXsdMojo.java | 34 +- .../maven/ModelloConvertersMojoTest.java | 73 +- .../modello/maven/ModelloJavaMojoTest.java | 68 +- .../modello-plugin-converters/pom.xml | 10 +- .../plugin/converters/ConverterGenerator.java | 456 ++- .../converters/ConverterGeneratorTest.java | 86 +- modello-plugins/modello-plugin-dom4j/pom.xml | 10 +- .../plugin/dom4j/Dom4jReaderGenerator.java | 1059 ++++--- .../plugin/dom4j/Dom4jWriterGenerator.java | 445 ++- .../plugin/dom4j/Dom4jGeneratorTest.java | 66 +- .../dom4j/FeaturesDom4jGeneratorTest.java | 37 +- .../modello-plugin-jackson/pom.xml | 27 +- .../jackson/AbstractJacksonGenerator.java | 5 +- .../JacksonExtendedReaderGenerator.java | 13 +- .../jackson/JacksonReaderGenerator.java | 934 +++--- .../jackson/JacksonWriterGenerator.java | 379 +-- .../plugin/jackson/JacksonGeneratorTest.java | 41 +- modello-plugins/modello-plugin-java/pom.xml | 10 +- .../java/AbstractJavaModelloGenerator.java | 303 +- .../plugin/java/JavaModelloGenerator.java | 2716 +++++++---------- .../plugin/java/javasource/JAnnotations.java | 34 +- .../plugin/java/javasource/JArrayType.java | 12 +- .../plugin/java/javasource/JClass.java | 621 ++-- .../java/javasource/JCollectionType.java | 31 +- .../plugin/java/javasource/JComment.java | 212 +- .../plugin/java/javasource/JCompUnit.java | 320 +- .../java/javasource/JComponentizedType.java | 15 +- .../plugin/java/javasource/JConstructor.java | 187 +- .../plugin/java/javasource/JDocComment.java | 147 +- .../java/javasource/JDocDescriptor.java | 190 +- .../plugin/java/javasource/JField.java | 127 +- .../plugin/java/javasource/JInterface.java | 356 +-- .../plugin/java/javasource/JMapType.java | 48 +- .../plugin/java/javasource/JMember.java | 10 +- .../plugin/java/javasource/JMethod.java | 239 +- .../java/javasource/JMethodSignature.java | 291 +- .../plugin/java/javasource/JModifiers.java | 186 +- .../plugin/java/javasource/JNaming.java | 47 +- .../plugin/java/javasource/JParameter.java | 75 +- .../plugin/java/javasource/JSourceCode.java | 189 +- .../plugin/java/javasource/JSourceWriter.java | 498 ++- .../plugin/java/javasource/JStructure.java | 744 ++--- .../modello/plugin/java/javasource/JType.java | 132 +- .../metadata/JavaAssociationMetadata.java | 62 +- .../java/metadata/JavaClassMetadata.java | 56 +- .../java/metadata/JavaFieldMetadata.java | 24 +- .../java/metadata/JavaInterfaceMetadata.java | 4 +- .../java/metadata/JavaMetadataPlugin.java | 58 +- .../java/metadata/JavaModelMetadata.java | 10 +- .../java/AbstractAnnotationsVerifier.java | 30 +- .../plugin/java/AbstractPrincipal.java | 9 +- .../java/AnnotationsJava4GeneratorTest.java | 23 +- .../java/AnnotationsJavaGeneratorTest.java | 34 +- .../plugin/java/AssociationGeneratorTest.java | 27 +- ...iDirectionalOverrideJavaGeneratorTest.java | 27 +- .../plugin/java/BuilderJavaGeneratorTest.java | 40 +- .../java/FeaturesJava5GeneratorTest.java | 33 +- .../FeaturesVersionJavaGeneratorTest.java | 36 +- .../plugin/java/InterfaceAssociationTest.java | 29 +- .../plugin/java/JavaGeneratorTest.java | 27 +- .../java/LocationsJavaGeneratorTest.java | 30 +- .../plugin/java/PackageVersionJavaTest.java | 29 +- .../modello/plugin/java/Permission.java | 7 +- .../codehaus/modello/plugin/java/Role.java | 3 +- .../java/StaticCreatorJavaGeneratorTest.java | 28 +- .../plugin/java/TmpJavaGeneratorTest.java | 25 +- .../java/ToStringJavaGeneratorTest.java | 31 +- .../java/javasource/JMapTypeTestCase.java | 47 +- .../java/javasource/JavaSourceTest.java | 207 +- modello-plugins/modello-plugin-jdom/pom.xml | 10 +- .../plugin/jdom/AbstractJDOMGenerator.java | 5 +- .../plugin/jdom/JDOMWriterGenerator.java | 992 +++--- .../jdom/FeaturesJDOMGeneratorTest.java | 35 +- .../modello-plugin-jsonschema/pom.xml | 6 +- .../jsonschema/JsonSchemaGenerator.java | 267 +- modello-plugins/modello-plugin-sax/pom.xml | 22 +- .../plugin/sax/SaxWriterGenerator.java | 693 ++--- .../modello/plugin/sax/SaxGeneratorTest.java | 59 +- .../modello-plugin-snakeyaml/pom.xml | 6 +- .../snakeyaml/AbstractSnakeYamlGenerator.java | 5 +- .../SnakeYamlExtendedReaderGenerator.java | 15 +- .../snakeyaml/SnakeYamlReaderGenerator.java | 1240 ++++---- .../snakeyaml/SnakeYamlWriterGenerator.java | 471 ++- modello-plugins/modello-plugin-stax/pom.xml | 12 +- .../plugin/stax/AbstractStaxGenerator.java | 75 +- .../plugin/stax/DummyIdModelField.java | 7 +- .../modello/plugin/stax/GeneratorNode.java | 72 +- .../plugin/stax/StaxReaderGenerator.java | 1969 ++++++------ .../plugin/stax/StaxSerializerGenerator.java | 511 ++-- .../plugin/stax/StaxWriterGenerator.java | 693 ++--- .../stax/AbstractStaxGeneratorTestCase.java | 61 +- .../stax/BooleanTypeStaxGeneratorTest.java | 27 +- .../stax/FeaturesStaxDomGeneratorTest.java | 43 +- .../xml/stax/FeaturesStaxGeneratorTest.java | 41 +- .../xml/stax/NoAdderStaxGeneratorTest.java | 25 +- .../xml/stax/StaxGeneratorPartsTest.java | 31 +- .../generator/xml/stax/StaxGeneratorTest.java | 52 +- .../stax/StaxGeneratorVersionInFieldTest.java | 31 +- .../StaxGeneratorVersionInNamespaceTest.java | 31 +- ...taxGeneratorVersionReaderDelegateTest.java | 22 +- ...xGeneratorWrongVersionInNamespaceTest.java | 31 +- .../stax/StaxGeneratorWrongVersionTest.java | 31 +- .../modello-plugin-velocity/pom.xml | 10 +- .../modello/plugin/velocity/Helper.java | 109 +- .../plugin/velocity/VelocityGenerator.java | 131 +- modello-plugins/modello-plugin-xdoc/pom.xml | 12 +- .../modello/plugin/xdoc/XdocGenerator.java | 610 ++-- .../metadata/XdocAssociationMetadata.java | 4 +- .../xdoc/metadata/XdocClassMetadata.java | 10 +- .../xdoc/metadata/XdocFieldMetadata.java | 10 +- .../xdoc/metadata/XdocInterfaceMetadata.java | 4 +- .../xdoc/metadata/XdocMetadataPlugin.java | 34 +- .../xdoc/metadata/XdocModelMetadata.java | 4 +- .../plugin/xdoc/XdocGeneratorTest.java | 176 +- modello-plugins/modello-plugin-xml/pom.xml | 13 +- .../plugins/xml/AbstractXmlGenerator.java | 44 +- .../plugins/xml/AbstractXmlJavaGenerator.java | 132 +- .../modello/plugins/xml/XmlModelHelpers.java | 119 +- .../xml/metadata/XmlAssociationMetadata.java | 62 +- .../xml/metadata/XmlClassMetadata.java | 16 +- .../xml/metadata/XmlFieldMetadata.java | 46 +- .../xml/metadata/XmlInterfaceMetadata.java | 4 +- .../xml/metadata/XmlMetadataPlugin.java | 52 +- .../xml/metadata/XmlModelMetadata.java | 32 +- .../plugins/xml/XmlModelHelpersTest.java | 123 +- .../plugins/xml/XmlModelloPluginTest.java | 81 +- modello-plugins/modello-plugin-xpp3/pom.xml | 10 +- .../plugin/xpp3/AbstractXpp3Generator.java | 27 +- .../xpp3/Xpp3ExtendedReaderGenerator.java | 17 +- .../xpp3/Xpp3ExtendedWriterGenerator.java | 152 +- .../plugin/xpp3/Xpp3ReaderGenerator.java | 1644 +++++----- .../plugin/xpp3/Xpp3WriterGenerator.java | 549 ++-- .../xml/xpp3/AbstractElementTest.java | 31 +- .../xpp3/BooleanTypeXpp3GeneratorTest.java | 25 +- .../xpp3/FeaturesXpp3DomGeneratorTest.java | 37 +- .../xml/xpp3/FeaturesXpp3GeneratorTest.java | 35 +- .../LocationsSourceXpp3GeneratorTest.java | 34 +- .../xml/xpp3/LocationsXpp3GeneratorTest.java | 34 +- .../xpp3/StandaloneReadXpp3GeneratorTest.java | 48 +- .../generator/xml/xpp3/Xpp3GeneratorTest.java | 69 +- modello-plugins/modello-plugin-xsd/pom.xml | 10 +- .../modello/plugin/xsd/XsdGenerator.java | 546 ++-- .../modello/plugin/xsd/XsdModelHelper.java | 49 +- .../xsd/metadata/XsdAssociationMetadata.java | 5 +- .../plugin/xsd/metadata/XsdClassMetadata.java | 17 +- .../plugin/xsd/metadata/XsdFieldMetadata.java | 5 +- .../xsd/metadata/XsdInterfaceMetadata.java | 6 +- .../xsd/metadata/XsdMetadataPlugin.java | 38 +- .../plugin/xsd/metadata/XsdModelMetadata.java | 31 +- .../plugin/xsd/ChangesXsdGeneratorTest.java | 26 +- .../plugin/xsd/FeaturesXsdGeneratorTest.java | 99 +- .../plugin/xsd/ModelloXsdGeneratorTest.java | 48 +- .../plugin/xsd/PluginsXsdGeneratorTest.java | 40 +- .../modello/plugin/xsd/XsdGeneratorTest.java | 61 +- modello-plugins/pom.xml | 14 +- modello-test/pom.xml | 14 +- .../modello/AbstractModelloGeneratorTest.java | 74 +- .../AbstractModelloJavaGeneratorTest.java | 336 +- .../codehaus/modello/OrderedProperties.java | 9 +- .../codehaus/modello/verifier/Verifier.java | 104 +- .../modello/verifier/VerifierException.java | 19 +- pom.xml | 33 +- 236 files changed, 13014 insertions(+), 17264 deletions(-) diff --git a/modello-core/pom.xml b/modello-core/pom.xml index 953434341..5d0b6cd37 100644 --- a/modello-core/pom.xml +++ b/modello-core/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello org.codehaus.modello + modello 2.1.2-SNAPSHOT - - 4.0.0 modello-core Modello Core - - Modello Core contains the basis for model description, reading, and plugins system. - + Modello Core contains the basis for model description, reading, and plugins system. diff --git a/modello-core/src/main/java/org/codehaus/modello/Modello.java b/modello-core/src/main/java/org/codehaus/modello/Modello.java index 03a1927ba..f1d2c8485 100644 --- a/modello-core/src/main/java/org/codehaus/modello/Modello.java +++ b/modello-core/src/main/java/org/codehaus/modello/Modello.java @@ -29,47 +29,39 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelValidationException; -import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.DefaultPlexusContainer; +import org.codehaus.plexus.PlexusContainer; /** * @author Jason van Zyl * @author Trygve Laugstøl */ -public class Modello -{ +public class Modello { private PlexusContainer container; private ModelloCore core; - public Modello() - throws ModelloException - { - try - { + public Modello() throws ModelloException { + try { container = new DefaultPlexusContainer(); - core = (ModelloCore) container.lookup( ModelloCore.ROLE ); - } - catch ( Exception ex ) - { - throw new ModelloException( "Error while starting plexus.", ex ); + core = (ModelloCore) container.lookup(ModelloCore.ROLE); + } catch (Exception ex) { + throw new ModelloException("Error while starting plexus.", ex); } } - public void generate( Reader modelReader, String outputType, Properties parameters ) - throws ModelloException, ModelValidationException - { - Model model = core.loadModel( modelReader ); + public void generate(Reader modelReader, String outputType, Properties parameters) + throws ModelloException, ModelValidationException { + Model model = core.loadModel(modelReader); - core.generate( model, outputType, parameters ); + core.generate(model, outputType, parameters); } - public void translate( Reader reader, Writer writer, String outputType, Properties parameters ) - throws ModelloException, ModelValidationException - { - Model model = core.translate( reader, outputType, parameters ); + public void translate(Reader reader, Writer writer, String outputType, Properties parameters) + throws ModelloException, ModelValidationException { + Model model = core.translate(reader, outputType, parameters); - core.saveModel( model, writer ); + core.saveModel(model, writer); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/ModelloCli.java b/modello-core/src/main/java/org/codehaus/modello/ModelloCli.java index 5cf716e4b..db4c84ef9 100644 --- a/modello-core/src/main/java/org/codehaus/modello/ModelloCli.java +++ b/modello-core/src/main/java/org/codehaus/modello/ModelloCli.java @@ -22,44 +22,38 @@ * SOFTWARE. */ -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.StringUtils; - import java.io.File; import java.util.Properties; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.StringUtils; + /** * @author Trygve Laugstøl */ -public class ModelloCli -{ +public class ModelloCli { private static File modelFile; private static String outputType; private static Properties parameters; - public static void main( String[] args ) - throws Exception - { + public static void main(String[] args) throws Exception { Modello modello = new Modello(); - parseArgumentsFromCommandLine( args ); + parseArgumentsFromCommandLine(args); - modello.generate( ReaderFactory.newXmlReader( modelFile ), outputType, parameters ); + modello.generate(ReaderFactory.newXmlReader(modelFile), outputType, parameters); } - public static void parseArgumentsFromCommandLine( String[] args ) - throws Exception - { - if ( args.length < 6 ) - { + public static void parseArgumentsFromCommandLine(String[] args) throws Exception { + if (args.length < 6) { usage(); - System.exit( 1 ); + System.exit(1); } - modelFile = new File( args[0] ); + modelFile = new File(args[0]); outputType = args[1]; @@ -67,59 +61,54 @@ public static void parseArgumentsFromCommandLine( String[] args ) String outputDirectory = args[2]; - if ( StringUtils.isEmpty( outputDirectory ) ) - { - System.err.println( "Missing required parameter: output directory" ); + if (StringUtils.isEmpty(outputDirectory)) { + System.err.println("Missing required parameter: output directory"); usage(); - System.exit( 1 ); + System.exit(1); } - parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, outputDirectory ); + parameters.setProperty(ModelloParameterConstants.OUTPUT_DIRECTORY, outputDirectory); - String modelVersion = args[ 3 ]; + String modelVersion = args[3]; - if ( StringUtils.isEmpty( modelVersion ) ) - { - System.err.println( "Missing required parameter: model version" ); + if (StringUtils.isEmpty(modelVersion)) { + System.err.println("Missing required parameter: model version"); usage(); - System.exit( 1 ); + System.exit(1); } - parameters.setProperty( ModelloParameterConstants.VERSION, modelVersion ); + parameters.setProperty(ModelloParameterConstants.VERSION, modelVersion); - String packageWithVersion = args[ 4 ]; + String packageWithVersion = args[4]; - if ( StringUtils.isEmpty( packageWithVersion ) ) - { - System.err.println( "Missing required parameter: package with version" ); + if (StringUtils.isEmpty(packageWithVersion)) { + System.err.println("Missing required parameter: package with version"); usage(); - System.exit( 1 ); + System.exit(1); } - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, packageWithVersion ); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, packageWithVersion); - String javaSource = args[ 5 ]; + String javaSource = args[5]; - if ( StringUtils.isEmpty( javaSource ) ) - { - System.err.println( "Missing required parameter: Java Source" ); + if (StringUtils.isEmpty(javaSource)) { + System.err.println("Missing required parameter: Java Source"); usage(); - System.exit( 1 ); + System.exit(1); } - parameters.setProperty( ModelloParameterConstants.OUTPUT_JAVA_SOURCE, javaSource ); + parameters.setProperty(ModelloParameterConstants.OUTPUT_JAVA_SOURCE, javaSource); - if ( args.length > 6 ) - { - parameters.setProperty( ModelloParameterConstants.ENCODING, args[6] ); + if (args.length > 6) { + parameters.setProperty(ModelloParameterConstants.ENCODING, args[6]); } } @@ -127,9 +116,8 @@ public static void parseArgumentsFromCommandLine( String[] args ) // // ---------------------------------------------------------------------- - private static void usage() - { - System.err.println( "Usage: modello " - + " []" ); + private static void usage() { + System.err.println("Usage: modello " + + " []"); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/ModelloException.java b/modello-core/src/main/java/org/codehaus/modello/ModelloException.java index 876757a09..73d4fc6f7 100644 --- a/modello-core/src/main/java/org/codehaus/modello/ModelloException.java +++ b/modello-core/src/main/java/org/codehaus/modello/ModelloException.java @@ -25,18 +25,14 @@ /** * @author Trygve Laugstøl */ -public class ModelloException - extends Exception -{ +public class ModelloException extends Exception { private static final long serialVersionUID = -8746896773615188345L; - public ModelloException( String msg ) - { - super( msg ); + public ModelloException(String msg) { + super(msg); } - public ModelloException( String msg, Throwable cause ) - { - super( msg, cause ); + public ModelloException(String msg, Throwable cause) { + super(msg, cause); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/ModelloParameterConstants.java b/modello-core/src/main/java/org/codehaus/modello/ModelloParameterConstants.java index 9e9db422b..0c80a98f5 100644 --- a/modello-core/src/main/java/org/codehaus/modello/ModelloParameterConstants.java +++ b/modello-core/src/main/java/org/codehaus/modello/ModelloParameterConstants.java @@ -25,8 +25,7 @@ /** * @author Trygve Laugstøl */ -public class ModelloParameterConstants -{ +public class ModelloParameterConstants { public static final String VERSION = "modello.version"; public static final String OUTPUT_DIRECTORY = "modello.output.directory"; @@ -47,7 +46,7 @@ public class ModelloParameterConstants public static final String ENCODING = "modello.output.encoding"; /** - * Replaces USE_JAVA5 + * Replaces USE_JAVA5 * @since 2.0 */ public static final String OUTPUT_JAVA_SOURCE = "modello.output.java.source"; @@ -78,7 +77,6 @@ public class ModelloParameterConstants * @since 2.1 */ public static final String XSD_ENFORCE_MANDATORY_ELEMENTS = "modello.xsd.enforce.mandatory.element"; - private ModelloParameterConstants() - { - } + + private ModelloParameterConstants() {} } diff --git a/modello-core/src/main/java/org/codehaus/modello/ModelloRuntimeException.java b/modello-core/src/main/java/org/codehaus/modello/ModelloRuntimeException.java index 8af6080df..d368f5b92 100644 --- a/modello-core/src/main/java/org/codehaus/modello/ModelloRuntimeException.java +++ b/modello-core/src/main/java/org/codehaus/modello/ModelloRuntimeException.java @@ -25,18 +25,14 @@ /** * @author Trygve Laugstøl */ -public class ModelloRuntimeException - extends RuntimeException -{ +public class ModelloRuntimeException extends RuntimeException { private static final long serialVersionUID = -637783066384319780L; - public ModelloRuntimeException( String msg ) - { - super( msg ); + public ModelloRuntimeException(String msg) { + super(msg); } - public ModelloRuntimeException( String msg, Throwable cause ) - { - super( msg, cause ); + public ModelloRuntimeException(String msg, Throwable cause) { + super(msg, cause); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/AbstractModelloCore.java b/modello-core/src/main/java/org/codehaus/modello/core/AbstractModelloCore.java index dc3233582..a0cecb74d 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/AbstractModelloCore.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/AbstractModelloCore.java @@ -22,34 +22,27 @@ * SOFTWARE. */ +import java.io.Reader; +import java.io.Writer; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelValidationException; import org.codehaus.plexus.logging.AbstractLogEnabled; -import java.io.Reader; -import java.io.Writer; - /** * @author Trygve Laugstøl */ -public abstract class AbstractModelloCore - extends AbstractLogEnabled - implements ModelloCore -{ +public abstract class AbstractModelloCore extends AbstractLogEnabled implements ModelloCore { // ---------------------------------------------------------------------- // Partial ModelloCore implementation // ---------------------------------------------------------------------- - public Model input( Reader reader ) - throws ModelloException, ModelValidationException - { - return loadModel( reader ); + public Model input(Reader reader) throws ModelloException, ModelValidationException { + return loadModel(reader); } - public void output( Model model, Writer writer ) - throws ModelloException - { - saveModel( model, writer ); + public void output(Model model, Writer writer) throws ModelloException { + saveModel(model, writer); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/DefaultGeneratorPluginManager.java b/modello-core/src/main/java/org/codehaus/modello/core/DefaultGeneratorPluginManager.java index 82e30f1c7..8f6139921 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/DefaultGeneratorPluginManager.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/DefaultGeneratorPluginManager.java @@ -33,33 +33,27 @@ /** * @author Trygve Laugstøl */ -@Component( role = GeneratorPluginManager.class ) -public class DefaultGeneratorPluginManager - extends AbstractPluginManager - implements GeneratorPluginManager -{ +@Component(role = GeneratorPluginManager.class) +public class DefaultGeneratorPluginManager extends AbstractPluginManager + implements GeneratorPluginManager { @Requirement private Map plugins; - public Map getPlugins() - { + public Map getPlugins() { return plugins; } - public ModelloGenerator getGeneratorPlugin( String generatorId ) - { - ModelloGenerator generator = getPlugin( generatorId ); + public ModelloGenerator getGeneratorPlugin(String generatorId) { + ModelloGenerator generator = getPlugin(generatorId); - if ( generator == null ) - { - throw new ModelloRuntimeException( "No such generator plugin: '" + generatorId + "'." ); + if (generator == null) { + throw new ModelloRuntimeException("No such generator plugin: '" + generatorId + "'."); } return generator; } - public boolean hasGeneratorPlugin( String generatorId ) - { - return hasPlugin( generatorId ); + public boolean hasGeneratorPlugin(String generatorId) { + return hasPlugin(generatorId); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/DefaultMetadataPluginManager.java b/modello-core/src/main/java/org/codehaus/modello/core/DefaultMetadataPluginManager.java index 85accc2eb..494dd2ca3 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/DefaultMetadataPluginManager.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/DefaultMetadataPluginManager.java @@ -33,33 +33,27 @@ /** * @author Trygve Laugstøl */ -@Component( role = MetadataPluginManager.class ) -public class DefaultMetadataPluginManager - extends AbstractPluginManager - implements MetadataPluginManager -{ +@Component(role = MetadataPluginManager.class) +public class DefaultMetadataPluginManager extends AbstractPluginManager + implements MetadataPluginManager { @Requirement private Map plugins; - public Map getPlugins() - { + public Map getPlugins() { return plugins; } - public MetadataPlugin getMetadataPlugin( String metadataId ) - { - MetadataPlugin metadata = getPlugin( metadataId ); + public MetadataPlugin getMetadataPlugin(String metadataId) { + MetadataPlugin metadata = getPlugin(metadataId); - if ( metadata == null ) - { - throw new ModelloRuntimeException( "No such metadata plugin: '" + metadataId + "'." ); + if (metadata == null) { + throw new ModelloRuntimeException("No such metadata plugin: '" + metadataId + "'."); } return metadata; } - public boolean hasMetadataPlugin( String metadataId ) - { - return hasPlugin( metadataId ); + public boolean hasMetadataPlugin(String metadataId) { + return hasPlugin(metadataId); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/DefaultModelloCore.java b/modello-core/src/main/java/org/codehaus/modello/core/DefaultModelloCore.java index 4981909dc..ba77df3fc 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/DefaultModelloCore.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/DefaultModelloCore.java @@ -22,6 +22,15 @@ * SOFTWARE. */ +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloRuntimeException; import org.codehaus.modello.core.io.ModelReader; @@ -44,86 +53,64 @@ import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.ReaderFactory; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Properties; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -@Component( role = ModelloCore.class ) -public class DefaultModelloCore - extends AbstractModelloCore -{ +@Component(role = ModelloCore.class) +public class DefaultModelloCore extends AbstractModelloCore { @Requirement private MetadataPluginManager metadataPluginManager; @Requirement private GeneratorPluginManager generatorPluginManager; - public MetadataPluginManager getMetadataPluginManager() - { + public MetadataPluginManager getMetadataPluginManager() { return metadataPluginManager; } - public Model loadModel( File file ) - throws IOException, ModelloException, ModelValidationException - { - try ( Reader reader = ReaderFactory.newXmlReader( file ) ) - { - return loadModel( reader ); + public Model loadModel(File file) throws IOException, ModelloException, ModelValidationException { + try (Reader reader = ReaderFactory.newXmlReader(file)) { + return loadModel(reader); } } - private void upgradeModifiedAttribute( String name, Map from, String newName, - Map to, String warn ) - { - String value = from.remove( name ); + private void upgradeModifiedAttribute( + String name, Map from, String newName, Map to, String warn) { + String value = from.remove(name); - if ( value != null ) - { - getLogger().warn( warn ); + if (value != null) { + getLogger().warn(warn); - to.put( newName, value ); + to.put(newName, value); } } - @SuppressWarnings( "unused" ) - private void upgradeModifiedAttribute( String name, Map from, Map to, String warn ) - { - upgradeModifiedAttribute( name, from, name, to, warn ); + @SuppressWarnings("unused") + private void upgradeModifiedAttribute(String name, Map from, Map to, String warn) { + upgradeModifiedAttribute(name, from, name, to, warn); } /** * Rename or move entities and provide a deprecation message - * + * * @param modelReader * @param model */ - private void upgradeModelloModel( ModelReader modelReader, Model model ) - { - } + private void upgradeModelloModel(ModelReader modelReader, Model model) {} - public Model loadModel( Reader reader ) - throws ModelloException, ModelValidationException - { + public Model loadModel(Reader reader) throws ModelloException, ModelValidationException { ModelReader modelReader = new ModelReader(); - Model model = modelReader.loadModel( reader ); + Model model = modelReader.loadModel(reader); model.initialize(); // keep backward compatibility with Modello attributes model changes - upgradeModelloModel( modelReader, model ); + upgradeModelloModel(modelReader, model); - handlePluginsMetadata( modelReader, model ); + handlePluginsMetadata(modelReader, model); - validate( model ); + validate(model); return model; } @@ -133,117 +120,100 @@ public Model loadModel( Reader reader ) * * @throws ModelloException */ - private void handlePluginsMetadata( ModelReader modelReader, Model model ) - throws ModelloException - { + private void handlePluginsMetadata(ModelReader modelReader, Model model) throws ModelloException { Collection plugins = metadataPluginManager.getPlugins().values(); - for ( MetadataPlugin plugin : plugins ) - { + for (MetadataPlugin plugin : plugins) { Map attributes = modelReader.getAttributesForModel(); - attributes = Collections.unmodifiableMap( attributes ); + attributes = Collections.unmodifiableMap(attributes); - ModelMetadata metadata = plugin.getModelMetadata( model, attributes ); + ModelMetadata metadata = plugin.getModelMetadata(model, attributes); - if ( metadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (metadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - model.addMetadata( metadata ); + model.addMetadata(metadata); } - for ( ModelClass clazz : model.getAllClasses() ) - { - Map attributes = modelReader.getAttributesForClass( clazz ); + for (ModelClass clazz : model.getAllClasses()) { + Map attributes = modelReader.getAttributesForClass(clazz); - attributes = Collections.unmodifiableMap( attributes ); + attributes = Collections.unmodifiableMap(attributes); - for ( MetadataPlugin plugin : plugins ) - { - ClassMetadata metadata = plugin.getClassMetadata( clazz, attributes ); + for (MetadataPlugin plugin : plugins) { + ClassMetadata metadata = plugin.getClassMetadata(clazz, attributes); - if ( metadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (metadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - clazz.addMetadata( metadata ); + clazz.addMetadata(metadata); } - for ( ModelField field : clazz.getAllFields() ) - { - if ( field instanceof ModelAssociation ) - { + for (ModelField field : clazz.getAllFields()) { + if (field instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) field; - Map fieldAttributes = modelReader.getAttributesForField( modelAssociation ); + Map fieldAttributes = modelReader.getAttributesForField(modelAssociation); - fieldAttributes = Collections.unmodifiableMap( fieldAttributes ); + fieldAttributes = Collections.unmodifiableMap(fieldAttributes); - Map associationAttributes = modelReader.getAttributesForAssociation( modelAssociation ); + Map associationAttributes = + modelReader.getAttributesForAssociation(modelAssociation); - associationAttributes = Collections.unmodifiableMap( associationAttributes ); + associationAttributes = Collections.unmodifiableMap(associationAttributes); - for ( MetadataPlugin plugin : plugins ) - { - FieldMetadata fieldMetadata = plugin.getFieldMetadata( modelAssociation, fieldAttributes ); + for (MetadataPlugin plugin : plugins) { + FieldMetadata fieldMetadata = plugin.getFieldMetadata(modelAssociation, fieldAttributes); - if ( fieldMetadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (fieldMetadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - modelAssociation.addMetadata( fieldMetadata ); + modelAssociation.addMetadata(fieldMetadata); - AssociationMetadata associationMetadata = plugin.getAssociationMetadata( modelAssociation, associationAttributes ); + AssociationMetadata associationMetadata = + plugin.getAssociationMetadata(modelAssociation, associationAttributes); - if ( associationMetadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (associationMetadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - modelAssociation.addMetadata( associationMetadata ); + modelAssociation.addMetadata(associationMetadata); } - } - else - { - attributes = modelReader.getAttributesForField( field ); + } else { + attributes = modelReader.getAttributesForField(field); - attributes = Collections.unmodifiableMap( attributes ); + attributes = Collections.unmodifiableMap(attributes); - for ( MetadataPlugin plugin : plugins ) - { - FieldMetadata metadata = plugin.getFieldMetadata( field, attributes ); + for (MetadataPlugin plugin : plugins) { + FieldMetadata metadata = plugin.getFieldMetadata(field, attributes); - if ( metadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (metadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - field.addMetadata( metadata ); + field.addMetadata(metadata); } } } } - for ( ModelInterface iface : model.getAllInterfaces() ) - { - Map attributes = modelReader.getAttributesForInterface( iface ); + for (ModelInterface iface : model.getAllInterfaces()) { + Map attributes = modelReader.getAttributesForInterface(iface); - attributes = Collections.unmodifiableMap( attributes ); + attributes = Collections.unmodifiableMap(attributes); - for ( MetadataPlugin plugin : plugins ) - { - InterfaceMetadata metadata = plugin.getInterfaceMetadata( iface, attributes ); + for (MetadataPlugin plugin : plugins) { + InterfaceMetadata metadata = plugin.getInterfaceMetadata(iface, attributes); - if ( metadata == null ) - { - throw new ModelloException( "A meta data plugin must not return null." ); + if (metadata == null) { + throw new ModelloException("A meta data plugin must not return null."); } - iface.addMetadata( metadata ); + iface.addMetadata(metadata); } } } @@ -253,67 +223,51 @@ private void handlePluginsMetadata( ModelReader modelReader, Model model ) * * @throws ModelValidationException */ - private void validate( Model model ) - throws ModelValidationException - { + private void validate(Model model) throws ModelValidationException { model.validate(); - for ( ModelDefault modelDefault : model.getDefaults() ) - { + for (ModelDefault modelDefault : model.getDefaults()) { modelDefault.validateElement(); } - for ( ModelClass modelClass : model.getAllClasses() ) - { + for (ModelClass modelClass : model.getAllClasses()) { modelClass.validate(); } - for ( ModelClass modelClass : model.getAllClasses() ) - { - for ( ModelField field : modelClass.getAllFields() ) - { + for (ModelClass modelClass : model.getAllClasses()) { + for (ModelField field : modelClass.getAllFields()) { field.validate(); } - for ( CodeSegment codeSegment : modelClass.getAllCodeSegments() ) - { + for (CodeSegment codeSegment : modelClass.getAllCodeSegments()) { codeSegment.validate(); } } } - public void saveModel( Model model, Writer writer ) - throws ModelloException - { - throw new ModelloRuntimeException( "Not implemented." ); + public void saveModel(Model model, Writer writer) throws ModelloException { + throw new ModelloRuntimeException("Not implemented."); } - public Model translate( Reader reader, String inputType, Properties parameters ) - throws ModelloException - { - throw new ModelloRuntimeException( "Not implemented." ); + public Model translate(Reader reader, String inputType, Properties parameters) throws ModelloException { + throw new ModelloRuntimeException("Not implemented."); } - public void generate( Model model, String outputType, Properties parameters ) - throws ModelloException - { - if ( model == null ) - { - throw new ModelloRuntimeException( "Illegal argument: model == null." ); + public void generate(Model model, String outputType, Properties parameters) throws ModelloException { + if (model == null) { + throw new ModelloRuntimeException("Illegal argument: model == null."); } - if ( outputType == null ) - { - throw new ModelloRuntimeException( "Illegal argument: outputType == null." ); + if (outputType == null) { + throw new ModelloRuntimeException("Illegal argument: outputType == null."); } - if ( parameters == null ) - { + if (parameters == null) { parameters = new Properties(); } - ModelloGenerator generator = generatorPluginManager.getGeneratorPlugin( outputType ); + ModelloGenerator generator = generatorPluginManager.getGeneratorPlugin(outputType); - generator.generate( model, parameters ); + generator.generate(model, parameters); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/GeneratorPluginManager.java b/modello-core/src/main/java/org/codehaus/modello/core/GeneratorPluginManager.java index e85a79f34..7ee720690 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/GeneratorPluginManager.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/GeneratorPluginManager.java @@ -22,23 +22,22 @@ * SOFTWARE. */ -import org.codehaus.modello.plugin.ModelloGenerator; - import java.util.Iterator; import java.util.Map; +import org.codehaus.modello.plugin.ModelloGenerator; + /** * @author Trygve Laugstøl */ -public interface GeneratorPluginManager -{ +public interface GeneratorPluginManager { String ROLE = GeneratorPluginManager.class.getName(); Map getPlugins(); Iterator getPluginsIterator(); - ModelloGenerator getGeneratorPlugin( String generatorId ); + ModelloGenerator getGeneratorPlugin(String generatorId); - boolean hasGeneratorPlugin( String generatorId ); + boolean hasGeneratorPlugin(String generatorId); } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/MetadataPluginManager.java b/modello-core/src/main/java/org/codehaus/modello/core/MetadataPluginManager.java index 992780874..4a980a867 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/MetadataPluginManager.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/MetadataPluginManager.java @@ -22,23 +22,22 @@ * SOFTWARE. */ -import org.codehaus.modello.metadata.MetadataPlugin; - import java.util.Iterator; import java.util.Map; +import org.codehaus.modello.metadata.MetadataPlugin; + /** * @author Trygve Laugstøl */ -public interface MetadataPluginManager -{ +public interface MetadataPluginManager { String ROLE = MetadataPluginManager.class.getName(); Map getPlugins(); Iterator getPluginsIterator(); - MetadataPlugin getMetadataPlugin( String metadataId ); + MetadataPlugin getMetadataPlugin(String metadataId); - boolean hasMetadataPlugin( String metadataId ); + boolean hasMetadataPlugin(String metadataId); } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/ModelloCore.java b/modello-core/src/main/java/org/codehaus/modello/core/ModelloCore.java index f2ab8d4a6..1f9e5a5eb 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/ModelloCore.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/ModelloCore.java @@ -22,37 +22,32 @@ * SOFTWARE. */ -import org.codehaus.modello.ModelloException; -import org.codehaus.modello.model.Model; -import org.codehaus.modello.model.ModelValidationException; - import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Properties; +import org.codehaus.modello.ModelloException; +import org.codehaus.modello.model.Model; +import org.codehaus.modello.model.ModelValidationException; + /** * @author Trygve Laugstøl */ -public interface ModelloCore -{ +public interface ModelloCore { String ROLE = ModelloCore.class.getName(); MetadataPluginManager getMetadataPluginManager(); - Model loadModel( File file ) - throws IOException, ModelloException, ModelValidationException; - - Model loadModel( Reader reader ) - throws ModelloException, ModelValidationException; + Model loadModel(File file) throws IOException, ModelloException, ModelValidationException; + + Model loadModel(Reader reader) throws ModelloException, ModelValidationException; - void saveModel( Model model, Writer writer ) - throws ModelloException; + void saveModel(Model model, Writer writer) throws ModelloException; - Model translate( Reader reader, String inputType, Properties parameters ) - throws ModelloException, ModelValidationException; + Model translate(Reader reader, String inputType, Properties parameters) + throws ModelloException, ModelValidationException; - void generate( Model model, String outputType, Properties parameters ) - throws ModelloException; + void generate(Model model, String outputType, Properties parameters) throws ModelloException; } diff --git a/modello-core/src/main/java/org/codehaus/modello/core/io/ModelReader.java b/modello-core/src/main/java/org/codehaus/modello/core/io/ModelReader.java index bafb3ab83..e5dcea99a 100644 --- a/modello-core/src/main/java/org/codehaus/modello/core/io/ModelReader.java +++ b/modello-core/src/main/java/org/codehaus/modello/core/io/ModelReader.java @@ -22,6 +22,13 @@ * SOFTWARE. */ +import java.io.IOException; +import java.io.Reader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.BaseElement; import org.codehaus.modello.model.CodeSegment; @@ -37,19 +44,11 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.IOException; -import java.io.Reader; -import java.util.HashMap; -import java.util.Map; -import java.util.ArrayList; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class ModelReader -{ +public class ModelReader { private Map modelAttributes = new HashMap(); private Map> classAttributes = new HashMap>(); @@ -60,405 +59,279 @@ public class ModelReader private Map> associationAttributes = new HashMap>(); - public Map getAttributesForModel() - { + public Map getAttributesForModel() { return modelAttributes; } - public Map getAttributesForClass( ModelClass modelClass ) - { - return classAttributes.get( modelClass.getName() ); + public Map getAttributesForClass(ModelClass modelClass) { + return classAttributes.get(modelClass.getName()); } - public Map getAttributesForInterface( ModelInterface modelInterface ) - { - return interfaceAttributes.get( modelInterface.getName() ); + public Map getAttributesForInterface(ModelInterface modelInterface) { + return interfaceAttributes.get(modelInterface.getName()); } - public Map getAttributesForField( ModelField modelField ) - { - return fieldAttributes.get( modelField.getModelClass().getName() + ':' + modelField.getName() + ':' - + modelField.getVersionRange() ); + public Map getAttributesForField(ModelField modelField) { + return fieldAttributes.get( + modelField.getModelClass().getName() + ':' + modelField.getName() + ':' + modelField.getVersionRange()); } - public Map getAttributesForAssociation( ModelAssociation modelAssociation ) - { - return associationAttributes.get( modelAssociation.getModelClass().getName() + ':' + modelAssociation.getName() - + ':' + modelAssociation.getVersionRange() ); + public Map getAttributesForAssociation(ModelAssociation modelAssociation) { + return associationAttributes.get(modelAssociation.getModelClass().getName() + + ':' + + modelAssociation.getName() + + ':' + + modelAssociation.getVersionRange()); } - public Model loadModel( Reader reader ) - throws ModelloException - { - try - { + public Model loadModel(Reader reader) throws ModelloException { + try { Model model = new Model(); XmlPullParser parser = new MXParser(); - parser.setInput( reader ); + parser.setInput(reader); - parseModel( model, parser ); + parseModel(model, parser); return model; - } - catch ( IOException ex ) - { - throw new ModelloException( "Error parsing the model.", ex ); - } - catch ( XmlPullParserException ex ) - { - throw new ModelloException( "Error parsing the model.", ex ); + } catch (IOException ex) { + throw new ModelloException("Error parsing the model.", ex); + } catch (XmlPullParserException ex) { + throw new ModelloException("Error parsing the model.", ex); } } - public void parseModel( Model model, XmlPullParser parser ) - throws XmlPullParserException, IOException - { + public void parseModel(Model model, XmlPullParser parser) throws XmlPullParserException, IOException { int eventType = parser.getEventType(); - while ( eventType != XmlPullParser.END_DOCUMENT ) - { - if ( eventType == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( model, parser ) ) - { - } - else if ( "id".equals( parser.getName() ) ) - { - model.setId( parser.nextText() ); - } - else if ( "defaults".equals( parser.getName() ) ) - { - parseDefaults( model, parser ); - } - else if ( "versionDefinition".equals( parser.getName() ) ) - { - parseVersionDefinition( model, parser ); - } - else if ( "interfaces".equals( parser.getName() ) ) - { - parseInterfaces( model, parser ); - } - else if ( "classes".equals( parser.getName() ) ) - { - parseClasses( model, parser ); - } - else if ( "model".equals( parser.getName() ) ) - { - modelAttributes = getAttributes( parser ); - } - else - { -// parser.nextText(); + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + if (parseBaseElement(model, parser)) { + } else if ("id".equals(parser.getName())) { + model.setId(parser.nextText()); + } else if ("defaults".equals(parser.getName())) { + parseDefaults(model, parser); + } else if ("versionDefinition".equals(parser.getName())) { + parseVersionDefinition(model, parser); + } else if ("interfaces".equals(parser.getName())) { + parseInterfaces(model, parser); + } else if ("classes".equals(parser.getName())) { + parseClasses(model, parser); + } else if ("model".equals(parser.getName())) { + modelAttributes = getAttributes(parser); + } else { + // parser.nextText(); } } eventType = parser.next(); } } - private void parseDefaults( Model model, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "default".equals( parser.getName() ) ) - { + private void parseDefaults(Model model, XmlPullParser parser) throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("default".equals(parser.getName())) { ModelDefault modelDefault = new ModelDefault(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "key".equals( parser.getName() ) ) - { - modelDefault.setKey( parser.nextText() ); - } - else if ( "value".equals( parser.getName() ) ) - { - modelDefault.setValue( parser.nextText() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("key".equals(parser.getName())) { + modelDefault.setKey(parser.nextText()); + } else if ("value".equals(parser.getName())) { + modelDefault.setValue(parser.nextText()); + } else { parser.nextText(); } } - model.addDefault( modelDefault ); - } - else - { + model.addDefault(modelDefault); + } else { parser.next(); } } } - private void parseVersionDefinition( Model model, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - if ( "versionDefinition".equals( parser.getName() ) ) - { + private void parseVersionDefinition(Model model, XmlPullParser parser) throws XmlPullParserException, IOException { + if ("versionDefinition".equals(parser.getName())) { VersionDefinition versionDefinition = new VersionDefinition(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "type".equals( parser.getName() ) ) - { - versionDefinition.setType( parser.nextText() ); - } - else if ( "value".equals( parser.getName() ) ) - { - versionDefinition.setValue( parser.nextText() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("type".equals(parser.getName())) { + versionDefinition.setType(parser.nextText()); + } else if ("value".equals(parser.getName())) { + versionDefinition.setValue(parser.nextText()); + } else { parser.nextText(); } } - model.setVersionDefinition( versionDefinition ); + model.setVersionDefinition(versionDefinition); } } - private void parseInterfaces( Model model, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "interface".equals( parser.getName() ) ) - { + private void parseInterfaces(Model model, XmlPullParser parser) throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("interface".equals(parser.getName())) { ModelInterface modelInterface = new ModelInterface(); - Map attributes = getAttributes( parser ); - - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( modelInterface, parser ) ) - { - } - else if ( "superInterface".equals( parser.getName() ) ) - { - modelInterface.setSuperInterface( parser.nextText() ); - } - else if ( "packageName".equals( parser.getName() ) ) - { - modelInterface.setPackageName( parser.nextText() ); - } - else if ( "codeSegments".equals( parser.getName() ) ) - { - parseCodeSegment( modelInterface, parser ); - } - else - { + Map attributes = getAttributes(parser); + + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(modelInterface, parser)) { + } else if ("superInterface".equals(parser.getName())) { + modelInterface.setSuperInterface(parser.nextText()); + } else if ("packageName".equals(parser.getName())) { + modelInterface.setPackageName(parser.nextText()); + } else if ("codeSegments".equals(parser.getName())) { + parseCodeSegment(modelInterface, parser); + } else { parser.nextText(); } } - model.addInterface( modelInterface ); - interfaceAttributes.put( modelInterface.getName(), attributes ); - } - else - { + model.addInterface(modelInterface); + interfaceAttributes.put(modelInterface.getName(), attributes); + } else { parser.next(); } } } - private void parseClasses( Model model, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "class".equals( parser.getName() ) ) - { + private void parseClasses(Model model, XmlPullParser parser) throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("class".equals(parser.getName())) { ModelClass modelClass = new ModelClass(); - Map attributes = getAttributes( parser ); - - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( modelClass, parser ) ) - { - } - else if ( "interfaces".equals( parser.getName() ) ) - { - parseClassInterfaces( modelClass, parser ); - } - else if ( "superClass".equals( parser.getName() ) ) - { - modelClass.setSuperClass( parser.nextText() ); - } - else if ( "packageName".equals( parser.getName() ) ) - { - modelClass.setPackageName( parser.nextText() ); - } - else if ( "fields".equals( parser.getName() ) ) - { - parseFields( modelClass, parser ); - } - else if ( "codeSegments".equals( parser.getName() ) ) - { - parseCodeSegment( modelClass, parser ); - } - else - { + Map attributes = getAttributes(parser); + + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(modelClass, parser)) { + } else if ("interfaces".equals(parser.getName())) { + parseClassInterfaces(modelClass, parser); + } else if ("superClass".equals(parser.getName())) { + modelClass.setSuperClass(parser.nextText()); + } else if ("packageName".equals(parser.getName())) { + modelClass.setPackageName(parser.nextText()); + } else if ("fields".equals(parser.getName())) { + parseFields(modelClass, parser); + } else if ("codeSegments".equals(parser.getName())) { + parseCodeSegment(modelClass, parser); + } else { parser.nextText(); } } - model.addClass( modelClass ); - classAttributes.put( modelClass.getName(), attributes ); - } - else - { + model.addClass(modelClass); + classAttributes.put(modelClass.getName(), attributes); + } else { parser.next(); } } } - private void parseClassInterfaces( ModelClass modelClass, XmlPullParser parser ) - throws IOException, XmlPullParserException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "interface".equals( parser.getName() ) ) - { - modelClass.addInterface( parser.nextText() ); - } - else - { + private void parseClassInterfaces(ModelClass modelClass, XmlPullParser parser) + throws IOException, XmlPullParserException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("interface".equals(parser.getName())) { + modelClass.addInterface(parser.nextText()); + } else { parser.nextText(); } } } - private void parseFields( ModelClass modelClass, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "field".equals( parser.getName() ) ) - { + private void parseFields(ModelClass modelClass, XmlPullParser parser) throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("field".equals(parser.getName())) { ModelField modelField = new ModelField(); ModelAssociation modelAssociation = null; - Map fAttributes = getAttributes( parser ); + Map fAttributes = getAttributes(parser); Map aAttributes = new HashMap(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( modelField, parser ) ) - { - } - else if ( "association".equals( parser.getName() ) ) - { - aAttributes = getAttributes( parser ); - - modelAssociation = parseAssociation( parser ); - } - else if ( "alias".equals( parser.getName() ) ) - { - modelField.setAlias( parser.nextText() ); - } - else if ( "type".equals( parser.getName() ) ) - { - modelField.setType( parser.nextText() ); - } - else if ( "defaultValue".equals( parser.getName() ) ) - { - modelField.setDefaultValue( parser.nextText() ); - } - else if ( "typeValidator".equals( parser.getName() ) ) - { - modelField.setTypeValidator( parser.nextText() ); - } - else if ( "required".equals( parser.getName() ) ) - { - modelField.setRequired( Boolean.valueOf( parser.nextText() ) ); - } - else if ( "identifier".equals( parser.getName() ) ) - { - modelField.setIdentifier( Boolean.valueOf( parser.nextText() ).booleanValue() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(modelField, parser)) { + } else if ("association".equals(parser.getName())) { + aAttributes = getAttributes(parser); + + modelAssociation = parseAssociation(parser); + } else if ("alias".equals(parser.getName())) { + modelField.setAlias(parser.nextText()); + } else if ("type".equals(parser.getName())) { + modelField.setType(parser.nextText()); + } else if ("defaultValue".equals(parser.getName())) { + modelField.setDefaultValue(parser.nextText()); + } else if ("typeValidator".equals(parser.getName())) { + modelField.setTypeValidator(parser.nextText()); + } else if ("required".equals(parser.getName())) { + modelField.setRequired(Boolean.valueOf(parser.nextText())); + } else if ("identifier".equals(parser.getName())) { + modelField.setIdentifier( + Boolean.valueOf(parser.nextText()).booleanValue()); + } else { parser.nextText(); } } - if ( modelField.getName() != null ) - { + if (modelField.getName() != null) { fieldAttributes.put( - modelClass.getName() + ":" + modelField.getName() + ":" + modelField.getVersionRange(), - fAttributes ); + modelClass.getName() + ":" + modelField.getName() + ":" + modelField.getVersionRange(), + fAttributes); } - if ( modelAssociation != null ) - { + if (modelAssociation != null) { // Base element - modelAssociation.setName( modelField.getName() ); + modelAssociation.setName(modelField.getName()); - modelAssociation.setDescription( modelField.getDescription() ); + modelAssociation.setDescription(modelField.getDescription()); - modelAssociation.setVersionRange( modelField.getVersionRange() ); + modelAssociation.setVersionRange(modelField.getVersionRange()); - modelAssociation.setComment( modelField.getComment() ); + modelAssociation.setComment(modelField.getComment()); - modelAssociation.setAnnotations( modelField.getAnnotations() ); + modelAssociation.setAnnotations(modelField.getAnnotations()); // model field fields - modelAssociation.setType( modelField.getType() ); + modelAssociation.setType(modelField.getType()); - modelAssociation.setAlias( modelField.getAlias() ); + modelAssociation.setAlias(modelField.getAlias()); - modelAssociation.setDefaultValue( modelField.getDefaultValue() ); + modelAssociation.setDefaultValue(modelField.getDefaultValue()); - modelAssociation.setTypeValidator( modelField.getTypeValidator() ); + modelAssociation.setTypeValidator(modelField.getTypeValidator()); - modelAssociation.setRequired( modelField.isRequired() ); + modelAssociation.setRequired(modelField.isRequired()); - modelAssociation.setIdentifier( modelField.isIdentifier() ); + modelAssociation.setIdentifier(modelField.isIdentifier()); - if ( modelAssociation.getName() != null ) - { - associationAttributes.put( modelClass.getName() + ":" + modelAssociation.getName() + ":" - + modelAssociation.getVersionRange(), aAttributes ); + if (modelAssociation.getName() != null) { + associationAttributes.put( + modelClass.getName() + ":" + modelAssociation.getName() + ":" + + modelAssociation.getVersionRange(), + aAttributes); } - modelClass.addField( modelAssociation ); - } - else - { - modelClass.addField( modelField ); + modelClass.addField(modelAssociation); + } else { + modelClass.addField(modelField); } - } - else - { + } else { parser.next(); } } } - private ModelAssociation parseAssociation( XmlPullParser parser ) - throws XmlPullParserException, IOException - { + private ModelAssociation parseAssociation(XmlPullParser parser) throws XmlPullParserException, IOException { ModelAssociation modelAssociation = new ModelAssociation(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( modelAssociation, parser ) ) - { - } - else if ( "type".equals( parser.getName() ) ) - { - modelAssociation.setTo( parser.nextText() ); - } - else if ( "multiplicity".equals( parser.getName() ) ) - { - modelAssociation.setMultiplicity( parser.nextText() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(modelAssociation, parser)) { + } else if ("type".equals(parser.getName())) { + modelAssociation.setTo(parser.nextText()); + } else if ("multiplicity".equals(parser.getName())) { + modelAssociation.setMultiplicity(parser.nextText()); + } else { parser.nextText(); } } @@ -466,122 +339,84 @@ else if ( "multiplicity".equals( parser.getName() ) ) return modelAssociation; } - private void parseCodeSegment( ModelClass modelClass, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "codeSegment".equals( parser.getName() ) ) - { + private void parseCodeSegment(ModelClass modelClass, XmlPullParser parser) + throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("codeSegment".equals(parser.getName())) { CodeSegment codeSegment = new CodeSegment(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( codeSegment, parser ) ) - { - } - else if ( "code".equals( parser.getName() ) ) - { - codeSegment.setCode( parser.nextText() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(codeSegment, parser)) { + } else if ("code".equals(parser.getName())) { + codeSegment.setCode(parser.nextText()); + } else { parser.nextText(); } } - modelClass.addCodeSegment( codeSegment ); - } - else - { + modelClass.addCodeSegment(codeSegment); + } else { parser.next(); } } } - private void parseCodeSegment( ModelInterface modelInterface, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "codeSegment".equals( parser.getName() ) ) - { + private void parseCodeSegment(ModelInterface modelInterface, XmlPullParser parser) + throws XmlPullParserException, IOException { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("codeSegment".equals(parser.getName())) { CodeSegment codeSegment = new CodeSegment(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( parseBaseElement( codeSegment, parser ) ) - { - } - else if ( "code".equals( parser.getName() ) ) - { - codeSegment.setCode( parser.nextText() ); - } - else - { + while (parser.nextTag() == XmlPullParser.START_TAG) { + if (parseBaseElement(codeSegment, parser)) { + } else if ("code".equals(parser.getName())) { + codeSegment.setCode(parser.nextText()); + } else { parser.nextText(); } } - modelInterface.addCodeSegment( codeSegment ); - } - else - { + modelInterface.addCodeSegment(codeSegment); + } else { parser.next(); } } } - private boolean parseBaseElement( BaseElement element, XmlPullParser parser ) - throws XmlPullParserException, IOException - { - if ( "name".equals( parser.getName() ) ) - { - element.setName( parser.nextText() ); - } - else if ( "description".equals( parser.getName() ) ) - { - element.setDescription( parser.nextText() ); - } - else if ( "version".equals( parser.getName() ) ) - { - element.setVersionRange( new VersionRange( parser.nextText() ) ); - } - else if ( "comment".equals( parser.getName() ) ) - { - element.setComment( parser.nextText() ); - } - else if ( "annotations".equals( parser.getName() ) ) - { + private boolean parseBaseElement(BaseElement element, XmlPullParser parser) + throws XmlPullParserException, IOException { + if ("name".equals(parser.getName())) { + element.setName(parser.nextText()); + } else if ("description".equals(parser.getName())) { + element.setDescription(parser.nextText()); + } else if ("version".equals(parser.getName())) { + element.setVersionRange(new VersionRange(parser.nextText())); + } else if ("comment".equals(parser.getName())) { + element.setComment(parser.nextText()); + } else if ("annotations".equals(parser.getName())) { List annotationsList = new ArrayList(); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "annotation".equals( parser.getName() ) ) - { - annotationsList.add( parser.nextText() ); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("annotation".equals(parser.getName())) { + annotationsList.add(parser.nextText()); } } - element.setAnnotations( annotationsList ); - } - else - { + element.setAnnotations(annotationsList); + } else { return false; } return true; } - private Map getAttributes( XmlPullParser parser ) - { + private Map getAttributes(XmlPullParser parser) { Map attributes = new HashMap(); - for ( int i = 0; i < parser.getAttributeCount(); i++ ) - { - String name = parser.getAttributeName( i ); + for (int i = 0; i < parser.getAttributeCount(); i++) { + String name = parser.getAttributeName(i); - String value = parser.getAttributeValue( i ); + String value = parser.getAttributeValue(i); - attributes.put( name, value ); + attributes.put(name, value); } return attributes; diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/AbstractMetadataPlugin.java b/modello-core/src/main/java/org/codehaus/modello/metadata/AbstractMetadataPlugin.java index 7bdf42bb6..152c67bd0 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/AbstractMetadataPlugin.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/AbstractMetadataPlugin.java @@ -22,34 +22,28 @@ * SOFTWARE. */ +import java.util.Map; + import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.util.StringUtils; -import java.util.Map; - /** * @author Trygve Laugstøl */ -public abstract class AbstractMetadataPlugin - extends AbstractLogEnabled - implements MetadataPlugin -{ - protected boolean getBoolean( Map data, String key, boolean defaultValue ) - { - String value = data.get( key ); - - if ( StringUtils.isEmpty( value ) ) - { +public abstract class AbstractMetadataPlugin extends AbstractLogEnabled implements MetadataPlugin { + protected boolean getBoolean(Map data, String key, boolean defaultValue) { + String value = data.get(key); + + if (StringUtils.isEmpty(value)) { return defaultValue; } - return Boolean.valueOf( value ).booleanValue(); + return Boolean.valueOf(value).booleanValue(); } - protected String getString( Map data, String key ) - { - String value = data.get( key ); + protected String getString(Map data, String key) { + String value = data.get(key); - return StringUtils.isEmpty( value ) ? null : value; + return StringUtils.isEmpty(value) ? null : value; } } diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/AssociationMetadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/AssociationMetadata.java index 23aa2ec6c..dbe59e49c 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/AssociationMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/AssociationMetadata.java @@ -25,7 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface AssociationMetadata - extends Metadata -{ -} +public interface AssociationMetadata extends Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/ClassMetadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/ClassMetadata.java index 282f6e175..c9fb241f6 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/ClassMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/ClassMetadata.java @@ -25,7 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface ClassMetadata - extends Metadata -{ -} +public interface ClassMetadata extends Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/FieldMetadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/FieldMetadata.java index 06e22bec9..fde3d0a86 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/FieldMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/FieldMetadata.java @@ -25,7 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface FieldMetadata - extends Metadata -{ -} +public interface FieldMetadata extends Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/InterfaceMetadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/InterfaceMetadata.java index 83597969c..050a23706 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/InterfaceMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/InterfaceMetadata.java @@ -25,7 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface InterfaceMetadata - extends Metadata -{ -} +public interface InterfaceMetadata extends Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/Metadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/Metadata.java index d3abd580d..353b47568 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/Metadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/Metadata.java @@ -25,6 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface Metadata -{ -} +public interface Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/MetadataPlugin.java b/modello-core/src/main/java/org/codehaus/modello/metadata/MetadataPlugin.java index 8717f6817..27029f424 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/MetadataPlugin.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/MetadataPlugin.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.Map; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -29,27 +31,20 @@ import org.codehaus.modello.model.ModelField; import org.codehaus.modello.model.ModelInterface; -import java.util.Map; - /** * @author Trygve Laugstøl */ -public interface MetadataPlugin -{ +public interface MetadataPlugin { String ROLE = MetadataPlugin.class.getName(); - ModelMetadata getModelMetadata( Model model, Map data ) - throws ModelloException; + ModelMetadata getModelMetadata(Model model, Map data) throws ModelloException; - ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - throws ModelloException; + ClassMetadata getClassMetadata(ModelClass clazz, Map data) throws ModelloException; - InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - throws ModelloException; + InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) throws ModelloException; - FieldMetadata getFieldMetadata( ModelField field, Map data ) - throws ModelloException; + FieldMetadata getFieldMetadata(ModelField field, Map data) throws ModelloException; - AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - throws ModelloException; + AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) + throws ModelloException; } diff --git a/modello-core/src/main/java/org/codehaus/modello/metadata/ModelMetadata.java b/modello-core/src/main/java/org/codehaus/modello/metadata/ModelMetadata.java index 327fcf96b..38ebb690f 100644 --- a/modello-core/src/main/java/org/codehaus/modello/metadata/ModelMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/metadata/ModelMetadata.java @@ -25,7 +25,4 @@ /** * @author Trygve Laugstøl */ -public interface ModelMetadata - extends Metadata -{ -} +public interface ModelMetadata extends Metadata {} diff --git a/modello-core/src/main/java/org/codehaus/modello/model/BaseElement.java b/modello-core/src/main/java/org/codehaus/modello/model/BaseElement.java index d6b620748..828af3522 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/BaseElement.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/BaseElement.java @@ -22,13 +22,13 @@ * SOFTWARE. */ -import org.codehaus.modello.ModelloRuntimeException; -import org.codehaus.modello.metadata.Metadata; - -import java.util.HashMap; -import java.util.Map; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; + +import org.codehaus.modello.ModelloRuntimeException; +import org.codehaus.modello.metadata.Metadata; /** * This is the base class for all elements of the model. The name attribute is immutable because it's used as the key. @@ -37,8 +37,7 @@ * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public abstract class BaseElement -{ +public abstract class BaseElement { private String name; private String description; @@ -47,7 +46,7 @@ public abstract class BaseElement private List annotations = new ArrayList(); - private VersionRange versionRange = new VersionRange( "0.0.0+" ); + private VersionRange versionRange = new VersionRange("0.0.0+"); private Version deprecatedVersion; @@ -55,132 +54,107 @@ public abstract class BaseElement private boolean nameRequired; - public abstract void validateElement() - throws ModelValidationException; + public abstract void validateElement() throws ModelValidationException; - public BaseElement( boolean nameRequired ) - { + public BaseElement(boolean nameRequired) { this.nameRequired = nameRequired; this.name = null; } - public BaseElement( boolean nameRequired, String name ) - { + public BaseElement(boolean nameRequired, String name) { this.nameRequired = nameRequired; this.name = name; } - public String getName() - { + public String getName() { return name; } - public void setName( String name ) - { + public void setName(String name) { this.name = name; } - public String getDescription() - { + public String getDescription() { return description; } - public void setDescription( String description ) - { + public void setDescription(String description) { this.description = description; } - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return versionRange; } - public void setVersionRange( VersionRange versionRange ) - { + public void setVersionRange(VersionRange versionRange) { this.versionRange = versionRange; } - public void setDeprecatedVersion( Version deprecatedVersion ) - { + public void setDeprecatedVersion(Version deprecatedVersion) { this.deprecatedVersion = deprecatedVersion; } - public Version getDeprecatedVersion() - { + public Version getDeprecatedVersion() { return deprecatedVersion; } - public String getComment() - { + public String getComment() { return comment; } - public void setComment( String comment ) - { + public void setComment(String comment) { this.comment = comment; } - public boolean hasMetadata( String key ) - { - return metadata.containsKey( key ); + public boolean hasMetadata(String key) { + return metadata.containsKey(key); } - public void addMetadata( Metadata metadata ) - { - this.metadata.put( metadata.getClass().getName(), metadata ); + public void addMetadata(Metadata metadata) { + this.metadata.put(metadata.getClass().getName(), metadata); } - protected T getMetadata( Class type, String key ) - { - Metadata metadata = this.metadata.get( key ); + protected T getMetadata(Class type, String key) { + Metadata metadata = this.metadata.get(key); - if ( metadata == null ) - { - throw new ModelloRuntimeException( "No such metadata: '" + key + "' for element: '" + getName() + "'." ); + if (metadata == null) { + throw new ModelloRuntimeException("No such metadata: '" + key + "' for element: '" + getName() + "'."); } - if ( !type.isInstance( metadata ) ) - { - throw new ModelloRuntimeException( "The metadata is not of the expected type. Key: '" + key - + "', expected type: '" + type.getName() + "'." ); + if (!type.isInstance(metadata)) { + throw new ModelloRuntimeException("The metadata is not of the expected type. Key: '" + key + + "', expected type: '" + type.getName() + "'."); } - return type.cast( metadata ); + return type.cast(metadata); } // ---------------------------------------------------------------------- // Validation utils // ---------------------------------------------------------------------- - protected void validateFieldNotEmpty( String objectName, String fieldName, String value ) - throws ModelValidationException - { - if ( value == null ) - { - throw new ModelValidationException( "Missing value '" + fieldName + "' from " + objectName + "." ); + protected void validateFieldNotEmpty(String objectName, String fieldName, String value) + throws ModelValidationException { + if (value == null) { + throw new ModelValidationException("Missing value '" + fieldName + "' from " + objectName + "."); } - if ( isEmpty( value ) ) - { - throw new ModelValidationException( "Empty value '" + fieldName + "' from " + objectName + "." ); + if (isEmpty(value)) { + throw new ModelValidationException("Empty value '" + fieldName + "' from " + objectName + "."); } } - public final void validate() - throws ModelValidationException - { - if ( nameRequired ) - { - validateFieldNotEmpty( "Element.name", "name", name ); + public final void validate() throws ModelValidationException { + if (nameRequired) { + validateFieldNotEmpty("Element.name", "name", name); } validateElement(); } - protected boolean isEmpty( String string ) - { + protected boolean isEmpty(String string) { return string == null || string.trim().length() == 0; } @@ -188,29 +162,24 @@ protected boolean isEmpty( String string ) // // ---------------------------------------------------------------------- - public boolean equals( Object other ) - { - if ( other == null || !( other instanceof BaseElement ) ) - { + public boolean equals(Object other) { + if (other == null || !(other instanceof BaseElement)) { return false; } // If we don't know how to identify this object it's not equal to any other object - if ( !nameRequired ) - { + if (!nameRequired) { return false; } BaseElement baseElem = (BaseElement) other; - return name.equals( baseElem.getName() ) && versionRange.equals( baseElem.getVersionRange() ); + return name.equals(baseElem.getName()) && versionRange.equals(baseElem.getVersionRange()); } - public int hashCode() - { - if ( !nameRequired ) - { - return System.identityHashCode( this ); + public int hashCode() { + if (!nameRequired) { + return System.identityHashCode(this); } return name.hashCode() + versionRange.toString().hashCode(); @@ -219,16 +188,14 @@ public int hashCode() /** * @return the annotations */ - public List getAnnotations() - { + public List getAnnotations() { return annotations; } /** * @param annotations the annotations to set */ - public void setAnnotations( List annotations ) - { + public void setAnnotations(List annotations) { this.annotations = annotations; } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/CodeSegment.java b/modello-core/src/main/java/org/codehaus/modello/model/CodeSegment.java index 4371dd2db..64326724c 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/CodeSegment.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/CodeSegment.java @@ -25,27 +25,20 @@ /** * @author Jason van Zyl */ -public class CodeSegment - extends BaseElement -{ +public class CodeSegment extends BaseElement { private String code; - public CodeSegment() - { - super( false ); + public CodeSegment() { + super(false); } - public String getCode() - { + public String getCode() { return code; } - public void setCode( String code ) - { + public void setCode(String code) { this.code = code; } - public void validateElement() - { - } + public void validateElement() {} } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/Model.java b/modello-core/src/main/java/org/codehaus/modello/model/Model.java index 04ffea4d1..68831905e 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/Model.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/Model.java @@ -22,23 +22,21 @@ * SOFTWARE. */ -import org.codehaus.modello.ModelloRuntimeException; -import org.codehaus.modello.metadata.ModelMetadata; -import org.codehaus.modello.plugin.model.ModelClassMetadata; -import org.codehaus.plexus.util.StringUtils; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.codehaus.modello.ModelloRuntimeException; +import org.codehaus.modello.metadata.ModelMetadata; +import org.codehaus.modello.plugin.model.ModelClassMetadata; +import org.codehaus.plexus.util.StringUtils; + /** * @author Jason van Zyl * @author Emmanuel Venisse */ -public class Model - extends BaseElement -{ +public class Model extends BaseElement { private String id; private List classes = new ArrayList<>(); @@ -55,71 +53,55 @@ public class Model private VersionDefinition versionDefinition; - public Model() - { - super( true ); + public Model() { + super(true); } - public String getId() - { + public String getId() { return id; } - public void setId( String id ) - { + public void setId(String id) { this.id = id; } - public VersionDefinition getVersionDefinition() - { + public VersionDefinition getVersionDefinition() { return versionDefinition; } - public void setVersionDefinition( VersionDefinition versionDefinition ) - { + public void setVersionDefinition(VersionDefinition versionDefinition) { this.versionDefinition = versionDefinition; } - public ModelMetadata getMetadata( String key ) - { - return getMetadata( ModelMetadata.class, key ); + public ModelMetadata getMetadata(String key) { + return getMetadata(ModelMetadata.class, key); } - public String getRoot( Version version ) - { - List classes = getClasses( version ); + public String getRoot(Version version) { + List classes = getClasses(version); String className = null; - for ( ModelClass currentClass : classes ) - { + for (ModelClass currentClass : classes) { ModelClassMetadata metadata = null; - try - { - metadata = (ModelClassMetadata) currentClass.getMetadata( ModelClassMetadata.ID ); - } - catch ( Exception e ) - { + try { + metadata = (ModelClassMetadata) currentClass.getMetadata(ModelClassMetadata.ID); + } catch (Exception e) { } - if ( metadata != null && metadata.isRootElement() ) - { - if ( className == null ) - { + if (metadata != null && metadata.isRootElement()) { + if (className == null) { className = currentClass.getName(); - } - else - { + } else { throw new ModelloRuntimeException( - "There are more than one class as root element for this version " + version + "." ); + "There are more than one class as root element for this version " + version + "."); } } } - if ( className == null ) - { - throw new ModelloRuntimeException( "There aren't root element for version " + version + "." ); + if (className == null) { + throw new ModelloRuntimeException("There aren't root element for version " + version + "."); } return className; @@ -134,89 +116,72 @@ public String getRoot( Version version ) * */ @Deprecated - public String getPackageName( boolean withVersion, Version version ) - { - return getDefaultPackageName( withVersion, version ); + public String getPackageName(boolean withVersion, Version version) { + return getDefaultPackageName(withVersion, version); } - public List getAllClasses() - { + public List getAllClasses() { return classes; } - public List getClasses( Version version ) - { + public List getClasses(Version version) { List classList = new ArrayList<>(); - for ( ModelClass currentClass : classes ) - { - if ( version.inside( currentClass.getVersionRange() ) ) - { - classList.add( currentClass ); + for (ModelClass currentClass : classes) { + if (version.inside(currentClass.getVersionRange())) { + classList.add(currentClass); } } return classList; } - public ModelClass getClass( String type, Version version, boolean optionnal ) - { - return getClass( type, new VersionRange( version ), optionnal ); + public ModelClass getClass(String type, Version version, boolean optionnal) { + return getClass(type, new VersionRange(version), optionnal); } - public ModelClass getClass( String type, Version version ) - { - return getClass( type, new VersionRange( version ), false ); + public ModelClass getClass(String type, Version version) { + return getClass(type, new VersionRange(version), false); } - public ModelClass getClass( String type, VersionRange versionRange, boolean optionnal ) - { - ModelClass value = getModelClass( type, versionRange ); + public ModelClass getClass(String type, VersionRange versionRange, boolean optionnal) { + ModelClass value = getModelClass(type, versionRange); - if ( value != null ) - { + if (value != null) { return value; } - if ( optionnal ) - { + if (optionnal) { return null; } throw new ModelloRuntimeException( - "There is no class '" + type + "' in the version range '" + versionRange.toString() + "'." ); + "There is no class '" + type + "' in the version range '" + versionRange.toString() + "'."); } - public ModelClass getClass( String type, VersionRange versionRange ) - { - ModelClass value = getModelClass( type, versionRange ); + public ModelClass getClass(String type, VersionRange versionRange) { + ModelClass value = getModelClass(type, versionRange); - if ( value != null ) - { + if (value != null) { return value; } throw new ModelloRuntimeException( - "There is no class '" + type + "' in the version range '" + versionRange.toString() + "'." ); + "There is no class '" + type + "' in the version range '" + versionRange.toString() + "'."); } - public boolean hasClass( String type, Version version ) - { - ModelClass value = getModelClass( type, new VersionRange( version ) ); + public boolean hasClass(String type, Version version) { + ModelClass value = getModelClass(type, new VersionRange(version)); return value != null; } - private ModelClass getModelClass( String type, VersionRange versionRange ) - { - List classList = classMap.get( type ); + private ModelClass getModelClass(String type, VersionRange versionRange) { + List classList = classMap.get(type); ModelClass value = null; - if ( classList != null ) - { - for ( ModelClass modelClass : classList ) - { - if ( versionRange.getFromVersion().inside( modelClass.getVersionRange() ) - && versionRange.getToVersion().inside( modelClass.getVersionRange() ) ) - { + if (classList != null) { + for (ModelClass modelClass : classList) { + if (versionRange.getFromVersion().inside(modelClass.getVersionRange()) + && versionRange.getToVersion().inside(modelClass.getVersionRange())) { value = modelClass; } } @@ -224,79 +189,63 @@ private ModelClass getModelClass( String type, VersionRange versionRange ) return value; } - public void addClass( ModelClass modelClass ) - { - if ( classMap.containsKey( modelClass.getName() ) ) - { - List classList = classMap.get( modelClass.getName() ); + public void addClass(ModelClass modelClass) { + if (classMap.containsKey(modelClass.getName())) { + List classList = classMap.get(modelClass.getName()); - for ( ModelClass currentClass : classList ) - { - if ( VersionUtil.isInConflict( modelClass.getVersionRange(), currentClass.getVersionRange() ) ) - { - throw new ModelloRuntimeException( "Duplicate class: " + modelClass.getName() + "." ); + for (ModelClass currentClass : classList) { + if (VersionUtil.isInConflict(modelClass.getVersionRange(), currentClass.getVersionRange())) { + throw new ModelloRuntimeException("Duplicate class: " + modelClass.getName() + "."); } } - } - else - { + } else { List classList = new ArrayList<>(); - classMap.put( modelClass.getName(), classList ); + classMap.put(modelClass.getName(), classList); } - getAllClasses().add( modelClass ); + getAllClasses().add(modelClass); - classMap.get( modelClass.getName() ).add( modelClass ); + classMap.get(modelClass.getName()).add(modelClass); } // ---------------------------------------------------------------------- // Defaults // ---------------------------------------------------------------------- - public List getDefaults() - { + public List getDefaults() { return defaults; } - public ModelDefault getDefault( String key ) - { - ModelDefault modelDefault = (ModelDefault) defaultMap.get( key ); + public ModelDefault getDefault(String key) { + ModelDefault modelDefault = (ModelDefault) defaultMap.get(key); - if ( modelDefault == null ) - { - try - { - modelDefault = ModelDefault.getDefault( key ); - } - catch ( ModelValidationException mve ) - { - throw new ModelloRuntimeException( mve.getMessage(), mve ); + if (modelDefault == null) { + try { + modelDefault = ModelDefault.getDefault(key); + } catch (ModelValidationException mve) { + throw new ModelloRuntimeException(mve.getMessage(), mve); } } return modelDefault; } - public void addDefault( ModelDefault modelDefault ) - { - if ( defaultMap.containsKey( modelDefault.getKey() ) ) - { - throw new ModelloRuntimeException( "Duplicate default: " + modelDefault.getKey() + "." ); + public void addDefault(ModelDefault modelDefault) { + if (defaultMap.containsKey(modelDefault.getKey())) { + throw new ModelloRuntimeException("Duplicate default: " + modelDefault.getKey() + "."); } - getDefaults().add( modelDefault ); + getDefaults().add(modelDefault); - defaultMap.put( modelDefault.getKey(), modelDefault ); + defaultMap.put(modelDefault.getKey(), modelDefault); } - public String getDefaultPackageName( boolean withVersion, Version version ) - { - String packageName = getDefault( ModelDefault.PACKAGE ).getValue(); + public String getDefaultPackageName(boolean withVersion, Version version) { + String packageName = getDefault(ModelDefault.PACKAGE).getValue(); - if ( withVersion ) - { - packageName += "." + version.toString( "v", "_" ); + if (withVersion) { + packageName += "." + version.toString("v", "_"); } return packageName; @@ -306,55 +255,44 @@ public String getDefaultPackageName( boolean withVersion, Version version ) // // ---------------------------------------------------------------------- - public List getAllInterfaces() - { + public List getAllInterfaces() { return interfaces; } - public List getInterfaces( Version version ) - { + public List getInterfaces(Version version) { List interfaceList = new ArrayList<>(); - for ( ModelInterface currentInterface : interfaces ) - { - if ( version.inside( currentInterface.getVersionRange() ) ) - { - interfaceList.add( currentInterface ); + for (ModelInterface currentInterface : interfaces) { + if (version.inside(currentInterface.getVersionRange())) { + interfaceList.add(currentInterface); } } return interfaceList; } - public ModelInterface getInterface( String type, Version version ) - { - return getInterface( type, new VersionRange( version ) ); + public ModelInterface getInterface(String type, Version version) { + return getInterface(type, new VersionRange(version)); } - public ModelInterface getInterface( String type, VersionRange versionRange ) - { - ModelInterface value = getModelInterface( type, versionRange ); + public ModelInterface getInterface(String type, VersionRange versionRange) { + ModelInterface value = getModelInterface(type, versionRange); - if ( value != null ) - { + if (value != null) { return value; } throw new ModelloRuntimeException( - "There is no interface '" + type + "' in the version range '" + versionRange.toString() + "'." ); + "There is no interface '" + type + "' in the version range '" + versionRange.toString() + "'."); } - private ModelInterface getModelInterface( String type, VersionRange versionRange ) - { - List interfaceList = interfaceMap.get( type ); + private ModelInterface getModelInterface(String type, VersionRange versionRange) { + List interfaceList = interfaceMap.get(type); - if ( interfaceList != null ) - { - for ( ModelInterface modelInterface : interfaceList ) - { - if ( versionRange.getFromVersion().inside( modelInterface.getVersionRange() ) - && versionRange.getToVersion().inside( modelInterface.getVersionRange() ) ) - { + if (interfaceList != null) { + for (ModelInterface modelInterface : interfaceList) { + if (versionRange.getFromVersion().inside(modelInterface.getVersionRange()) + && versionRange.getToVersion().inside(modelInterface.getVersionRange())) { return modelInterface; } } @@ -363,95 +301,74 @@ private ModelInterface getModelInterface( String type, VersionRange versionRange return null; } - public void addInterface( ModelInterface modelInterface ) - { - if ( interfaceMap.containsKey( modelInterface.getName() ) ) - { - List interfaceList = interfaceMap.get( modelInterface.getName() ); + public void addInterface(ModelInterface modelInterface) { + if (interfaceMap.containsKey(modelInterface.getName())) { + List interfaceList = interfaceMap.get(modelInterface.getName()); - for ( ModelInterface currentInterface : interfaceList ) - { - if ( VersionUtil.isInConflict( modelInterface.getVersionRange(), currentInterface.getVersionRange() ) ) - { - throw new ModelloRuntimeException( "Duplicate interface: " + modelInterface.getName() + "." ); + for (ModelInterface currentInterface : interfaceList) { + if (VersionUtil.isInConflict(modelInterface.getVersionRange(), currentInterface.getVersionRange())) { + throw new ModelloRuntimeException("Duplicate interface: " + modelInterface.getName() + "."); } } - } - else - { + } else { List interfaceList = new ArrayList<>(); - interfaceMap.put( modelInterface.getName(), interfaceList ); + interfaceMap.put(modelInterface.getName(), interfaceList); } - getAllInterfaces().add( modelInterface ); + getAllInterfaces().add(modelInterface); - interfaceMap.get( modelInterface.getName() ).add( modelInterface ); + interfaceMap.get(modelInterface.getName()).add(modelInterface); } - public ModelType getType( String type, Version version ) - { - return getType( type, new VersionRange( version ) ); + public ModelType getType(String type, Version version) { + return getType(type, new VersionRange(version)); } - public ModelType getType( String type, VersionRange versionRange ) - { - ModelType value = getModelClass( type, versionRange ); + public ModelType getType(String type, VersionRange versionRange) { + ModelType value = getModelClass(type, versionRange); - if ( value != null ) - { + if (value != null) { return value; } - value = getModelInterface( type, versionRange ); + value = getModelInterface(type, versionRange); - if ( value != null ) - { + if (value != null) { return value; } - throw new ModelloRuntimeException( - "There is no class or interface '" + type + "' in the version range '" + versionRange.toString() + "'." ); + throw new ModelloRuntimeException("There is no class or interface '" + type + "' in the version range '" + + versionRange.toString() + "'."); } - public void initialize() - { - for ( ModelClass modelClass : classes ) - { - modelClass.initialize( this ); + public void initialize() { + for (ModelClass modelClass : classes) { + modelClass.initialize(this); } - for ( ModelInterface modelInterface : interfaces ) - { - modelInterface.initialize( this ); + for (ModelInterface modelInterface : interfaces) { + modelInterface.initialize(this); } } - public void validateElement() - { - } + public void validateElement() {} - public ModelClass getLocationTracker( Version version ) - { - List modelClasses = getClasses( version ); + public ModelClass getLocationTracker(Version version) { + List modelClasses = getClasses(version); ModelClass locationTracker = null; - for ( ModelClass modelClass : modelClasses ) - { - ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + for (ModelClass modelClass : modelClasses) { + ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); - if ( metadata != null && StringUtils.isNotEmpty( metadata.getLocationTracker() ) ) - { - if ( locationTracker == null ) - { + if (metadata != null && StringUtils.isNotEmpty(metadata.getLocationTracker())) { + if (locationTracker == null) { locationTracker = modelClass; - } - else - { + } else { throw new ModelloRuntimeException( - "There are multiple location tracker classes (" + locationTracker.getName() + " vs. " - + modelClass.getName() + ") for this version " + version + "." ); + "There are multiple location tracker classes (" + locationTracker.getName() + " vs. " + + modelClass.getName() + ") for this version " + version + "."); } } } @@ -459,32 +376,25 @@ public ModelClass getLocationTracker( Version version ) return locationTracker; } - public ModelClass getSourceTracker( Version version ) - { - List modelClasses = getClasses( version ); + public ModelClass getSourceTracker(Version version) { + List modelClasses = getClasses(version); ModelClass sourceTracker = null; - for ( ModelClass modelClass : modelClasses ) - { - ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + for (ModelClass modelClass : modelClasses) { + ModelClassMetadata metadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); - if ( metadata != null && StringUtils.isNotEmpty( metadata.getSourceTracker() ) ) - { - if ( sourceTracker == null ) - { + if (metadata != null && StringUtils.isNotEmpty(metadata.getSourceTracker())) { + if (sourceTracker == null) { sourceTracker = modelClass; - } - else - { + } else { throw new ModelloRuntimeException( - "There are multiple source tracker classes (" + sourceTracker.getName() + " vs. " - + modelClass.getName() + ") for this version " + version + "." ); + "There are multiple source tracker classes (" + sourceTracker.getName() + " vs. " + + modelClass.getName() + ") for this version " + version + "."); } } } return sourceTracker; } - } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelAssociation.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelAssociation.java index f5904270e..51ab63f92 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelAssociation.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelAssociation.java @@ -29,9 +29,7 @@ * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class ModelAssociation - extends ModelField -{ +public class ModelAssociation extends ModelField { public static final String ONE_MULTIPLICITY = "1"; public static final String MANY_MULTIPLICITY = "*"; @@ -53,27 +51,21 @@ public class ModelAssociation /** * @param to The to to set. */ - public void setTo( String to ) - { + public void setTo(String to) { this.to = to; } /** * @return Returns the to. */ - public String getTo() - { + public String getTo() { return to; } - public String getType() - { - if ( ONE_MULTIPLICITY.equals( getMultiplicity() ) ) - { + public String getType() { + if (ONE_MULTIPLICITY.equals(getMultiplicity())) { return getTo(); - } - else - { + } else { return super.getType(); } } @@ -81,142 +73,111 @@ public String getType() /** * @return Returns the multiplicity. */ - public String getMultiplicity() - { + public String getMultiplicity() { return multiplicity; } /** * @param multiplicity The multiplicity to set. */ - public void setMultiplicity( String multiplicity ) - { + public void setMultiplicity(String multiplicity) { this.multiplicity = multiplicity; } - public boolean isManyMultiplicity() - { - return MANY_MULTIPLICITY.equals( multiplicity ); + public boolean isManyMultiplicity() { + return MANY_MULTIPLICITY.equals(multiplicity); } - public boolean isOneMultiplicity() - { - return ONE_MULTIPLICITY.equals( multiplicity ); + public boolean isOneMultiplicity() { + return ONE_MULTIPLICITY.equals(multiplicity); } /** * @return Returns the to ModelClass. */ - public ModelClass getToClass() - { + public ModelClass getToClass() { return toClass; } - public AssociationMetadata getAssociationMetadata( String key ) - { - return getMetadata( AssociationMetadata.class, key ); + public AssociationMetadata getAssociationMetadata(String key) { + return getMetadata(AssociationMetadata.class, key); } // ---------------------------------------------------------------------- // BaseElement overrides // ---------------------------------------------------------------------- - public void validateElement() - throws ModelValidationException - { - validateFieldNotEmpty( "Association", "name", getName() ); + public void validateElement() throws ModelValidationException { + validateFieldNotEmpty("Association", "name", getName()); - validateFieldNotEmpty( "Association '" + getName() + "'", "to", to ); + validateFieldNotEmpty("Association '" + getName() + "'", "to", to); - if ( isEmpty( to ) ) - { - throw new ModelValidationException( "You must define the type of association." ); + if (isEmpty(to)) { + throw new ModelValidationException("You must define the type of association."); } - if ( !"String".equals( to ) ) - { - toClass = getModelClass().getModel().getClass( to, getVersionRange() ); + if (!"String".equals(to)) { + toClass = getModelClass().getModel().getClass(to, getVersionRange()); - if ( toClass == null ) - { - throw new ModelValidationException( "Association '" + getName() + "': Could not find to class." ); + if (toClass == null) { + throw new ModelValidationException("Association '" + getName() + "': Could not find to class."); } } - if ( isEmpty( multiplicity ) ) - { + if (isEmpty(multiplicity)) { multiplicity = ONE_MULTIPLICITY; } - if ( "n".equals( multiplicity ) || "*".equals( multiplicity ) ) - { + if ("n".equals(multiplicity) || "*".equals(multiplicity)) { multiplicity = MANY_MULTIPLICITY; } - if ( !ONE_MULTIPLICITY.equals( multiplicity ) && !MANY_MULTIPLICITY.equals( multiplicity ) ) - { - throw new ModelValidationException( "Association multiplicity '" + getName() + "' is incorrect: " - + "Possible values are '1', '*' or 'n'." ); + if (!ONE_MULTIPLICITY.equals(multiplicity) && !MANY_MULTIPLICITY.equals(multiplicity)) { + throw new ModelValidationException("Association multiplicity '" + getName() + "' is incorrect: " + + "Possible values are '1', '*' or 'n'."); } - if ( isEmpty( getType() ) ) - { - ModelDefault modelDefault = getModelClass().getModel().getDefault( ModelDefault.LIST ); - - setType( modelDefault.getKey() ); - - setDefaultValue( getDefaultValue( modelDefault ) ); - } - else - { - if ( isManyMultiplicity() ) - { - if ( "Set".equalsIgnoreCase( getType() ) ) - { - setType( ModelDefault.SET ); - } - else if ( "List".equalsIgnoreCase( getType() ) ) - { - setType( ModelDefault.LIST ); - } - else if ( "Map".equalsIgnoreCase( getType() ) ) - { - setType( ModelDefault.MAP ); - } - else if ( "Properties".equalsIgnoreCase( getType() ) ) - { - setType( ModelDefault.PROPERTIES ); - } - else - { + if (isEmpty(getType())) { + ModelDefault modelDefault = getModelClass().getModel().getDefault(ModelDefault.LIST); + + setType(modelDefault.getKey()); + + setDefaultValue(getDefaultValue(modelDefault)); + } else { + if (isManyMultiplicity()) { + if ("Set".equalsIgnoreCase(getType())) { + setType(ModelDefault.SET); + } else if ("List".equalsIgnoreCase(getType())) { + setType(ModelDefault.LIST); + } else if ("Map".equalsIgnoreCase(getType())) { + setType(ModelDefault.MAP); + } else if ("Properties".equalsIgnoreCase(getType())) { + setType(ModelDefault.PROPERTIES); + } else { throw new ModelValidationException( - "The type of element '" + getName() + "' must be List, Map, Properties or Set." ); + "The type of element '" + getName() + "' must be List, Map, Properties or Set."); } - if ( isEmpty( getDefaultValue() ) ) - { - ModelDefault modelDefault = getModelClass().getModel().getDefault( getType() ); + if (isEmpty(getDefaultValue())) { + ModelDefault modelDefault = getModelClass().getModel().getDefault(getType()); -// setType( modelDefault.getKey() ); + // setType( modelDefault.getKey() ); - setDefaultValue( getDefaultValue( modelDefault ) ); + setDefaultValue(getDefaultValue(modelDefault)); } } } } - public boolean isGenericType() - { - return getType().equals( ModelDefault.LIST ) || getType().equals( ModelDefault.SET ); + public boolean isGenericType() { + return getType().equals(ModelDefault.LIST) || getType().equals(ModelDefault.SET); } - private String getDefaultValue( ModelDefault modelDefault ) - { + private String getDefaultValue(ModelDefault modelDefault) { String value = modelDefault.getValue(); - if ( isGenericType() ) - { - value = StringUtils.replace( value, "", "/*<" + getTo() + ">*/" ); + if (isGenericType()) { + value = StringUtils.replace(value, "", "/*<" + getTo() + ">*/"); } return value; diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelClass.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelClass.java index 163c8be01..f68065fc1 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelClass.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelClass.java @@ -22,22 +22,20 @@ * SOFTWARE. */ -import org.codehaus.modello.ModelloRuntimeException; -import org.codehaus.modello.metadata.ClassMetadata; -import org.codehaus.plexus.util.StringUtils; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.codehaus.modello.ModelloRuntimeException; +import org.codehaus.modello.metadata.ClassMetadata; +import org.codehaus.plexus.util.StringUtils; + /** * @author Jason van Zyl * @author Emmanuel Venisse */ -public class ModelClass - extends ModelType -{ +public class ModelClass extends ModelType { private String superClass; private boolean isInternalSuperClass; @@ -48,23 +46,19 @@ public class ModelClass private transient Map> fieldMap = new HashMap>(); - public ModelClass() - { + public ModelClass() { super(); } - public ModelClass( Model model, String name ) - { - super( model, name ); + public ModelClass(Model model, String name) { + super(model, name); } - public String getSuperClass() - { + public String getSuperClass() { return superClass; } - public void setSuperClass( String superClass ) - { + public void setSuperClass(String superClass) { this.superClass = superClass; } @@ -77,24 +71,20 @@ public void setSuperClass( String superClass ) * * @return Returns the list of all interfaces of this class. */ - public List getInterfaces() - { - if ( interfaces == null ) - { + public List getInterfaces() { + if (interfaces == null) { interfaces = new ArrayList(); } return interfaces; } - public void addInterface( String modelInterface ) - { - if ( getInterfaces().contains( modelInterface ) ) - { - throw new ModelloRuntimeException( "Duplicate interface in " + getName() + ": " + modelInterface + "." ); + public void addInterface(String modelInterface) { + if (getInterfaces().contains(modelInterface)) { + throw new ModelloRuntimeException("Duplicate interface in " + getName() + ": " + modelInterface + "."); } - getInterfaces().add( modelInterface ); + getInterfaces().add(modelInterface); } // ---------------------------------------------------------------------- @@ -104,10 +94,8 @@ public void addInterface( String modelInterface ) /** * {@inheritDoc} */ - public List getAllFields() - { - if ( fields == null ) - { + public List getAllFields() { + if (fields == null) { fields = new ArrayList(); } @@ -119,22 +107,19 @@ public List getAllFields() * * @return Returns all the fields in this class and all super classes. */ - public List getAllFields( boolean withInheritedField ) - { - if ( ! withInheritedField ) - { + public List getAllFields(boolean withInheritedField) { + if (!withInheritedField) { return getAllFields(); } - List fields = new ArrayList( getAllFields() ); + List fields = new ArrayList(getAllFields()); ModelClass c = this; - while ( c.hasSuperClass() && c.isInternalSuperClass() ) - { - ModelClass parent = getModel().getClass( c.getSuperClass(), getVersionRange() ); + while (c.hasSuperClass() && c.isInternalSuperClass()) { + ModelClass parent = getModel().getClass(c.getSuperClass(), getVersionRange()); - fields.addAll( parent.getAllFields() ); + fields.addAll(parent.getAllFields()); c = parent; } @@ -142,103 +127,82 @@ public List getAllFields( boolean withInheritedField ) return fields; } - public ModelField getField( String type, VersionRange versionRange ) - { - List fieldList = fieldMap.get( type ); - - if ( fieldList != null ) - { - for ( ModelField modelField : fieldList ) - { - if ( versionRange.getFromVersion().inside( modelField.getVersionRange() ) - && versionRange.getToVersion().inside( modelField.getVersionRange() ) ) - { + public ModelField getField(String type, VersionRange versionRange) { + List fieldList = fieldMap.get(type); + + if (fieldList != null) { + for (ModelField modelField : fieldList) { + if (versionRange.getFromVersion().inside(modelField.getVersionRange()) + && versionRange.getToVersion().inside(modelField.getVersionRange())) { return modelField; } } } - throw new ModelloRuntimeException( "There are no field '" + type + "' in version range '" + versionRange.toString() + "'." ); + throw new ModelloRuntimeException( + "There are no field '" + type + "' in version range '" + versionRange.toString() + "'."); } - public void addField( ModelField modelField ) - { - if ( fieldMap.containsKey( modelField.getName() ) ) - { - List fieldList = fieldMap.get( modelField.getName() ); - - for ( ModelField currentField : fieldList ) - { - if ( VersionUtil.isInConflict( modelField.getVersionRange(), currentField.getVersionRange() ) ) - { - throw new ModelloRuntimeException( "Duplicate field in " + getName() + ": " + modelField.getName() + "." ); + public void addField(ModelField modelField) { + if (fieldMap.containsKey(modelField.getName())) { + List fieldList = fieldMap.get(modelField.getName()); + + for (ModelField currentField : fieldList) { + if (VersionUtil.isInConflict(modelField.getVersionRange(), currentField.getVersionRange())) { + throw new ModelloRuntimeException( + "Duplicate field in " + getName() + ": " + modelField.getName() + "."); } } - } - else - { + } else { List fieldList = new ArrayList(); - fieldMap.put( modelField.getName(), fieldList ); + fieldMap.put(modelField.getName(), fieldList); } - getAllFields().add( modelField ); + getAllFields().add(modelField); - fieldMap.get( modelField.getName() ).add( modelField ); + fieldMap.get(modelField.getName()).add(modelField); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - public boolean hasSuperClass() - { - return StringUtils.isNotEmpty( superClass ); + public boolean hasSuperClass() { + return StringUtils.isNotEmpty(superClass); } - public boolean isInternalSuperClass() - { + public boolean isInternalSuperClass() { return isInternalSuperClass; } - public ClassMetadata getMetadata( String key ) - { - return getMetadata( ClassMetadata.class, key ); + public ClassMetadata getMetadata(String key) { + return getMetadata(ClassMetadata.class, key); } - public void initialize( Model model ) - { - super.initialize( model ); + public void initialize(Model model) { + super.initialize(model); - for ( ModelField modelField : getAllFields() ) - { - modelField.initialize( this ); + for (ModelField modelField : getAllFields()) { + modelField.initialize(this); } } - public void validateElement() - throws ModelValidationException - { + public void validateElement() throws ModelValidationException { // Check if superClass exists - if ( hasSuperClass() ) - { - try - { - getModel().getClass( superClass, getVersionRange() ); + if (hasSuperClass()) { + try { + getModel().getClass(superClass, getVersionRange()); isInternalSuperClass = true; - } - catch ( ModelloRuntimeException e ) - { + } catch (ModelloRuntimeException e) { isInternalSuperClass = false; } } - if ( getModel().getDefault( ModelDefault.CHECK_DEPRECATION ).getBoolean() ) - { - if ( ! Version.INFINITE.equals( getVersionRange().getToVersion() ) - && getDeprecatedVersion() == null ) - { - throw new ModelValidationException( "You must define the deprecated version of '" + getName() + "' class." ); + if (getModel().getDefault(ModelDefault.CHECK_DEPRECATION).getBoolean()) { + if (!Version.INFINITE.equals(getVersionRange().getToVersion()) && getDeprecatedVersion() == null) { + throw new ModelValidationException( + "You must define the deprecated version of '" + getName() + "' class."); } } } @@ -247,30 +211,24 @@ && getDeprecatedVersion() == null ) // Object Overrides // ---------------------------------------------------------------------- - public boolean equals( Object o ) - { - if ( ! super.equals( o ) ) - { + public boolean equals(Object o) { + if (!super.equals(o)) { return false; } - if ( !( o instanceof ModelClass ) ) - { + if (!(o instanceof ModelClass)) { return false; } ModelClass other = (ModelClass) o; - return getPackageName().equals( other.getPackageName() ); - + return getPackageName().equals(other.getPackageName()); } - public int hashCode() - { + public int hashCode() { int hashCode = getName().hashCode(); - if ( !StringUtils.isEmpty( getPackageName() ) ) - { + if (!StringUtils.isEmpty(getPackageName())) { hashCode += 37 * getPackageName().hashCode(); } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelDefault.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelDefault.java index 6272e6245..9ab8e4efc 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelDefault.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelDefault.java @@ -27,8 +27,7 @@ * * @author Emmanuel Venisse */ -public class ModelDefault -{ +public class ModelDefault { public static final String CHECK_DEPRECATION = "checkDeprecation"; public static final String CHECK_DEPRECATION_VALUE = "false"; @@ -61,107 +60,79 @@ public class ModelDefault private String value; - public static ModelDefault getDefault( String key ) - throws ModelValidationException - { - validateKey( key ); + public static ModelDefault getDefault(String key) throws ModelValidationException { + validateKey(key); ModelDefault modelDefault = new ModelDefault(); - modelDefault.setKey( key ); - - if ( CHECK_DEPRECATION.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( CHECK_DEPRECATION_VALUE ); - } - else if ( PACKAGE.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( PACKAGE_VALUE ); - } - else if ( LIST.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( LIST_VALUE ); - } - else if ( MAP.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( MAP_VALUE ); - } - else if ( PROPERTIES.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( PROPERTIES_VALUE ); - } - else if ( SET.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( SET_VALUE ); - } - else if ( STRICT_XML_ATTRIBUTES.equalsIgnoreCase( key ) ) - { - modelDefault.setValue( STRICT_XML_ATTRIBUTES_VALUE ); + modelDefault.setKey(key); + + if (CHECK_DEPRECATION.equalsIgnoreCase(key)) { + modelDefault.setValue(CHECK_DEPRECATION_VALUE); + } else if (PACKAGE.equalsIgnoreCase(key)) { + modelDefault.setValue(PACKAGE_VALUE); + } else if (LIST.equalsIgnoreCase(key)) { + modelDefault.setValue(LIST_VALUE); + } else if (MAP.equalsIgnoreCase(key)) { + modelDefault.setValue(MAP_VALUE); + } else if (PROPERTIES.equalsIgnoreCase(key)) { + modelDefault.setValue(PROPERTIES_VALUE); + } else if (SET.equalsIgnoreCase(key)) { + modelDefault.setValue(SET_VALUE); + } else if (STRICT_XML_ATTRIBUTES.equalsIgnoreCase(key)) { + modelDefault.setValue(STRICT_XML_ATTRIBUTES_VALUE); } return modelDefault; } - public void setKey( String key ) - { + public void setKey(String key) { this.key = key; } - public String getKey() - { + public String getKey() { return key; } - public void setValue( String value ) - { + public void setValue(String value) { this.value = value; } - public String getValue() - { + public String getValue() { return value; } - public boolean getBoolean() - { - return Boolean.valueOf( value ).booleanValue(); + public boolean getBoolean() { + return Boolean.valueOf(value).booleanValue(); } - public void validateElement() - throws ModelValidationException - { - if ( isEmpty( key ) ) - { - throw new ModelValidationException( "You must define the key of default element." ); + public void validateElement() throws ModelValidationException { + if (isEmpty(key)) { + throw new ModelValidationException("You must define the key of default element."); } - if ( isEmpty( value ) ) - { - throw new ModelValidationException( "You must define the value of default element." ); + if (isEmpty(value)) { + throw new ModelValidationException("You must define the value of default element."); } - validateKey( key ); + validateKey(key); } - private static void validateKey( String key ) - throws ModelValidationException - { - if ( ! SET.equalsIgnoreCase( key ) - && ! LIST.equalsIgnoreCase( key ) - && ! MAP.equalsIgnoreCase( key ) - && ! PROPERTIES.equalsIgnoreCase( key ) - && ! CHECK_DEPRECATION.equalsIgnoreCase( key ) - && ! PACKAGE.equalsIgnoreCase( key ) - && ! STRICT_XML_ATTRIBUTES.equalsIgnoreCase( key ) ) - { - throw new ModelValidationException( "The key of default element must be ' " + SET + "', '" + LIST + "', '" - + MAP + "', '" + PROPERTIES + "', '" + CHECK_DEPRECATION + "', '" + PACKAGE + "' or '" - + STRICT_XML_ATTRIBUTES + "', was '" + key + "'." ); + private static void validateKey(String key) throws ModelValidationException { + if (!SET.equalsIgnoreCase(key) + && !LIST.equalsIgnoreCase(key) + && !MAP.equalsIgnoreCase(key) + && !PROPERTIES.equalsIgnoreCase(key) + && !CHECK_DEPRECATION.equalsIgnoreCase(key) + && !PACKAGE.equalsIgnoreCase(key) + && !STRICT_XML_ATTRIBUTES.equalsIgnoreCase(key)) { + throw new ModelValidationException("The key of default element must be ' " + SET + "', '" + LIST + "', '" + + MAP + "', '" + PROPERTIES + "', '" + CHECK_DEPRECATION + "', '" + PACKAGE + "' or '" + + STRICT_XML_ATTRIBUTES + "', was '" + key + "'."); } } - protected boolean isEmpty( String string ) - { + protected boolean isEmpty(String string) { return string == null || string.trim().length() == 0; } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelField.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelField.java index abb49707d..32c0ca6f6 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelField.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelField.java @@ -28,9 +28,7 @@ * @author Jason van Zyl * @author Emmanuel Venisse */ -public class ModelField - extends BaseElement -{ +public class ModelField extends BaseElement { private String type; private String defaultValue; @@ -45,18 +43,34 @@ public class ModelField private transient ModelClass modelClass; - private static final String[] PRIMITIVE_TYPES = - { "boolean", "Boolean", "char", "Character", "byte", "Byte", "short", "Short", "int", "Integer", "long", - "Long", "float", "Float", "double", "Double", "String", "Date", "DOM" }; - - public ModelField() - { - super( true ); - } - - public ModelField( ModelClass modelClass, String name ) - { - super( true, name ); + private static final String[] PRIMITIVE_TYPES = { + "boolean", + "Boolean", + "char", + "Character", + "byte", + "Byte", + "short", + "Short", + "int", + "Integer", + "long", + "Long", + "float", + "Float", + "double", + "Double", + "String", + "Date", + "DOM" + }; + + public ModelField() { + super(true); + } + + public ModelField(ModelClass modelClass, String name) { + super(true, name); this.modelClass = modelClass; } @@ -65,93 +79,75 @@ public ModelField( ModelClass modelClass, String name ) // Property accessors // ---------------------------------------------------------------------- - public String getType() - { + public String getType() { return type; } - public void setType( String type ) - { + public void setType(String type) { this.type = type; } - public String getDefaultValue() - { + public String getDefaultValue() { return defaultValue; } - public void setDefaultValue( String defaultValue ) - { + public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } - public String getTypeValidator() - { + public String getTypeValidator() { return typeValidator; } - public void setTypeValidator( String typeValidator ) - { + public void setTypeValidator(String typeValidator) { this.typeValidator = typeValidator; } - public boolean isRequired() - { + public boolean isRequired() { return required; } - public void setRequired( boolean required ) - { + public void setRequired(boolean required) { this.required = required; } - public boolean isIdentifier() - { + public boolean isIdentifier() { return identifier; } - public void setIdentifier( boolean identifier ) - { + public void setIdentifier(boolean identifier) { this.identifier = identifier; } - public String getAlias() - { + public String getAlias() { return alias; } - public void setAlias( String alias ) - { + public void setAlias(String alias) { this.alias = alias; } // ---------------------------------------------------------------------- // Misc // ---------------------------------------------------------------------- - public ModelClass getModelClass() - { + public ModelClass getModelClass() { return modelClass; } - public FieldMetadata getMetadata( String key ) - { - return getMetadata( FieldMetadata.class, key ); + public FieldMetadata getMetadata(String key) { + return getMetadata(FieldMetadata.class, key); } - public boolean isPrimitive() - { + public boolean isPrimitive() { String type = getType(); // TODO: This should not happen - if ( type == null ) - { + if (type == null) { return false; } - for ( String validType : PRIMITIVE_TYPES ) - { - if ( type.equals( validType ) ) - { + for (String validType : PRIMITIVE_TYPES) { + if (type.equals(validType)) { return true; } } @@ -159,21 +155,17 @@ public boolean isPrimitive() return false; } - public boolean isArray() - { - return getType().endsWith( "[]" ); + public boolean isArray() { + return getType().endsWith("[]"); } - public boolean isPrimitiveArray() - { + public boolean isPrimitiveArray() { String type = getType(); - for ( String PRIMITIVE_TYPE : PRIMITIVE_TYPES ) - { + for (String PRIMITIVE_TYPE : PRIMITIVE_TYPES) { String validType = PRIMITIVE_TYPE + "[]"; - if ( validType.equals( type ) ) - { + if (validType.equals(type)) { return true; } } @@ -185,43 +177,31 @@ public boolean isPrimitiveArray() // BaseElement Overrides // ---------------------------------------------------------------------- - public void initialize( ModelClass modelClass ) - { + public void initialize(ModelClass modelClass) { this.modelClass = modelClass; - if ( defaultValue == null ) - { - if ( "boolean".equals( type ) ) - { + if (defaultValue == null) { + if ("boolean".equals(type)) { defaultValue = "false"; - } - else if ( "float".equals( type ) || "double".equals( type ) ) - { + } else if ("float".equals(type) || "double".equals(type)) { defaultValue = "0.0"; - } - else if ( "int".equals( type ) || "long".equals( type ) || "short".equals( type ) || "byte".equals( type ) ) - { + } else if ("int".equals(type) || "long".equals(type) || "short".equals(type) || "byte".equals(type)) { defaultValue = "0"; - } - else if ( "char".equals( type ) ) - { + } else if ("char".equals(type)) { defaultValue = "\0"; } } } - public void validateElement() - throws ModelValidationException - { - validateFieldNotEmpty( "field", "name", getName() ); + public void validateElement() throws ModelValidationException { + validateFieldNotEmpty("field", "name", getName()); - validateFieldNotEmpty( "field '" + getName() + "'", "type", type ); + validateFieldNotEmpty("field '" + getName() + "'", "type", type); // TODO: these definitions are duplicated throughout. Defined centrally, and loop through in the various uses - if ( !isPrimitive() && !isPrimitiveArray() ) - { - throw new ModelValidationException( "Field '" + getName() + "': Illegal type: '" + type + "'." ); + if (!isPrimitive() && !isPrimitiveArray()) { + throw new ModelValidationException("Field '" + getName() + "': Illegal type: '" + type + "'."); } } @@ -229,18 +209,18 @@ public void validateElement() // Object Overrides // ---------------------------------------------------------------------- - public String toString() - { + public String toString() { return "[Field: name=" + getName() + ", alias: " + alias + ", type: " + type + ", " + "version: " - + getVersionRange() + "]"; + + getVersionRange() + "]"; } - public boolean isModelVersionField() - { + public boolean isModelVersionField() { Model model = modelClass.getModel(); VersionDefinition versionDefinition = model.getVersionDefinition(); - return ( versionDefinition != null ) && versionDefinition.isFieldType() - && ( versionDefinition.getValue().equals( getName() ) || versionDefinition.getValue().equals( alias ) ); + return (versionDefinition != null) + && versionDefinition.isFieldType() + && (versionDefinition.getValue().equals(getName()) + || versionDefinition.getValue().equals(alias)); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelInterface.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelInterface.java index 34d3a6a60..64d6dc814 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelInterface.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelInterface.java @@ -30,54 +30,42 @@ /** * @author Emmanuel Venisse */ -public class ModelInterface - extends ModelType -{ +public class ModelInterface extends ModelType { private String superInterface; - public ModelInterface() - { + public ModelInterface() { super(); } - public ModelInterface( Model model, String name ) - { - super( model, name ); + public ModelInterface(Model model, String name) { + super(model, name); } - public void setSuperInterface( String superInterface ) - { + public void setSuperInterface(String superInterface) { this.superInterface = superInterface; } - public String getSuperInterface() - { + public String getSuperInterface() { return superInterface; } /** * {@inheritDoc} */ - public List getAllFields() - { + public List getAllFields() { return new ArrayList(); } /** * {@inheritDoc} */ - public List getAllFields( boolean withInheritedField ) - { + public List getAllFields(boolean withInheritedField) { return new ArrayList(); } - public ModelField getField( String type, VersionRange versionRange ) - { - throw new ModelloRuntimeException( "There are no field '" + type + "' in an interface." ); + public ModelField getField(String type, VersionRange versionRange) { + throw new ModelloRuntimeException("There are no field '" + type + "' in an interface."); } - public void validateElement() - throws ModelValidationException - { - } + public void validateElement() throws ModelValidationException {} } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelType.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelType.java index 6972e685b..bf3a7e805 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelType.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelType.java @@ -32,9 +32,7 @@ * * @author Hervé Boutemy */ -public abstract class ModelType - extends BaseElement -{ +public abstract class ModelType extends BaseElement { private String packageName; private List codeSegments; @@ -43,58 +41,45 @@ public abstract class ModelType private transient Map codeSegmentMap = new HashMap(); - public ModelType() - { - super( true ); + public ModelType() { + super(true); } - public ModelType( Model model, String name ) - { - super( true, name ); + public ModelType(Model model, String name) { + super(true, name); this.model = model; } - public String getPackageName() - { - return getPackageName( false, null ); + public String getPackageName() { + return getPackageName(false, null); } - public String getPackageName( boolean withVersion, Version version ) - { + public String getPackageName(boolean withVersion, Version version) { String p; - if ( packageName != null ) - { + if (packageName != null) { p = packageName; - } - else - { - try - { - p = model.getDefault( ModelDefault.PACKAGE ).getValue(); - } - catch ( Exception e ) - { + } else { + try { + p = model.getDefault(ModelDefault.PACKAGE).getValue(); + } catch (Exception e) { p = ModelDefault.PACKAGE_VALUE; } } - if ( withVersion ) - { - p += "." + version.toString( "v", "_" ); + if (withVersion) { + p += "." + version.toString("v", "_"); } return p; } - public void setPackageName( String packageName ) - { + public void setPackageName(String packageName) { this.packageName = packageName; } - public Model getModel() - { + public Model getModel() { return model; } @@ -102,35 +87,28 @@ public Model getModel() // CodeSegment // ---------------------------------------------------------------------- - public List getAllCodeSegments() - { - if ( codeSegments == null ) - { + public List getAllCodeSegments() { + if (codeSegments == null) { codeSegments = new ArrayList(); } return codeSegments; } - public List getCodeSegments( Version version ) - { - return getCodeSegments( new VersionRange( version ) ); + public List getCodeSegments(Version version) { + return getCodeSegments(new VersionRange(version)); } - public List getCodeSegments( VersionRange versionRange ) - { + public List getCodeSegments(VersionRange versionRange) { List codeSegments = getAllCodeSegments(); List codeSegmentsList = new ArrayList(); - if ( codeSegments != null ) - { - for ( CodeSegment codeSegment : codeSegments ) - { - if ( versionRange.getFromVersion().inside( codeSegment.getVersionRange() ) - && versionRange.getToVersion().inside( codeSegment.getVersionRange() ) ) - { - codeSegmentsList.add( codeSegment ); + if (codeSegments != null) { + for (CodeSegment codeSegment : codeSegments) { + if (versionRange.getFromVersion().inside(codeSegment.getVersionRange()) + && versionRange.getToVersion().inside(codeSegment.getVersionRange())) { + codeSegmentsList.add(codeSegment); } } } @@ -138,11 +116,10 @@ public List getCodeSegments( VersionRange versionRange ) return codeSegmentsList; } - public void addCodeSegment( CodeSegment codeSegment ) - { - getAllCodeSegments().add( codeSegment ); + public void addCodeSegment(CodeSegment codeSegment) { + getAllCodeSegments().add(codeSegment); - codeSegmentMap.put( codeSegment.getName(), codeSegment ); + codeSegmentMap.put(codeSegment.getName(), codeSegment); } // ---------------------------------------------------------------------- @@ -165,9 +142,9 @@ public void addCodeSegment( CodeSegment codeSegment ) * @param withInheritedField whether inherited fields should be included. * @return Returns all the fields in this class and all super classes. */ - public abstract List getAllFields( boolean withInheritedField ); + public abstract List getAllFields(boolean withInheritedField); - public abstract ModelField getField( String type, VersionRange versionRange ); + public abstract ModelField getField(String type, VersionRange versionRange); /** * Returns the list of all fields in this class for a specific version. @@ -178,74 +155,58 @@ public void addCodeSegment( CodeSegment codeSegment ) * @return Returns the list of all fields in this class. It does not include the * fields of super classes. */ - public List getFields( Version version ) - { + public List getFields(Version version) { List fieldList = new ArrayList(); - for ( ModelField currentField : getAllFields() ) - { - if ( version.inside( currentField.getVersionRange() ) ) - { - fieldList.add( currentField ); + for (ModelField currentField : getAllFields()) { + if (version.inside(currentField.getVersionRange())) { + fieldList.add(currentField); } } return fieldList; } - public List getAllFields( Version version, boolean withInheritedField ) - { + public List getAllFields(Version version, boolean withInheritedField) { List allFieldsList = new ArrayList(); List fieldList = new ArrayList(); - for ( ModelField currentField : getAllFields( withInheritedField ) ) - { - if ( version.inside( currentField.getVersionRange() ) ) - { - allFieldsList.add( currentField ); + for (ModelField currentField : getAllFields(withInheritedField)) { + if (version.inside(currentField.getVersionRange())) { + allFieldsList.add(currentField); } } - for ( ModelField currentField : allFieldsList ) - { - if ( version.inside( currentField.getVersionRange() ) ) - { - fieldList.add( currentField ); + for (ModelField currentField : allFieldsList) { + if (version.inside(currentField.getVersionRange())) { + fieldList.add(currentField); } } return fieldList; } - public boolean hasField( String type, Version version ) - { - try - { - getField( type, new VersionRange( version ) ); + public boolean hasField(String type, Version version) { + try { + getField(type, new VersionRange(version)); return true; - } - catch ( Exception e ) - { + } catch (Exception e) { return false; } } - public ModelField getField( String type, Version version ) - { - return getField( type, new VersionRange( version ) ); + public ModelField getField(String type, Version version) { + return getField(type, new VersionRange(version)); } - public List getIdentifierFields( Version version ) - { + public List getIdentifierFields(Version version) { List identifierFields = new ArrayList(); - for ( ModelField field : getFields( version ) ) - { - if ( field.isIdentifier() ) - { - identifierFields.add( field ); + for (ModelField field : getFields(version)) { + if (field.isIdentifier()) { + identifierFields.add(field); } } @@ -256,13 +217,11 @@ public List getIdentifierFields( Version version ) // // ---------------------------------------------------------------------- - public void initialize( Model model ) - { + public void initialize(Model model) { this.model = model; - if ( packageName == null ) - { - packageName = model.getDefaultPackageName( false, null ); + if (packageName == null) { + packageName = model.getDefaultPackageName(false, null); } } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/ModelValidationException.java b/modello-core/src/main/java/org/codehaus/modello/model/ModelValidationException.java index 5c3f56480..3e97c3bc5 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/ModelValidationException.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/ModelValidationException.java @@ -25,13 +25,10 @@ /** * @author Trygve Laugstøl */ -public class ModelValidationException - extends Exception -{ +public class ModelValidationException extends Exception { private static final long serialVersionUID = -8146274663701861789L; - public ModelValidationException( String msg ) - { - super( msg ); + public ModelValidationException(String msg) { + super(msg); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/Version.java b/modello-core/src/main/java/org/codehaus/modello/model/Version.java index 5def332c5..75c5ec5bb 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/Version.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/Version.java @@ -31,10 +31,8 @@ * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class Version - implements Comparable -{ - public static final Version INFINITE = new Version( "32767.32767.32767" ); +public class Version implements Comparable { + public static final Version INFINITE = new Version("32767.32767.32767"); private short major; @@ -42,20 +40,17 @@ public class Version private short micro; - public Version( String version ) - { - if ( version == null ) - { - throw new ModelloRuntimeException( "Syntax error in the version field: Missing. " ); + public Version(String version) { + if (version == null) { + throw new ModelloRuntimeException("Syntax error in the version field: Missing. "); } - String[] splittedVersion = StringUtils.split( version.trim(), "." ); + String[] splittedVersion = StringUtils.split(version.trim(), "."); - if ( splittedVersion.length > 3 ) - { + if (splittedVersion.length > 3) { throw new ModelloRuntimeException( - "Syntax error in the field: The field must be at more 3 parts long (major, minor and micro). Was: '" - + version + "'." ); + "Syntax error in the field: The field must be at more 3 parts long (major, minor and micro). Was: '" + + version + "'."); } String majorString = splittedVersion[0]; @@ -64,43 +59,34 @@ public Version( String version ) String microString = "0"; - if ( splittedVersion.length > 1 ) - { + if (splittedVersion.length > 1) { minorString = splittedVersion[1]; - if ( splittedVersion.length > 2 ) - { + if (splittedVersion.length > 2) { microString = splittedVersion[2]; - } } - try - { - major = Short.parseShort( majorString ); + try { + major = Short.parseShort(majorString); - minor = Short.parseShort( minorString ); + minor = Short.parseShort(minorString); - micro = Short.parseShort( microString ); - } - catch ( NumberFormatException e ) - { - throw new ModelloRuntimeException( "Invalid version string: '" + version + "'." ); + micro = Short.parseShort(microString); + } catch (NumberFormatException e) { + throw new ModelloRuntimeException("Invalid version string: '" + version + "'."); } } - public int getMajor() - { + public int getMajor() { return major; } - public int getMinor() - { + public int getMinor() { return minor; } - public int getMicro() - { + public int getMicro() { return micro; } @@ -110,20 +96,16 @@ public int getMicro() * @param other the other {@link Version} * @return {@code true} if this instance is greater than other instance, otherwise {@code false} */ - public boolean greaterThan( Version other ) - { - if ( this.major != other.major ) - { + public boolean greaterThan(Version other) { + if (this.major != other.major) { return major > other.major; } - if ( this.minor != other.minor ) - { + if (this.minor != other.minor) { return this.minor > other.minor; } - if ( this.micro != other.micro ) - { + if (this.micro != other.micro) { return this.micro > other.micro; } @@ -136,20 +118,16 @@ public boolean greaterThan( Version other ) * @param other the other {@link Version} * @return {@code true} if this instance is greater or equals than other instance, otherwise {@code false} */ - public boolean greaterOrEqualsThan( Version other ) - { - if ( this.major != other.major ) - { + public boolean greaterOrEqualsThan(Version other) { + if (this.major != other.major) { return major >= other.major; } - if ( this.minor != other.minor ) - { + if (this.minor != other.minor) { return this.minor >= other.minor; } - if ( this.micro != other.micro ) - { + if (this.micro != other.micro) { return this.micro >= other.micro; } @@ -162,20 +140,16 @@ public boolean greaterOrEqualsThan( Version other ) * @param other the other {@link Version} * @return {@code true} if this instance is lesser than other instance, otherwise {@code false} */ - public boolean lesserThan( Version other ) - { - if ( this.major != other.major ) - { + public boolean lesserThan(Version other) { + if (this.major != other.major) { return major < other.major; } - if ( this.minor != other.minor ) - { + if (this.minor != other.minor) { return this.minor < other.minor; } - if ( this.micro != other.micro ) - { + if (this.micro != other.micro) { return this.micro < other.micro; } @@ -188,38 +162,28 @@ public boolean lesserThan( Version other ) * @param other the other {@link Version} * @return {@code true} if this instance is lesser or equals than other instance, otherwise {@code false} */ - public boolean lesserOrEqualsThan( Version other ) - { - if ( this.major != other.major ) - { + public boolean lesserOrEqualsThan(Version other) { + if (this.major != other.major) { return major <= other.major; } - if ( this.minor != other.minor ) - { + if (this.minor != other.minor) { return this.minor <= other.minor; } - if ( this.micro != other.micro ) - { + if (this.micro != other.micro) { return this.micro <= other.micro; } return false; } - public boolean inside( VersionRange range ) - { - if ( range.getFromVersion().equals( this ) ) - { + public boolean inside(VersionRange range) { + if (range.getFromVersion().equals(this)) { return true; - } - else if ( ( this.greaterThan( range.getFromVersion() ) ) && ( this.lesserThan( range.getToVersion() ) ) ) - { + } else if ((this.greaterThan(range.getFromVersion())) && (this.lesserThan(range.getToVersion()))) { return true; - } - else if ( this.equals( range.getFromVersion() ) || this.equals( range.getToVersion() ) ) - { + } else if (this.equals(range.getFromVersion()) || this.equals(range.getToVersion())) { return true; } @@ -230,10 +194,8 @@ else if ( this.equals( range.getFromVersion() ) || this.equals( range.getToVersi // Object overrides // ---------------------------------------------------------------------- - public boolean equals( Object object ) - { - if ( !( object instanceof Version ) ) - { + public boolean equals(Object object) { + if (!(object instanceof Version)) { return false; } @@ -242,33 +204,24 @@ public boolean equals( Object object ) return this.major == other.major && this.minor == other.minor && this.micro == other.micro; } - public int hashCode() - { - return toString( "", null ).hashCode(); + public int hashCode() { + return toString("", null).hashCode(); } - public String toString() - { - return toString( "", "." ); + public String toString() { + return toString("", "."); } - public String toString( String prefix, String separator ) - { + public String toString(String prefix, String separator) { return prefix + major + separator + minor + separator + micro; } - public int compareTo( Version otherVersion ) - { - if ( greaterThan( otherVersion ) ) - { + public int compareTo(Version otherVersion) { + if (greaterThan(otherVersion)) { return +1; - } - else if ( equals( otherVersion ) ) - { + } else if (equals(otherVersion)) { return 0; - } - else - { + } else { return -1; } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/VersionDefinition.java b/modello-core/src/main/java/org/codehaus/modello/model/VersionDefinition.java index d813321e9..4bcb06595 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/VersionDefinition.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/VersionDefinition.java @@ -22,56 +22,48 @@ * SOFTWARE. */ -public class VersionDefinition -{ +public class VersionDefinition { private static final String FIELD = "field"; - + private static final String NAMESPACE = "namespace"; - + private static final String FIELD_NAMESPACE = "field+namespace"; - + private String type; private String value; - public String getType() - { + public String getType() { return type; } - public void setType( String type ) - { + public void setType(String type) { this.type = type; } - public String getValue() - { + public String getValue() { return value; } - public void setValue( String value ) - { + public void setValue(String value) { this.value = value; } - + /** - * + * * @return {@code true} if the versionDefinition can be based on the namespace - * @since 1.9 + * @since 1.9 */ - public boolean isNamespaceType() - { - return NAMESPACE.equals( type ) || FIELD_NAMESPACE.equals( type ); + public boolean isNamespaceType() { + return NAMESPACE.equals(type) || FIELD_NAMESPACE.equals(type); } /** - * + * * @return {@code true} if the versionDefinition can be based on the field * @since 1.9 */ - public boolean isFieldType() - { - return FIELD.equals( type ) || FIELD_NAMESPACE.equals( type ); + public boolean isFieldType() { + return FIELD.equals(type) || FIELD_NAMESPACE.equals(type); } - } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/VersionRange.java b/modello-core/src/main/java/org/codehaus/modello/model/VersionRange.java index b75094b42..fd23ea7f2 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/VersionRange.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/VersionRange.java @@ -30,57 +30,46 @@ * * @author Emmanuel Venisse */ -public class VersionRange -{ +public class VersionRange { private static final String VERSION_SEPARATOR = "/"; private Version fromVersion; private Version toVersion; - public VersionRange( String versionRange ) - { - if ( versionRange.endsWith( "+" ) ) - { - fromVersion = new Version( versionRange.substring( 0, versionRange.length() - 1 ) ); + public VersionRange(String versionRange) { + if (versionRange.endsWith("+")) { + fromVersion = new Version(versionRange.substring(0, versionRange.length() - 1)); toVersion = Version.INFINITE; - } - else if ( versionRange.indexOf( VERSION_SEPARATOR ) > 0 && ! versionRange.endsWith( VERSION_SEPARATOR ) ) - { - int pos = versionRange.indexOf( VERSION_SEPARATOR ); + } else if (versionRange.indexOf(VERSION_SEPARATOR) > 0 && !versionRange.endsWith(VERSION_SEPARATOR)) { + int pos = versionRange.indexOf(VERSION_SEPARATOR); - fromVersion = new Version( versionRange.substring( 0, pos ) ); + fromVersion = new Version(versionRange.substring(0, pos)); - toVersion = new Version( versionRange.substring( pos + 1 ) ); - } - else - { - fromVersion = new Version( versionRange ); + toVersion = new Version(versionRange.substring(pos + 1)); + } else { + fromVersion = new Version(versionRange); - toVersion = new Version( versionRange ); + toVersion = new Version(versionRange); } } - public VersionRange( Version version ) - { + public VersionRange(Version version) { fromVersion = version; toVersion = version; } - public Version getFromVersion() - { + public Version getFromVersion() { return fromVersion; } - public Version getToVersion() - { + public Version getToVersion() { return toVersion; } - public boolean isToInfinite() - { + public boolean isToInfinite() { return toVersion == Version.INFINITE; } @@ -88,36 +77,27 @@ public boolean isToInfinite() // Object overrides // ---------------------------------------------------------------------- - public int hashCode() - { + public int hashCode() { return fromVersion.hashCode() + toVersion.hashCode(); } - public boolean equals( Object obj ) - { - if ( !( obj instanceof VersionRange ) ) - { + public boolean equals(Object obj) { + if (!(obj instanceof VersionRange)) { return false; } VersionRange other = (VersionRange) obj; - return fromVersion.equals( other.fromVersion ) && toVersion.equals( other.toVersion ); + return fromVersion.equals(other.fromVersion) && toVersion.equals(other.toVersion); } - public String toString() - { - if ( fromVersion.equals( toVersion ) ) - { - return fromVersion.toString( "", "." ); - } - else if ( toVersion.equals( Version.INFINITE ) ) - { - return fromVersion.toString( "", "." ) + "+"; - } - else - { - return "[" + fromVersion.toString( "", "." ) + " => " + toVersion.toString( "", "." ) + "]"; + public String toString() { + if (fromVersion.equals(toVersion)) { + return fromVersion.toString("", "."); + } else if (toVersion.equals(Version.INFINITE)) { + return fromVersion.toString("", ".") + "+"; + } else { + return "[" + fromVersion.toString("", ".") + " => " + toVersion.toString("", ".") + "]"; } } } diff --git a/modello-core/src/main/java/org/codehaus/modello/model/VersionUtil.java b/modello-core/src/main/java/org/codehaus/modello/model/VersionUtil.java index f53de0290..78a632d5e 100644 --- a/modello-core/src/main/java/org/codehaus/modello/model/VersionUtil.java +++ b/modello-core/src/main/java/org/codehaus/modello/model/VersionUtil.java @@ -25,11 +25,9 @@ /** * @author Emmanuel Venisse */ -public class VersionUtil -{ - public static boolean isInConflict( VersionRange version1, VersionRange version2 ) - { - return !( version1.getToVersion().lesserThan( version2.getFromVersion() ) - || version2.getToVersion().lesserThan( version1.getFromVersion() ) ); +public class VersionUtil { + public static boolean isInConflict(VersionRange version1, VersionRange version2) { + return !(version1.getToVersion().lesserThan(version2.getFromVersion()) + || version2.getToVersion().lesserThan(version1.getFromVersion())); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractModelloGenerator.java b/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractModelloGenerator.java index e1c88e712..334e16e8d 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractModelloGenerator.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractModelloGenerator.java @@ -43,23 +43,21 @@ import org.codehaus.modello.model.Version; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.util.io.CachingWriter; -import org.sonatype.plexus.build.incremental.BuildContext; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.io.CachingWriter; +import org.sonatype.plexus.build.incremental.BuildContext; /** * @author Jason van Zyl * @author Emmanuel Venisse */ -public abstract class AbstractModelloGenerator - extends AbstractLogEnabled - implements ModelloGenerator, Contextualizable -{ +public abstract class AbstractModelloGenerator extends AbstractLogEnabled + implements ModelloGenerator, Contextualizable { private Model model; private File outputDirectory; @@ -72,65 +70,52 @@ public abstract class AbstractModelloGenerator private BuildContext buildContext; - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { + protected void initialize(Model model, Properties parameters) throws ModelloException { this.model = model; - outputDirectory = new File( getParameter( parameters, ModelloParameterConstants.OUTPUT_DIRECTORY ) ); + outputDirectory = new File(getParameter(parameters, ModelloParameterConstants.OUTPUT_DIRECTORY)); - String version = getParameter( parameters, ModelloParameterConstants.VERSION ); + String version = getParameter(parameters, ModelloParameterConstants.VERSION); - generatedVersion = new Version( version ); + generatedVersion = new Version(version); - packageWithVersion = - Boolean.valueOf( getParameter( parameters, ModelloParameterConstants.PACKAGE_WITH_VERSION ) ); + packageWithVersion = Boolean.valueOf(getParameter(parameters, ModelloParameterConstants.PACKAGE_WITH_VERSION)); - encoding = parameters.getProperty( ModelloParameterConstants.ENCODING ); + encoding = parameters.getProperty(ModelloParameterConstants.ENCODING); } - protected Model getModel() - { + protected Model getModel() { return model; } - protected Version getGeneratedVersion() - { + protected Version getGeneratedVersion() { return generatedVersion; } - protected boolean isPackageWithVersion() - { + protected boolean isPackageWithVersion() { return packageWithVersion; } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - protected String getEncoding() - { + protected String getEncoding() { return encoding; } - protected String getHeader() - { + protected String getHeader() { String version = getClass().getPackage().getImplementationVersion(); return "=================== DO NOT EDIT THIS FILE ====================\n" - + "Generated by Modello" + ( ( version == null ) ? "" : ( ' ' + version ) ) + ",\n" - + "any modifications will be overwritten.\n" - + "=============================================================="; + + "Generated by Modello" + ((version == null) ? "" : (' ' + version)) + ",\n" + + "any modifications will be overwritten.\n" + + "=============================================================="; } - protected boolean isClassInModel( String fieldType, Model model ) - { - try - { - return model.getClass( fieldType, generatedVersion ) != null; - } - catch ( Exception e ) - { + protected boolean isClassInModel(String fieldType, Model model) { + try { + return model.getClass(fieldType, generatedVersion) != null; + } catch (Exception e) { } return false; @@ -141,21 +126,16 @@ protected boolean isClassInModel( String fieldType, Model model ) * @param modelClass current class * @return the list of fields of this class */ - protected List getFieldsForClass( ModelClass modelClass ) - { + protected List getFieldsForClass(ModelClass modelClass) { List fields = new ArrayList(); - while ( modelClass != null ) - { - fields.addAll( modelClass.getFields( getGeneratedVersion() ) ); + while (modelClass != null) { + fields.addAll(modelClass.getFields(getGeneratedVersion())); String superClass = modelClass.getSuperClass(); - if ( superClass != null ) - { - modelClass = getModel().getClass( superClass, getGeneratedVersion() ); - } - else - { + if (superClass != null) { + modelClass = getModel().getClass(superClass, getGeneratedVersion()); + } else { modelClass = null; } } @@ -163,81 +143,63 @@ protected List getFieldsForClass( ModelClass modelClass ) return fields; } - protected boolean isInnerAssociation( ModelField field ) - { - return field instanceof ModelAssociation - && isClassInModel( ( (ModelAssociation) field ).getTo(), getModel() ); + protected boolean isInnerAssociation(ModelField field) { + return field instanceof ModelAssociation && isClassInModel(((ModelAssociation) field).getTo(), getModel()); } - protected boolean isMap( String fieldType ) - { - return ModelDefault.MAP.equals( fieldType ) || ModelDefault.PROPERTIES.equals( fieldType ); + protected boolean isMap(String fieldType) { + return ModelDefault.MAP.equals(fieldType) || ModelDefault.PROPERTIES.equals(fieldType); } - protected boolean isCollection( String fieldType ) - { - return ModelDefault.LIST.equals( fieldType ) || ModelDefault.SET.equals( fieldType ); + protected boolean isCollection(String fieldType) { + return ModelDefault.LIST.equals(fieldType) || ModelDefault.SET.equals(fieldType); } - protected String capitalise( String str ) - { - if ( StringUtils.isEmpty( str ) ) - { + protected String capitalise(String str) { + if (StringUtils.isEmpty(str)) { return str; } - return new StringBuilder( str.length() ) - .append( Character.toTitleCase( str.charAt( 0 ) ) ) - .append( str.substring( 1 ) ) - .toString(); + return new StringBuilder(str.length()) + .append(Character.toTitleCase(str.charAt(0))) + .append(str.substring(1)) + .toString(); } - public static String singular( String name ) - { - if ( StringUtils.isEmpty( name ) ) - { + public static String singular(String name) { + if (StringUtils.isEmpty(name)) { return name; } - if ( name.endsWith( "ies" ) ) - { - return name.substring( 0, name.length() - 3 ) + "y"; - } - else if ( name.endsWith( "es" ) && name.endsWith( "ches" ) ) - { - return name.substring( 0, name.length() - 2 ); - } - else if ( name.endsWith( "xes" ) ) - { - return name.substring( 0, name.length() - 2 ); - } - else if ( name.endsWith( "s" ) && ( name.length() != 1 ) ) - { - return name.substring( 0, name.length() - 1 ); + if (name.endsWith("ies")) { + return name.substring(0, name.length() - 3) + "y"; + } else if (name.endsWith("es") && name.endsWith("ches")) { + return name.substring(0, name.length() - 2); + } else if (name.endsWith("xes")) { + return name.substring(0, name.length() - 2); + } else if (name.endsWith("s") && (name.length() != 1)) { + return name.substring(0, name.length() - 1); } return name; } - public static String uncapitalise( String str ) - { - if ( StringUtils.isEmpty( str ) ) - { + public static String uncapitalise(String str) { + if (StringUtils.isEmpty(str)) { return str; } - return new StringBuilder( str.length() ) - .append( Character.toLowerCase( str.charAt( 0 ) ) ) - .append( str.substring( 1 ) ) - .toString(); + return new StringBuilder(str.length()) + .append(Character.toLowerCase(str.charAt(0))) + .append(str.substring(1)) + .toString(); } // ---------------------------------------------------------------------- // Text utils // ---------------------------------------------------------------------- - protected boolean isEmpty( String string ) - { + protected boolean isEmpty(String string) { return string == null || string.trim().length() == 0; } @@ -252,73 +214,55 @@ protected boolean isEmpty( String string ) * @return the parameter value */ @Deprecated - protected String getParameter( String name, Properties parameters ) - { - return getParameter( parameters, name ); + protected String getParameter(String name, Properties parameters) { + return getParameter(parameters, name); } - protected String getParameter( Properties parameters, String name ) - { - String value = parameters.getProperty( name ); + protected String getParameter(Properties parameters, String name) { + String value = parameters.getProperty(name); - if ( value == null ) - { - throw new ModelloRuntimeException( "Missing parameter '" + name + "'." ); + if (value == null) { + throw new ModelloRuntimeException("Missing parameter '" + name + "'."); } return value; } - protected String getParameter( Properties parameters, String name, String defaultValue ) - { - return parameters.getProperty( name, defaultValue ); + protected String getParameter(Properties parameters, String name, String defaultValue) { + return parameters.getProperty(name, defaultValue); } - public void contextualize( Context ctx ) - throws ContextException - { - PlexusContainer plexus = (PlexusContainer) ctx.get( PlexusConstants.PLEXUS_KEY ); + public void contextualize(Context ctx) throws ContextException { + PlexusContainer plexus = (PlexusContainer) ctx.get(PlexusConstants.PLEXUS_KEY); - try - { - buildContext = (BuildContext) plexus.lookup( BuildContext.class.getName() ); - } - catch( ComponentLookupException e ) - { - throw new ContextException( "Unable to lookup required component", e ); + try { + buildContext = (BuildContext) plexus.lookup(BuildContext.class.getName()); + } catch (ComponentLookupException e) { + throw new ContextException("Unable to lookup required component", e); } } - protected BuildContext getBuildContext() - { + protected BuildContext getBuildContext() { return buildContext; } - protected Writer newWriter( Path path ) throws IOException - { - Charset charset = getEncoding() != null ? Charset.forName( getEncoding() ) : Charset.defaultCharset(); - return newWriter( path, charset ); + protected Writer newWriter(Path path) throws IOException { + Charset charset = getEncoding() != null ? Charset.forName(getEncoding()) : Charset.defaultCharset(); + return newWriter(path, charset); } - protected Writer newWriter( Path path, Charset charset ) throws IOException - { - CachingWriter cachingWriter = new CachingWriter( path, charset ); - return new FilterWriter( cachingWriter ) - { + protected Writer newWriter(Path path, Charset charset) throws IOException { + CachingWriter cachingWriter = new CachingWriter(path, charset); + return new FilterWriter(cachingWriter) { @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); - if ( cachingWriter.isModified() ) - { - getBuildContext().refresh( path.toFile() ); - } - else - { - getLogger().debug( "The contents of the file " + path + " matches, skipping writing file." ); + if (cachingWriter.isModified()) { + getBuildContext().refresh(path.toFile()); + } else { + getLogger().debug("The contents of the file " + path + " matches, skipping writing file."); } } }; } - } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractPluginManager.java b/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractPluginManager.java index 2ee6cc499..c74bfa81f 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractPluginManager.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/AbstractPluginManager.java @@ -22,47 +22,36 @@ * SOFTWARE. */ -import org.codehaus.modello.ModelloRuntimeException; +import java.util.Iterator; +import java.util.Map; +import org.codehaus.modello.ModelloRuntimeException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - /** * @author Trygve Laugstøl */ -public abstract class AbstractPluginManager - extends AbstractLogEnabled - implements Initializable -{ - public void initialize() - { - } +public abstract class AbstractPluginManager extends AbstractLogEnabled implements Initializable { + public void initialize() {} - abstract public Map getPlugins(); + public abstract Map getPlugins(); - public Iterator getPluginsIterator() - { + public Iterator getPluginsIterator() { return getPlugins().values().iterator(); } - public T getPlugin( String name ) - { - T plugin = getPlugins().get( name ); + public T getPlugin(String name) { + T plugin = getPlugins().get(name); - if ( plugin == null ) - { - throw new ModelloRuntimeException( "No such plugin: " + name ); + if (plugin == null) { + throw new ModelloRuntimeException("No such plugin: " + name); } return plugin; } - public boolean hasPlugin( String name ) - { - return getPlugins().containsKey( name ); + public boolean hasPlugin(String name) { + return getPlugins().containsKey(name); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/ModelloGenerator.java b/modello-core/src/main/java/org/codehaus/modello/plugin/ModelloGenerator.java index 568c1605a..caacb67db 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/ModelloGenerator.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/ModelloGenerator.java @@ -22,16 +22,14 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Trygve Laugstøl */ -public interface ModelloGenerator -{ - void generate( Model model, Properties parameters ) - throws ModelloException; +public interface ModelloGenerator { + void generate(Model model, Properties parameters) throws ModelloException; } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelAssociationMetadata.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelAssociationMetadata.java index 221902759..eb8d7cf74 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelAssociationMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelAssociationMetadata.java @@ -27,8 +27,6 @@ /** * @author Emmanuel Venisse */ -public class ModelAssociationMetadata - implements AssociationMetadata -{ +public class ModelAssociationMetadata implements AssociationMetadata { public static final String ID = ModelAssociationMetadata.class.getName(); } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelClassMetadata.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelClassMetadata.java index 89ff85113..8a0dc2600 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelClassMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelClassMetadata.java @@ -27,9 +27,7 @@ /** * @author Emmanuel Venisse */ -public class ModelClassMetadata - implements ClassMetadata -{ +public class ModelClassMetadata implements ClassMetadata { public static final String ID = ModelClassMetadata.class.getName(); private boolean rootElement = false; @@ -38,34 +36,27 @@ public class ModelClassMetadata private String sourceTracker; - public boolean isRootElement() - { + public boolean isRootElement() { return rootElement; } - public void setRootElement( boolean rootElement ) - { + public void setRootElement(boolean rootElement) { this.rootElement = rootElement; } - public String getLocationTracker() - { + public String getLocationTracker() { return locationTracker; } - public void setLocationTracker( String locationTracker ) - { + public void setLocationTracker(String locationTracker) { this.locationTracker = locationTracker; } - public String getSourceTracker() - { + public String getSourceTracker() { return sourceTracker; } - public void setSourceTracker( String sourceTracker ) - { + public void setSourceTracker(String sourceTracker) { this.sourceTracker = sourceTracker; } - } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelFieldMetadata.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelFieldMetadata.java index 6715b3891..d84ca1708 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelFieldMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelFieldMetadata.java @@ -27,8 +27,6 @@ /** * @author Emmanuel Venisse */ -public class ModelFieldMetadata - implements FieldMetadata -{ +public class ModelFieldMetadata implements FieldMetadata { public static final String ID = ModelFieldMetadata.class.getName(); } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelInterfaceMetadata.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelInterfaceMetadata.java index 02b1471f6..6f0580162 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelInterfaceMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelInterfaceMetadata.java @@ -27,8 +27,6 @@ /** * @author Emmanuel Venisse */ -public class ModelInterfaceMetadata - implements InterfaceMetadata -{ +public class ModelInterfaceMetadata implements InterfaceMetadata { public static final String ID = ModelInterfaceMetadata.class.getName(); } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelMetadataPlugin.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelMetadataPlugin.java index a43c67d88..4ec4a0b21 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelMetadataPlugin.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelMetadataPlugin.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.Map; + import org.codehaus.modello.metadata.AbstractMetadataPlugin; import org.codehaus.modello.metadata.AssociationMetadata; import org.codehaus.modello.metadata.ClassMetadata; @@ -34,19 +36,13 @@ import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.ModelField; import org.codehaus.modello.model.ModelInterface; - import org.codehaus.plexus.component.annotations.Component; -import java.util.Map; - /** * @author Emmanuel Venisse */ -@Component( role = MetadataPlugin.class, hint = "model" ) -public class ModelMetadataPlugin - extends AbstractMetadataPlugin - implements MetadataPlugin -{ +@Component(role = MetadataPlugin.class, hint = "model") +public class ModelMetadataPlugin extends AbstractMetadataPlugin implements MetadataPlugin { public static final String ROOT_ELEMENT = "rootElement"; public static final String LOCATION_TRACKER = "locationTracker"; @@ -57,36 +53,31 @@ public class ModelMetadataPlugin // Map to Metadata // ---------------------------------------------------------------------- - public ModelMetadata getModelMetadata( Model model, Map data ) - { + public ModelMetadata getModelMetadata(Model model, Map data) { return new ModelModelMetadata(); } - public ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - { + public ClassMetadata getClassMetadata(ModelClass clazz, Map data) { ModelClassMetadata metadata = new ModelClassMetadata(); - metadata.setRootElement( getBoolean( data, ROOT_ELEMENT, false ) ); + metadata.setRootElement(getBoolean(data, ROOT_ELEMENT, false)); - metadata.setLocationTracker( getString( data, LOCATION_TRACKER ) ); + metadata.setLocationTracker(getString(data, LOCATION_TRACKER)); - metadata.setSourceTracker( getString( data, SOURCE_TRACKER ) ); + metadata.setSourceTracker(getString(data, SOURCE_TRACKER)); return metadata; } - public InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - { + public InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) { return new ModelInterfaceMetadata(); } - public FieldMetadata getFieldMetadata( ModelField field, Map data ) - { + public FieldMetadata getFieldMetadata(ModelField field, Map data) { return new ModelFieldMetadata(); } - public AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - { + public AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) { return new ModelAssociationMetadata(); } } diff --git a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelModelMetadata.java b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelModelMetadata.java index c31e4ae20..80ac4a97d 100644 --- a/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelModelMetadata.java +++ b/modello-core/src/main/java/org/codehaus/modello/plugin/model/ModelModelMetadata.java @@ -27,8 +27,6 @@ /** * @author Emmanuel Venisse */ -public class ModelModelMetadata - implements ModelMetadata -{ +public class ModelModelMetadata implements ModelMetadata { public static final String ID = ModelModelMetadata.class.getName(); } diff --git a/modello-core/src/test/java/org/codehaus/modello/core/DefaultModelloCoreTest.java b/modello-core/src/test/java/org/codehaus/modello/core/DefaultModelloCoreTest.java index 4d1923eb4..60373ed1d 100644 --- a/modello-core/src/test/java/org/codehaus/modello/core/DefaultModelloCoreTest.java +++ b/modello-core/src/test/java/org/codehaus/modello/core/DefaultModelloCoreTest.java @@ -28,64 +28,46 @@ /** * @author Trygve Laugstøl */ -public class DefaultModelloCoreTest - extends PlexusTestCase -{ - public void testModelWithDuplicateClasses() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); +public class DefaultModelloCoreTest extends PlexusTestCase { + public void testModelWithDuplicateClasses() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - try - { - modello.loadModel( getTestFile( "src/test/resources/models/duplicate-classes.mdo" ) ); + try { + modello.loadModel(getTestFile("src/test/resources/models/duplicate-classes.mdo")); - fail( "Expected ModelloRuntimeException." ); - } - catch( ModelloRuntimeException ex ) - { - assertEquals( "Duplicate class: MyClass.", ex.getMessage() ); + fail("Expected ModelloRuntimeException."); + } catch (ModelloRuntimeException ex) { + assertEquals("Duplicate class: MyClass.", ex.getMessage()); } } - public void testModelWithDuplicateFields() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testModelWithDuplicateFields() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - try - { - modello.loadModel( getTestFile( "src/test/resources/models/duplicate-fields.mdo" ) ); + try { + modello.loadModel(getTestFile("src/test/resources/models/duplicate-fields.mdo")); - fail( "Expected ModelloRuntimeException." ); - } - catch( ModelloRuntimeException ex ) - { - assertEquals( "Duplicate field in MyClass: MyField.", ex.getMessage() ); + fail("Expected ModelloRuntimeException."); + } catch (ModelloRuntimeException ex) { + assertEquals("Duplicate field in MyClass: MyField.", ex.getMessage()); } } - public void testModelWithDuplicateAssociations() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testModelWithDuplicateAssociations() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - try - { - modello.loadModel( getTestFile( "src/test/resources/models/duplicate-associations.mdo" ) ); + try { + modello.loadModel(getTestFile("src/test/resources/models/duplicate-associations.mdo")); - fail( "Expected ModelloRuntimeException." ); - } - catch( ModelloRuntimeException ex ) - { - assertEquals( "Duplicate field in MyClass: MyAssociation.", ex.getMessage() ); + fail("Expected ModelloRuntimeException."); + } catch (ModelloRuntimeException ex) { + assertEquals("Duplicate field in MyClass: MyAssociation.", ex.getMessage()); } } - - public void testRecursion() throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); - - modello.loadModel( getTestFile( "src/test/resources/models/recursion.mdo" ) ); + + public void testRecursion() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); + + modello.loadModel(getTestFile("src/test/resources/models/recursion.mdo")); } } diff --git a/modello-core/src/test/java/org/codehaus/modello/core/io/ModelReaderTest.java b/modello-core/src/test/java/org/codehaus/modello/core/io/ModelReaderTest.java index f7aa93fad..3cdff59e9 100644 --- a/modello-core/src/test/java/org/codehaus/modello/core/io/ModelReaderTest.java +++ b/modello-core/src/test/java/org/codehaus/modello/core/io/ModelReaderTest.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.List; + import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -31,147 +33,135 @@ import org.codehaus.modello.model.VersionRange; import org.codehaus.plexus.PlexusTestCase; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class ModelReaderTest - extends PlexusTestCase -{ - public void testBasic() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); +public class ModelReaderTest extends PlexusTestCase { + public void testBasic() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getTestFile( "src/test/resources/models/simple.mdo" ) ); + Model model = modello.loadModel(getTestFile("src/test/resources/models/simple.mdo")); - assertNotNull( model ); + assertNotNull(model); - assertEquals( "field", model.getVersionDefinition().getType() ); - assertEquals( "foo", model.getVersionDefinition().getValue() ); + assertEquals("field", model.getVersionDefinition().getType()); + assertEquals("foo", model.getVersionDefinition().getValue()); - assertEquals( "simple", model.getId() ); + assertEquals("simple", model.getId()); - assertEquals( "Simple Modello Test Model", model.getName() ); + assertEquals("Simple Modello Test Model", model.getName()); - assertEquals( "foo.bar", model.getDefaultPackageName( false, null ) ); + assertEquals("foo.bar", model.getDefaultPackageName(false, null)); - assertEquals( "Boy", model.getRoot( new Version( "1.0.0" ) ) ); + assertEquals("Boy", model.getRoot(new Version("1.0.0"))); List classes = model.getAllClasses(); - assertNotNull( classes ); + assertNotNull(classes); - assertEquals( 2, classes.size() ); + assertEquals(2, classes.size()); - assertEquals( 2, model.getClasses( new Version( "1.0.0" ) ).size() ); + assertEquals(2, model.getClasses(new Version("1.0.0")).size()); - assertBoy( classes.get( 0 ) ); + assertBoy(classes.get(0)); - assertBoy( model.getClass( "Boy", new VersionRange( "1.0.0" ) ) ); + assertBoy(model.getClass("Boy", new VersionRange("1.0.0"))); - assertGirl( model.getClass( "Girl", new VersionRange( "1.0.0" ) ) ); + assertGirl(model.getClass("Girl", new VersionRange("1.0.0"))); } - public void testAssociationDefaultValues() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testAssociationDefaultValues() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getTestFile( "src/test/resources/models/association.mdo" ) ); + Model model = modello.loadModel(getTestFile("src/test/resources/models/association.mdo")); - ModelField field = model.getClass( "Foo", new VersionRange( "1.0.0" ) ).getField( "bars", new VersionRange( "1.0.0" ) ); + ModelField field = model.getClass("Foo", new VersionRange("1.0.0")).getField("bars", new VersionRange("1.0.0")); - assertTrue( field instanceof ModelAssociation ); + assertTrue(field instanceof ModelAssociation); ModelAssociation association = (ModelAssociation) field; - assertEquals( "bars", association.getName() ); + assertEquals("bars", association.getName()); - assertEquals( "Foo", association.getModelClass().getName() ); + assertEquals("Foo", association.getModelClass().getName()); - assertEquals( "Bar", association.getTo() ); + assertEquals("Bar", association.getTo()); - assertEquals( "Bar", association.getToClass().getName() ); + assertEquals("Bar", association.getToClass().getName()); -// assertEquals( "bars", association.getFromRole() ); + // assertEquals( "bars", association.getFromRole() ); -// assertEquals( "foo", association.getToRole() ); + // assertEquals( "foo", association.getToRole() ); -// assertEquals( "1", association.getFromMultiplicity() ); + // assertEquals( "1", association.getFromMultiplicity() ); -// assertEquals( "*", association.getToMultiplicity() ); + // assertEquals( "*", association.getToMultiplicity() ); } - private void assertBoy( Object boyObject ) - { - assertTrue( boyObject instanceof ModelClass ); + private void assertBoy(Object boyObject) { + assertTrue(boyObject instanceof ModelClass); - ModelClass boy = (ModelClass)boyObject; + ModelClass boy = (ModelClass) boyObject; - assertNotNull( boy ); + assertNotNull(boy); - assertEquals( "Boy", boy.getName() ); + assertEquals("Boy", boy.getName()); - assertEquals( "1.0.0", boy.getVersionRange().toString() ); + assertEquals("1.0.0", boy.getVersionRange().toString()); - List fields = boy.getFields( new Version( "1.0.0" ) ); + List fields = boy.getFields(new Version("1.0.0")); - assertEquals( 2, fields.size() ); + assertEquals(2, fields.size()); - assertBoyName( fields.get( 0 ) ); + assertBoyName(fields.get(0)); - assertBoyName( boy.getField( "name", new VersionRange( "1.0.0" ) ) ); + assertBoyName(boy.getField("name", new VersionRange("1.0.0"))); } - private void assertBoyName( Object nameObject ) - { - assertTrue( nameObject instanceof ModelField ); + private void assertBoyName(Object nameObject) { + assertTrue(nameObject instanceof ModelField); ModelField name = (ModelField) nameObject; - assertEquals( "name", name.getName() ); + assertEquals("name", name.getName()); - assertEquals( "1.0.0", name.getVersionRange().toString() ); + assertEquals("1.0.0", name.getVersionRange().toString()); - assertEquals( "String", name.getType() ); + assertEquals("String", name.getType()); - assertEquals( "moniker", name.getAlias() ); + assertEquals("moniker", name.getAlias()); } - private void assertGirl( Object girlObject ) - { - assertTrue( girlObject instanceof ModelClass ); + private void assertGirl(Object girlObject) { + assertTrue(girlObject instanceof ModelClass); - ModelClass girl = (ModelClass)girlObject; + ModelClass girl = (ModelClass) girlObject; - assertNotNull( girl ); + assertNotNull(girl); - assertEquals( "Girl", girl.getName() ); + assertEquals("Girl", girl.getName()); - assertEquals( "1.0.0", girl.getVersionRange().toString() ); + assertEquals("1.0.0", girl.getVersionRange().toString()); - List fields = girl.getFields( new Version( "1.0.0" ) ); + List fields = girl.getFields(new Version("1.0.0")); - assertEquals( 1, fields.size() ); + assertEquals(1, fields.size()); - assertGirlAge( fields.get( 0 ) ); + assertGirlAge(fields.get(0)); - assertGirlAge( girl.getField( "age", new VersionRange( "1.0.0" ) ) ); + assertGirlAge(girl.getField("age", new VersionRange("1.0.0"))); } - private void assertGirlAge( Object ageObject ) - { - assertTrue( ageObject instanceof ModelField ); + private void assertGirlAge(Object ageObject) { + assertTrue(ageObject instanceof ModelField); ModelField age = (ModelField) ageObject; - assertEquals( "age", age.getName() ); + assertEquals("age", age.getName()); - assertEquals( "1.0.0+", age.getVersionRange().toString() ); + assertEquals("1.0.0+", age.getVersionRange().toString()); - assertEquals( "int", age.getType() ); + assertEquals("int", age.getType()); } } diff --git a/modello-core/src/test/java/org/codehaus/modello/model/VersionDefinitionTest.java b/modello-core/src/test/java/org/codehaus/modello/model/VersionDefinitionTest.java index 5382fe2fb..f5968b709 100644 --- a/modello-core/src/test/java/org/codehaus/modello/model/VersionDefinitionTest.java +++ b/modello-core/src/test/java/org/codehaus/modello/model/VersionDefinitionTest.java @@ -2,33 +2,26 @@ import junit.framework.TestCase; -public class VersionDefinitionTest - extends TestCase -{ +public class VersionDefinitionTest extends TestCase { - public void testFieldType() - { + public void testFieldType() { VersionDefinition def = new VersionDefinition(); - def.setType( "field" ); - assertTrue( def.isFieldType() ); - assertFalse( def.isNamespaceType() ); + def.setType("field"); + assertTrue(def.isFieldType()); + assertFalse(def.isNamespaceType()); } - - public void testNamespaceType() - { + + public void testNamespaceType() { VersionDefinition def = new VersionDefinition(); - def.setType( "namespace" ); - assertTrue( def.isNamespaceType() ); - assertFalse( def.isFieldType() ); + def.setType("namespace"); + assertTrue(def.isNamespaceType()); + assertFalse(def.isFieldType()); } - public void testFieldAndNamespaceType() - { + public void testFieldAndNamespaceType() { VersionDefinition def = new VersionDefinition(); - def.setType( "field+namespace" ); - assertTrue( def.isFieldType() ); - assertTrue( def.isNamespaceType() ); + def.setType("field+namespace"); + assertTrue(def.isFieldType()); + assertTrue(def.isNamespaceType()); } - - } diff --git a/modello-core/src/test/java/org/codehaus/modello/model/VersionTest.java b/modello-core/src/test/java/org/codehaus/modello/model/VersionTest.java index b641e58fa..403364fa5 100644 --- a/modello-core/src/test/java/org/codehaus/modello/model/VersionTest.java +++ b/modello-core/src/test/java/org/codehaus/modello/model/VersionTest.java @@ -27,79 +27,70 @@ /** * @author Trygve Laugstøl */ -public class VersionTest - extends TestCase -{ +public class VersionTest extends TestCase { // TODO: Add testing for multidigit version numbers // TODO: Add tests for invalid version strings - public void testVersionParsing() - { - Version version = new Version( "1.2.3" ); + public void testVersionParsing() { + Version version = new Version("1.2.3"); - assertEquals( 1, version.getMajor() ); + assertEquals(1, version.getMajor()); - assertEquals( 2, version.getMinor() ); + assertEquals(2, version.getMinor()); - assertEquals( 3, version.getMicro() ); + assertEquals(3, version.getMicro()); } - public void testVersionRange() - { - VersionRange range = new VersionRange( "2.0.0+" ); + public void testVersionRange() { + VersionRange range = new VersionRange("2.0.0+"); - assertFalse( new Version( "1.0.0" ).inside( range ) ); + assertFalse(new Version("1.0.0").inside(range)); - assertTrue( new Version( "2.0.0" ).inside( range ) ); + assertTrue(new Version("2.0.0").inside(range)); - assertTrue( new Version( "3.0.0" ).inside( range ) ); + assertTrue(new Version("3.0.0").inside(range)); - assertTrue( new Version( "2.0.0" ).equals( range.getFromVersion() ) ); + assertTrue(new Version("2.0.0").equals(range.getFromVersion())); - assertTrue( Version.INFINITE.equals( range.getToVersion() ) ); + assertTrue(Version.INFINITE.equals(range.getToVersion())); - range = new VersionRange( "1.0.0" ); + range = new VersionRange("1.0.0"); - assertTrue( new Version( "1.0.0" ).equals( range.getFromVersion() ) ); + assertTrue(new Version("1.0.0").equals(range.getFromVersion())); - assertTrue( new Version( "1.0.0" ).equals( range.getToVersion() ) ); + assertTrue(new Version("1.0.0").equals(range.getToVersion())); - range = new VersionRange( "1.0.0/3.0.0" ); + range = new VersionRange("1.0.0/3.0.0"); - assertTrue( new Version( "1.0.0" ).equals( range.getFromVersion() ) ); + assertTrue(new Version("1.0.0").equals(range.getFromVersion())); - assertTrue( new Version( "3.0.0" ).equals( range.getToVersion() ) ); + assertTrue(new Version("3.0.0").equals(range.getToVersion())); } - public void testGreaterThanWhenFooIsLessThanBar() - { - assertNotGreaterThan( "1.0.0", "2.9.9" ); - assertNotGreaterThan( "1.9.9", "2.0.0" ); - assertNotGreaterThan( "0.1.0", "0.2.9" ); - assertNotGreaterThan( "0.1.1", "0.2.0" ); - assertNotGreaterThan( "0.0.1", "0.0.1" ); + public void testGreaterThanWhenFooIsLessThanBar() { + assertNotGreaterThan("1.0.0", "2.9.9"); + assertNotGreaterThan("1.9.9", "2.0.0"); + assertNotGreaterThan("0.1.0", "0.2.9"); + assertNotGreaterThan("0.1.1", "0.2.0"); + assertNotGreaterThan("0.0.1", "0.0.1"); } - public void testGreaterThanWhenFooIsEqualBar() - { - assertNotGreaterThan( "1.2.3", "1.2.3" ); + public void testGreaterThanWhenFooIsEqualBar() { + assertNotGreaterThan("1.2.3", "1.2.3"); } - public void testGreaterThanWhenFooIsGreaterThanBar() - { - assertGreaterThan( "2.0.0", "1.9.9" ); - assertGreaterThan( "2.9.9", "1.0.0" ); - assertGreaterThan( "0.2.9", "0.1.0" ); - assertGreaterThan( "0.2.0", "0.1.9" ); - assertGreaterThan( "0.0.2", "0.0.1" ); + public void testGreaterThanWhenFooIsGreaterThanBar() { + assertGreaterThan("2.0.0", "1.9.9"); + assertGreaterThan("2.9.9", "1.0.0"); + assertGreaterThan("0.2.9", "0.1.0"); + assertGreaterThan("0.2.0", "0.1.9"); + assertGreaterThan("0.0.2", "0.0.1"); } - private void assertGreaterThan( String foo, String bar ) - { - assertTrue( new Version( foo ).greaterThan( new Version( bar ) ) ); + private void assertGreaterThan(String foo, String bar) { + assertTrue(new Version(foo).greaterThan(new Version(bar))); } - private void assertNotGreaterThan( String foo, String bar ) - { - assertFalse( new Version( foo ).greaterThan( new Version( bar ) ) ); + private void assertNotGreaterThan(String foo, String bar) { + assertFalse(new Version(foo).greaterThan(new Version(bar))); } } diff --git a/modello-maven-plugin/pom.xml b/modello-maven-plugin/pom.xml index d6a359752..0120e9de9 100644 --- a/modello-maven-plugin/pom.xml +++ b/modello-maven-plugin/pom.xml @@ -1,20 +1,18 @@ + + 4.0.0 - modello org.codehaus.modello + modello 2.1.2-SNAPSHOT - 4.0.0 - modello-maven-plugin maven-plugin Modello Maven Plugin - - Modello Maven Plugin enables the use of Modello in Maven builds. - + Modello Maven Plugin enables the use of Modello in Maven builds. ${maven.version} @@ -225,10 +223,11 @@ features - pre-site + verify + pre-site ${basedir}/src/test/verifier/site-verifications.xml @@ -241,10 +240,10 @@ features - site copy-resources + site diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloGeneratorMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloGeneratorMojo.java index 99d9d47b6..51b75a126 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloGeneratorMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloGeneratorMojo.java @@ -47,9 +47,7 @@ /** * @author Trygve Laugstøl */ -public abstract class AbstractModelloGeneratorMojo - extends AbstractMojo -{ +public abstract class AbstractModelloGeneratorMojo extends AbstractMojo { // ---------------------------------------------------------------------- // Parameters // ---------------------------------------------------------------------- @@ -57,25 +55,25 @@ public abstract class AbstractModelloGeneratorMojo /** * Base directory of the project, from where the Modello models are loaded. */ - @Parameter( defaultValue = "${basedir}", required = true ) + @Parameter(defaultValue = "${basedir}", required = true) private String basedir; /** * List of relative paths to mdo files containing the models. */ - @Parameter( required = true ) + @Parameter(required = true) private String[] models; /** * The version of the model we will be working on. */ - @Parameter( property = "version", required = true ) + @Parameter(property = "version", required = true) private String version; /** * True if the generated package names should include the version. */ - @Parameter( property = "packageWithVersion", defaultValue = "false", required = true ) + @Parameter(property = "packageWithVersion", defaultValue = "false", required = true) private boolean packageWithVersion; /** @@ -87,7 +85,7 @@ public abstract class AbstractModelloGeneratorMojo /** * The Maven project instance for the executing project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** @@ -111,13 +109,11 @@ public abstract class AbstractModelloGeneratorMojo public abstract File getOutputDirectory(); - protected boolean producesCompilableResult() - { + protected boolean producesCompilableResult() { return false; } - protected boolean producesResources() - { + protected boolean producesResources() { return false; } @@ -129,8 +125,7 @@ protected boolean producesResources() * * @return the parameters */ - protected Properties createParameters() - { + protected Properties createParameters() { return new Properties(); } @@ -142,20 +137,16 @@ protected Properties createParameters() * * @param parameters the parameters to customize */ - protected void customizeParameters( Properties parameters ) - { - } + protected void customizeParameters(Properties parameters) {} // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - public void execute() - throws MojoExecutionException - { + public void execute() throws MojoExecutionException { String outputDirectory = getOutputDirectory().getAbsolutePath(); - getLog().info( "outputDirectory: " + outputDirectory ); + getLog().info("outputDirectory: " + outputDirectory); // ---------------------------------------------------------------------- // Initialize the parameters @@ -163,43 +154,35 @@ public void execute() Properties parameters = createParameters(); - parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, outputDirectory ); + parameters.setProperty(ModelloParameterConstants.OUTPUT_DIRECTORY, outputDirectory); - parameters.setProperty( ModelloParameterConstants.VERSION, version ); + parameters.setProperty(ModelloParameterConstants.VERSION, version); - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, - Boolean.toString( packageWithVersion ) ); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(packageWithVersion)); - if ( packagedVersions.size() > 0 ) - { - parameters.setProperty( ModelloParameterConstants.ALL_VERSIONS, - StringUtils.join( packagedVersions.iterator(), "," ) ); + if (packagedVersions.size() > 0) { + parameters.setProperty( + ModelloParameterConstants.ALL_VERSIONS, StringUtils.join(packagedVersions.iterator(), ",")); } - - customizeParameters( parameters ); + + customizeParameters(parameters); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- MojoExecutionException firstError = null; - for ( String modelStr : models ) - { - try - { - doExecute( modelStr, outputDirectory, parameters ); - } - catch ( MojoExecutionException e ) - { - if ( firstError == null ) - { + for (String modelStr : models) { + try { + doExecute(modelStr, outputDirectory, parameters); + } catch (MojoExecutionException e) { + if (firstError == null) { firstError = e; } - getLog().error( e ); + getLog().error(e); } } - if ( firstError != null ) - { + if (firstError != null) { throw firstError; } } @@ -207,89 +190,98 @@ public void execute() /** * Performs execute on a single specified model. */ - private void doExecute( String modelStr, String outputDirectory, Properties parameters ) - throws MojoExecutionException - { - if ( !buildContext.hasDelta( modelStr ) ) - { - getLog().debug( "Skipping unchanged model: " + modelStr ); + private void doExecute(String modelStr, String outputDirectory, Properties parameters) + throws MojoExecutionException { + if (!buildContext.hasDelta(modelStr)) { + getLog().debug("Skipping unchanged model: " + modelStr); return; } - getLog().info( "Working on model: " + modelStr ); + getLog().info("Working on model: " + modelStr); - File modelFile = new File( basedir, modelStr ); - buildContext.removeMessages( modelFile ); + File modelFile = new File(basedir, modelStr); + buildContext.removeMessages(modelFile); - try - { - Model model = modelloCore.loadModel( modelFile ); + try { + Model model = modelloCore.loadModel(modelFile); // TODO: dynamically resolve/load the generator type - getLog().info( "Generating current version: " + version ); - modelloCore.generate( model, getGeneratorType(), parameters ); + getLog().info("Generating current version: " + version); + modelloCore.generate(model, getGeneratorType(), parameters); - for ( String version : packagedVersions ) - { - parameters.setProperty( ModelloParameterConstants.VERSION, version ); + for (String version : packagedVersions) { + parameters.setProperty(ModelloParameterConstants.VERSION, version); - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); - getLog().info( "Generating packaged version: " + version ); - modelloCore.generate( model, getGeneratorType(), parameters ); + getLog().info("Generating packaged version: " + version); + modelloCore.generate(model, getGeneratorType(), parameters); } - if ( producesCompilableResult() && project != null ) - { - project.addCompileSourceRoot( outputDirectory ); + if (producesCompilableResult() && project != null) { + project.addCompileSourceRoot(outputDirectory); } - if ( producesResources() && project != null ) - { + if (producesResources() && project != null) { Resource resource = new Resource(); - resource.setDirectory( outputDirectory ); - project.addResource( resource ); + resource.setDirectory(outputDirectory); + project.addResource(resource); } - } - catch ( FileNotFoundException e ) - { - MojoExecutionException mojoExecutionException = new MojoExecutionException( e.getMessage(), e ); - buildContext.addMessage( modelFile, 1 /* line */, 1 /* column */, mojoExecutionException.getMessage(), - BuildContext.SEVERITY_ERROR, mojoExecutionException ); + } catch (FileNotFoundException e) { + MojoExecutionException mojoExecutionException = new MojoExecutionException(e.getMessage(), e); + buildContext.addMessage( + modelFile, + 1 /* line */, + 1 /* column */, + mojoExecutionException.getMessage(), + BuildContext.SEVERITY_ERROR, + mojoExecutionException); throw mojoExecutionException; - } - catch ( ModelloException e ) - { + } catch (ModelloException e) { MojoExecutionException mojoExecutionException = - new MojoExecutionException( "Error generating: " + e.getMessage(), e ); + new MojoExecutionException("Error generating: " + e.getMessage(), e); // TODO: Provide actual line/column numbers - buildContext.addMessage( modelFile, 1 /* line */, 1 /* column */, mojoExecutionException.getMessage(), - BuildContext.SEVERITY_ERROR, mojoExecutionException ); + buildContext.addMessage( + modelFile, + 1 /* line */, + 1 /* column */, + mojoExecutionException.getMessage(), + BuildContext.SEVERITY_ERROR, + mojoExecutionException); throw mojoExecutionException; - } - catch ( ModelValidationException e ) - { + } catch (ModelValidationException e) { MojoExecutionException mojoExecutionException = - new MojoExecutionException( "Error generating: " + e.getMessage(), e ); + new MojoExecutionException("Error generating: " + e.getMessage(), e); // TODO: Provide actual line/column numbers - buildContext.addMessage( modelFile, 1 /* line */, 1 /* column */, mojoExecutionException.getMessage(), - BuildContext.SEVERITY_ERROR, mojoExecutionException ); + buildContext.addMessage( + modelFile, + 1 /* line */, + 1 /* column */, + mojoExecutionException.getMessage(), + BuildContext.SEVERITY_ERROR, + mojoExecutionException); throw mojoExecutionException; - } - catch ( IOException e ) - { + } catch (IOException e) { MojoExecutionException mojoExecutionException = - new MojoExecutionException( "Couldn't read file: " + e.getMessage(), e ); - buildContext.addMessage( modelFile, 1 /* line */, 1 /* column */, mojoExecutionException.getMessage(), - BuildContext.SEVERITY_ERROR, mojoExecutionException ); + new MojoExecutionException("Couldn't read file: " + e.getMessage(), e); + buildContext.addMessage( + modelFile, + 1 /* line */, + 1 /* column */, + mojoExecutionException.getMessage(), + BuildContext.SEVERITY_ERROR, + mojoExecutionException); throw mojoExecutionException; - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { MojoExecutionException mojoExecutionException = - new MojoExecutionException( "Error generating: " + e.getMessage(), e ); - buildContext.addMessage( modelFile, 1 /* line */, 1 /* column */, mojoExecutionException.getMessage(), - BuildContext.SEVERITY_ERROR, mojoExecutionException ); + new MojoExecutionException("Error generating: " + e.getMessage(), e); + buildContext.addMessage( + modelFile, + 1 /* line */, + 1 /* column */, + mojoExecutionException.getMessage(), + BuildContext.SEVERITY_ERROR, + mojoExecutionException); throw mojoExecutionException; } } @@ -298,79 +290,65 @@ private void doExecute( String modelStr, String outputDirectory, Properties para // Accessors // ---------------------------------------------------------------------- - public String getBasedir() - { + public String getBasedir() { return basedir; } - public void setBasedir( String basedir ) - { + public void setBasedir(String basedir) { this.basedir = basedir; } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } - public boolean getPackageWithVersion() - { + public boolean getPackageWithVersion() { return packageWithVersion; } - public void setPackageWithVersion( boolean packageWithVersion ) - { + public void setPackageWithVersion(boolean packageWithVersion) { this.packageWithVersion = packageWithVersion; } - public ModelloCore getModelloCore() - { + public ModelloCore getModelloCore() { return modelloCore; } - public void setModelloCore( ModelloCore modelloCore ) - { + public void setModelloCore(ModelloCore modelloCore) { this.modelloCore = modelloCore; } - public void setBuildContext( BuildContext context ) - { + public void setBuildContext(BuildContext context) { this.buildContext = context; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public void setProject( MavenProject project ) - { + public void setProject(MavenProject project) { this.project = project; } - public void setPackagedVersions( List packagedVersions ) - { - this.packagedVersions = Collections.unmodifiableList( packagedVersions ); + public void setPackagedVersions(List packagedVersions) { + this.packagedVersions = Collections.unmodifiableList(packagedVersions); } /** * @return Returns the paths to the models. */ - public String[] getModels() - { + public String[] getModels() { return models; } /** * @param models Sets the paths to the models. */ - public void setModels( String[] models ) - { + public void setModels(String[] models) { this.models = models; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloSourceGeneratorMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloSourceGeneratorMojo.java index e9279b844..e6021ed62 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloSourceGeneratorMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/AbstractModelloSourceGeneratorMojo.java @@ -31,13 +31,11 @@ /** * @author Hervé Boutemy */ -public abstract class AbstractModelloSourceGeneratorMojo - extends AbstractModelloGeneratorMojo -{ +public abstract class AbstractModelloSourceGeneratorMojo extends AbstractModelloGeneratorMojo { /** * The output directory of the generated Java beans. */ - @Parameter( defaultValue = "${project.build.directory}/generated-sources/modello", required = true ) + @Parameter(defaultValue = "${project.build.directory}/generated-sources/modello", required = true) private File outputDirectory; /** @@ -45,58 +43,51 @@ public abstract class AbstractModelloSourceGeneratorMojo * * @since 1.0-alpha-19 */ - @Parameter( defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(defaultValue = "${project.build.sourceEncoding}") private String encoding; /** * Generate Java 5 sources, with generic collections. * @since 1.0 */ - @Parameter( defaultValue = "${maven.compiler.source}" ) + @Parameter(defaultValue = "${maven.compiler.source}") private String javaSource; /** * Generate DOM content as plexus-utils Xpp3Dom objects instead of org.w3c.dom.Element. * @since 1.6 */ - @Parameter( defaultValue = "true" ) + @Parameter(defaultValue = "true") private boolean domAsXpp3; @Override - protected boolean producesCompilableResult() - { + protected boolean producesCompilableResult() { return true; } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } @Override - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); - if ( encoding != null ) - { - parameters.setProperty( ModelloParameterConstants.ENCODING, encoding ); + if (encoding != null) { + parameters.setProperty(ModelloParameterConstants.ENCODING, encoding); } - if ( javaSource != null ) - { - if ( javaSource.startsWith( "1." ) ) - { - javaSource = javaSource.substring( "1.".length() ); + if (javaSource != null) { + if (javaSource.startsWith("1.")) { + javaSource = javaSource.substring("1.".length()); } - parameters.setProperty( ModelloParameterConstants.OUTPUT_JAVA_SOURCE, javaSource ); + parameters.setProperty(ModelloParameterConstants.OUTPUT_JAVA_SOURCE, javaSource); } - parameters.setProperty( ModelloParameterConstants.DOM_AS_XPP3, Boolean.toString( domAsXpp3 ) ); + parameters.setProperty(ModelloParameterConstants.DOM_AS_XPP3, Boolean.toString(domAsXpp3)); } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloConvertersMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloConvertersMojo.java index 1868d9fe6..797f4daa1 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloConvertersMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloConvertersMojo.java @@ -8,12 +8,9 @@ * * @author Brett Porter */ -@Mojo( name = "converters", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloConvertersMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "converters", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloConvertersMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "converters"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jReaderMojo.java index 981077950..2a26018ed 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jReaderMojo.java @@ -6,12 +6,9 @@ /** * Creates a DOM4J reader from the model. */ -@Mojo( name = "dom4j-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloDom4jReaderMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "dom4j-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloDom4jReaderMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "dom4j-reader"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jWriterMojo.java index 9887de6ec..26c8f83a5 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloDom4jWriterMojo.java @@ -6,12 +6,9 @@ /** * Creates a DOM4J writer from the model. */ -@Mojo( name = "dom4j-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloDom4jWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "dom4j-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloDom4jWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "dom4j-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloGenerateMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloGenerateMojo.java index af0a5f354..c95222b23 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloGenerateMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloGenerateMojo.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.Map; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -29,8 +31,6 @@ import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.modello.plugin.ModelloGenerator; -import java.util.Map; - /** *

* A dynamic way to use generators and Modello plugins. @@ -83,31 +83,25 @@ * * @author Joakim Erdfelt */ -@Mojo( name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloGenerateMojo - extends AbstractModelloSourceGeneratorMojo -{ - @Component( role = ModelloGenerator.class ) +@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloGenerateMojo extends AbstractModelloSourceGeneratorMojo { + @Component(role = ModelloGenerator.class) private Map generatorMap; - @Parameter( property = "modello.generator.id", defaultValue = "java" ) + @Parameter(property = "modello.generator.id", defaultValue = "java") private String generatorId; - protected String getGeneratorType() - { + protected String getGeneratorType() { return generatorId; } - public void execute() - throws MojoExecutionException - { - if ( !generatorMap.containsKey( generatorId ) ) - { - throw new MojoExecutionException( "Unable to execute modello, generator id [" + generatorId - + "] not found. (Available generator ids : " + generatorMap.keySet() + ")" ); + public void execute() throws MojoExecutionException { + if (!generatorMap.containsKey(generatorId)) { + throw new MojoExecutionException("Unable to execute modello, generator id [" + generatorId + + "] not found. (Available generator ids : " + generatorMap.keySet() + ")"); } - getLog().info( "[modello:generate {generator: " + generatorId + "}]" ); + getLog().info("[modello:generate {generator: " + generatorId + "}]"); super.execute(); } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJDOMWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJDOMWriterMojo.java index 303702fd6..a8bb718b1 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJDOMWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJDOMWriterMojo.java @@ -31,12 +31,9 @@ * * @author Milos Kleint */ -@Mojo( name = "jdom-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloJDOMWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "jdom-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloJDOMWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "jdom-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonExtendedReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonExtendedReaderMojo.java index fbcb181d6..a67518b4d 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonExtendedReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonExtendedReaderMojo.java @@ -32,15 +32,11 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "jackson-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloJacksonExtendedReaderMojo - extends ModelloXpp3ReaderMojo -{ +@Mojo(name = "jackson-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloJacksonExtendedReaderMojo extends ModelloXpp3ReaderMojo { @Override - protected String getGeneratorType() - { + protected String getGeneratorType() { return "jackson-extended-reader"; } - } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonReaderMojo.java index 0b468a4c2..12a16251c 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonReaderMojo.java @@ -1,7 +1,5 @@ package org.codehaus.modello.maven; -import java.util.Properties; - /* * Copyright (c) 2004-2012, Codehaus.org * @@ -24,6 +22,8 @@ * SOFTWARE. */ +import java.util.Properties; + import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.modello.ModelloParameterConstants; @@ -34,24 +34,19 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "jackson-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloJacksonReaderMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "jackson-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloJacksonReaderMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "jackson-reader"; } - + @Override - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); - - if ( "true".equals( parameters.getProperty( ModelloParameterConstants.DOM_AS_XPP3 ) ) && - !getProject().getArtifactMap().containsKey( "com.fasterxml.jackson.core:jackson-databind" ) ) - { - getLog().warn( "Jackson DOM support requires auxiliary com.fasterxml.jackson.core:jackson-databind module!" ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); + + if ("true".equals(parameters.getProperty(ModelloParameterConstants.DOM_AS_XPP3)) + && !getProject().getArtifactMap().containsKey("com.fasterxml.jackson.core:jackson-databind")) { + getLog().warn("Jackson DOM support requires auxiliary com.fasterxml.jackson.core:jackson-databind module!"); } } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonWriterMojo.java index bef4d2ff5..02b8ed16b 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJacksonWriterMojo.java @@ -1,7 +1,5 @@ package org.codehaus.modello.maven; -import java.util.Properties; - /* * Copyright (c) 2004, Codehaus.org * @@ -24,6 +22,8 @@ * SOFTWARE. */ +import java.util.Properties; + import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.modello.ModelloParameterConstants; @@ -34,24 +34,19 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "jackson-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloJacksonWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "jackson-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloJacksonWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "jackson-writer"; } - + @Override - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); - - if ( "true".equals( parameters.getProperty( ModelloParameterConstants.DOM_AS_XPP3 ) ) && - !getProject().getArtifactMap().containsKey( "com.fasterxml.jackson.core:jackson-databind" ) ) - { - getLog().warn( "Jackson DOM support requires auxiliary com.fasterxml.jackson.core:jackson-databind module!" ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); + + if ("true".equals(parameters.getProperty(ModelloParameterConstants.DOM_AS_XPP3)) + && !getProject().getArtifactMap().containsKey("com.fasterxml.jackson.core:jackson-databind")) { + getLog().warn("Jackson DOM support requires auxiliary com.fasterxml.jackson.core:jackson-databind module!"); } } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJavaMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJavaMojo.java index 88cbfd52c..e388d6f23 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJavaMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJavaMojo.java @@ -30,12 +30,9 @@ * * @author Trygve Laugstøl */ -@Mojo( name = "java", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloJavaMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "java", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloJavaMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "java"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJsonSchemaGeneratorMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJsonSchemaGeneratorMojo.java index e22299dfd..3a0a9e09a 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJsonSchemaGeneratorMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloJsonSchemaGeneratorMojo.java @@ -36,41 +36,34 @@ * @author Simone Tripodi * @since 1.8 */ -@Mojo( name = "jsonschema", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public final class ModelloJsonSchemaGeneratorMojo - extends AbstractModelloGeneratorMojo -{ +@Mojo(name = "jsonschema", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public final class ModelloJsonSchemaGeneratorMojo extends AbstractModelloGeneratorMojo { /** * The output directory of the generated JSON Schema. Hint: if you want to publish the schema automatically with * the site, configure this parameter to ${basedir}/target/generated-site/resources/jsonschema. */ - @Parameter( defaultValue = "${project.build.directory}/generated-site/jsonschema", required = true ) + @Parameter(defaultValue = "${project.build.directory}/generated-site/jsonschema", required = true) private File outputDirectory; @Parameter private String jsonSchemaFileName; - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); - if ( jsonSchemaFileName != null ) - { - parameters.put( ModelloParameterConstants.OUTPUT_JSONSCHEMA_FILE_NAME, jsonSchemaFileName ); + if (jsonSchemaFileName != null) { + parameters.put(ModelloParameterConstants.OUTPUT_JSONSCHEMA_FILE_NAME, jsonSchemaFileName); } } @Override - protected String getGeneratorType() - { + protected String getGeneratorType() { return "jsonschema"; } @Override - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSaxWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSaxWriterMojo.java index fba868d51..e22ddd01e 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSaxWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSaxWriterMojo.java @@ -31,12 +31,9 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "sax-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloSaxWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "sax-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloSaxWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "sax-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlExtendedReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlExtendedReaderMojo.java index 663118e11..1bef20143 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlExtendedReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlExtendedReaderMojo.java @@ -32,15 +32,11 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "snakeyaml-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloSnakeYamlExtendedReaderMojo - extends ModelloXpp3ReaderMojo -{ +@Mojo(name = "snakeyaml-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloSnakeYamlExtendedReaderMojo extends ModelloXpp3ReaderMojo { @Override - protected String getGeneratorType() - { + protected String getGeneratorType() { return "snakeyaml-extended-reader"; } - } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlReaderMojo.java index f53f57efa..791381244 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlReaderMojo.java @@ -31,12 +31,9 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "snakeyaml-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloSnakeYamlReaderMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "snakeyaml-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloSnakeYamlReaderMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "snakeyaml-reader"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlWriterMojo.java index 7d438d15f..ebc020985 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloSnakeYamlWriterMojo.java @@ -31,12 +31,9 @@ * @since 1.8 * @author Simone Tripodi */ -@Mojo( name = "snakeyaml-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloSnakeYamlWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "snakeyaml-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloSnakeYamlWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "snakeyaml-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxReaderMojo.java index 774e21935..29c51b1a8 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxReaderMojo.java @@ -8,12 +8,9 @@ * * @author Brett Porter */ -@Mojo( name = "stax-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloStaxReaderMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "stax-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloStaxReaderMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "stax-reader"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxWriterMojo.java index d446d5535..ac1efc9d7 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloStaxWriterMojo.java @@ -8,12 +8,9 @@ * * @author Brett Porter */ -@Mojo( name = "stax-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloStaxWriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "stax-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloStaxWriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "stax-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloVelocityMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloVelocityMojo.java index 109f4e413..eb28b7140 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloVelocityMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloVelocityMojo.java @@ -20,12 +20,9 @@ */ import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; @@ -54,20 +51,18 @@ *

* {@code #MODELLO-VELOCITY#SAVE-OUTPUT-TO ${package.replace('.','/')}/${className}.java} */ -@Mojo( name = "velocity", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloVelocityMojo - extends AbstractModelloGeneratorMojo -{ +@Mojo(name = "velocity", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloVelocityMojo extends AbstractModelloGeneratorMojo { /** * The output directory of the generated files. */ - @Parameter( defaultValue = "${project.build.directory}/generated-sources/modello" ) + @Parameter(defaultValue = "${project.build.directory}/generated-sources/modello") private File outputDirectory; /** * The directory where Velocity templates are looked for. */ - @Parameter( defaultValue = "${project.basedir}" ) + @Parameter(defaultValue = "${project.basedir}") private File velocityBasedir; /** @@ -86,34 +81,31 @@ public class ModelloVelocityMojo @Parameter private List params; - protected String getGeneratorType() - { + protected String getGeneratorType() { return "velocity"; } - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); - Map params = this.params == null ? Collections.emptyMap() - : this.params.stream().collect( Collectors.toMap( s -> s.substring( 0, s.indexOf( '=' ) ), - s -> s.substring( s.indexOf( '=' ) + 1 ) ) ); + Map params = this.params == null + ? Collections.emptyMap() + : this.params.stream() + .collect(Collectors.toMap( + s -> s.substring(0, s.indexOf('=')), s -> s.substring(s.indexOf('=') + 1))); - parameters.put( VelocityGenerator.VELOCITY_BASEDIR, velocityBasedir.getAbsolutePath() ); + parameters.put(VelocityGenerator.VELOCITY_BASEDIR, velocityBasedir.getAbsolutePath()); - parameters.put( VelocityGenerator.VELOCITY_TEMPLATES, - templates.stream().collect( Collectors.joining( "," ) ) ); - parameters.put( VelocityGenerator.VELOCITY_PARAMETERS, params ); + parameters.put(VelocityGenerator.VELOCITY_TEMPLATES, templates.stream().collect(Collectors.joining(","))); + parameters.put(VelocityGenerator.VELOCITY_PARAMETERS, params); } - protected boolean producesCompilableResult() - { + protected boolean producesCompilableResult() { return true; } @Override - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXdocMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXdocMojo.java index 46fca6676..c210806a3 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXdocMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXdocMojo.java @@ -22,30 +22,28 @@ * SOFTWARE. */ +import java.io.File; +import java.util.Properties; + import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.modello.ModelloParameterConstants; -import java.io.File; -import java.util.Properties; - /** * Creates documentation for the model in xdoc format. * * @author Brett Porter */ -@Mojo( name = "xdoc", threadSafe = true ) -public class ModelloXdocMojo - extends AbstractModelloGeneratorMojo -{ +@Mojo(name = "xdoc", threadSafe = true) +public class ModelloXdocMojo extends AbstractModelloGeneratorMojo { /** * The output directory of the generated documentation. */ - @Parameter( defaultValue = "${project.build.directory}/generated-site/xdoc", required = true ) + @Parameter(defaultValue = "${project.build.directory}/generated-site/xdoc", required = true) private File outputDirectory; - + /** - * + * * @since 1.0-alpha-21 */ @Parameter @@ -62,51 +60,42 @@ public class ModelloXdocMojo @Parameter private String firstVersion; - protected String getGeneratorType() - { + protected String getGeneratorType() { return "xdoc"; } - protected boolean producesCompilableResult() - { + protected boolean producesCompilableResult() { return false; } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); // Use version if firstVersion was not specified - if ( firstVersion == null ) - { + if (firstVersion == null) { firstVersion = getVersion(); } - parameters.put( ModelloParameterConstants.FIRST_VERSION, firstVersion ); - - if ( xdocFileName != null ) - { - parameters.put( ModelloParameterConstants.OUTPUT_XDOC_FILE_NAME, xdocFileName ); + parameters.put(ModelloParameterConstants.FIRST_VERSION, firstVersion); + + if (xdocFileName != null) { + parameters.put(ModelloParameterConstants.OUTPUT_XDOC_FILE_NAME, xdocFileName); } } - public String getFirstVersion() - { + public String getFirstVersion() { return firstVersion; } - public void setFirstVersion( String firstVersion ) - { + public void setFirstVersion(String firstVersion) { this.firstVersion = firstVersion; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedReaderMojo.java index d2409fa61..6c5943da8 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedReaderMojo.java @@ -32,15 +32,11 @@ * @since 1.4 * @author Benjamin Bentmann */ -@Mojo( name = "xpp3-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloXpp3ExtendedReaderMojo - extends ModelloXpp3ReaderMojo -{ +@Mojo(name = "xpp3-extended-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloXpp3ExtendedReaderMojo extends ModelloXpp3ReaderMojo { @Override - protected String getGeneratorType() - { + protected String getGeneratorType() { return "xpp3-extended-reader"; } - } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedWriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedWriterMojo.java index 39f983411..bc4ed44e3 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedWriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ExtendedWriterMojo.java @@ -36,29 +36,24 @@ * @author Hervé Boutemy * @since 1.10 */ -@Mojo( name = "xpp3-extended-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloXpp3ExtendedWriterMojo - extends ModelloXpp3WriterMojo -{ +@Mojo(name = "xpp3-extended-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloXpp3ExtendedWriterMojo extends ModelloXpp3WriterMojo { /** * The class name suffix for the generated writer. */ - @Parameter( defaultValue = "Ex" ) + @Parameter(defaultValue = "Ex") private String extendedClassnameSuffix; @Override - protected String getGeneratorType() - { + protected String getGeneratorType() { return "xpp3-extended-writer"; } - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); - if ( extendedClassnameSuffix != null ) - { - parameters.put( ModelloParameterConstants.EXTENDED_CLASSNAME_SUFFIX, extendedClassnameSuffix ); + if (extendedClassnameSuffix != null) { + parameters.put(ModelloParameterConstants.EXTENDED_CLASSNAME_SUFFIX, extendedClassnameSuffix); } } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ReaderMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ReaderMojo.java index 8d1a7be12..e59ba20cd 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ReaderMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3ReaderMojo.java @@ -30,12 +30,9 @@ * * @author Brett Porter */ -@Mojo( name = "xpp3-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloXpp3ReaderMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "xpp3-reader", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloXpp3ReaderMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "xpp3-reader"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3WriterMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3WriterMojo.java index 10d1fff94..ec18c16f3 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3WriterMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXpp3WriterMojo.java @@ -30,12 +30,9 @@ * * @author Brett Porter */ -@Mojo( name = "xpp3-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloXpp3WriterMojo - extends AbstractModelloSourceGeneratorMojo -{ - protected String getGeneratorType() - { +@Mojo(name = "xpp3-writer", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloXpp3WriterMojo extends AbstractModelloSourceGeneratorMojo { + protected String getGeneratorType() { return "xpp3-writer"; } } diff --git a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXsdMojo.java b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXsdMojo.java index 161789df0..ce2e63a70 100644 --- a/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXsdMojo.java +++ b/modello-maven-plugin/src/main/java/org/codehaus/modello/maven/ModelloXsdMojo.java @@ -35,14 +35,12 @@ * * @author Brett Porter */ -@Mojo( name = "xsd", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true ) -public class ModelloXsdMojo - extends AbstractModelloGeneratorMojo -{ +@Mojo(name = "xsd", defaultPhase = LifecyclePhase.GENERATE_SOURCES, threadSafe = true) +public class ModelloXsdMojo extends AbstractModelloGeneratorMojo { /** * The output directory of the generated XML Schema. */ - @Parameter( defaultValue = "${project.build.directory}/generated-site/resources/xsd", required = true ) + @Parameter(defaultValue = "${project.build.directory}/generated-site/resources/xsd", required = true) private File outputDirectory; /** @@ -51,7 +49,7 @@ public class ModelloXsdMojo * The default value is {@code false} for backwards compatibility reasons, but should be set to {@code true} for most cases. * @since 2.1.0 */ - @Parameter( defaultValue = "false") + @Parameter(defaultValue = "false") private boolean enforceMandatoryElements; /** @@ -61,34 +59,28 @@ public class ModelloXsdMojo @Parameter private String xsdFileName; - protected String getGeneratorType() - { + protected String getGeneratorType() { return "xsd"; } - protected void customizeParameters( Properties parameters ) - { - super.customizeParameters( parameters ); + protected void customizeParameters(Properties parameters) { + super.customizeParameters(parameters); - if ( xsdFileName != null ) - { - parameters.put( ModelloParameterConstants.OUTPUT_XSD_FILE_NAME, xsdFileName ); + if (xsdFileName != null) { + parameters.put(ModelloParameterConstants.OUTPUT_XSD_FILE_NAME, xsdFileName); } - parameters.put( ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS, enforceMandatoryElements ); + parameters.put(ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS, enforceMandatoryElements); } - protected boolean producesCompilableResult() - { + protected boolean producesCompilableResult() { return false; } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } } diff --git a/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloConvertersMojoTest.java b/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloConvertersMojoTest.java index 4c08d8151..23f466d3f 100644 --- a/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloConvertersMojoTest.java +++ b/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloConvertersMojoTest.java @@ -22,52 +22,48 @@ * SOFTWARE. */ +import java.io.File; +import java.util.Arrays; + import org.codehaus.modello.core.ModelloCore; import org.codehaus.plexus.PlexusTestCase; -import org.sonatype.plexus.build.incremental.BuildContext; import org.codehaus.plexus.util.FileUtils; - -import java.io.File; -import java.util.Arrays; +import org.sonatype.plexus.build.incremental.BuildContext; /** * @author Brett Porter */ -public class ModelloConvertersMojoTest - extends PlexusTestCase -{ - public void testModelloConvertersMojo() - throws Exception - { - ModelloCore modelloCore = (ModelloCore) lookup( ModelloCore.ROLE ); +public class ModelloConvertersMojoTest extends PlexusTestCase { + public void testModelloConvertersMojo() throws Exception { + ModelloCore modelloCore = (ModelloCore) lookup(ModelloCore.ROLE); - BuildContext buildContext = (BuildContext) lookup( BuildContext.class ); + BuildContext buildContext = (BuildContext) lookup(BuildContext.class); ModelloConvertersMojo mojo = new ModelloConvertersMojo(); - File outputDirectory = getTestFile( "target/converters-test" ); + File outputDirectory = getTestFile("target/converters-test"); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); // ---------------------------------------------------------------------- // Call the mojo // ---------------------------------------------------------------------- - mojo.setOutputDirectory( outputDirectory ); + mojo.setOutputDirectory(outputDirectory); String models[] = new String[1]; - models[0] = getTestPath( "src/test/resources/java-model.mdo" ); - mojo.setModels( models ); + models[0] = getTestPath("src/test/resources/java-model.mdo"); + mojo.setModels(models); + + mojo.setVersion("1.0.0"); - mojo.setVersion( "1.0.0" ); + mojo.setPackageWithVersion(false); - mojo.setPackageWithVersion( false ); + mojo.setPackagedVersions(Arrays.asList(new String[] {"0.9.0", "1.0.0"})); - mojo.setPackagedVersions( Arrays.asList( new String[] { "0.9.0", "1.0.0" } ) ); + mojo.setModelloCore(modelloCore); - mojo.setModelloCore( modelloCore ); - - mojo.setBuildContext( buildContext ); + mojo.setBuildContext(buildContext); mojo.execute(); @@ -76,33 +72,30 @@ public void testModelloConvertersMojo() // ---------------------------------------------------------------------- File javaFile = - new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/convert/VersionConverter.java" ); + new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/convert/VersionConverter.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = - new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/convert/BasicVersionConverter.java" ); + javaFile = new File( + outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/convert/BasicVersionConverter.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = - new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/convert/VersionConverter.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/convert/VersionConverter.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = - new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/convert/BasicVersionConverter.java" ); + javaFile = new File( + outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/convert/BasicVersionConverter.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/convert/VersionConverter.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/convert/VersionConverter.java"); - assertFalse( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", - javaFile.exists() ); + assertFalse("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/convert/BasicVersionConverter.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/convert/BasicVersionConverter.java"); - assertFalse( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", - javaFile.exists() ); + assertFalse("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); } } diff --git a/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloJavaMojoTest.java b/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloJavaMojoTest.java index dc109e269..bb5bb7cff 100644 --- a/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloJavaMojoTest.java +++ b/modello-maven-plugin/src/test/java/org/codehaus/modello/maven/ModelloJavaMojoTest.java @@ -22,52 +22,48 @@ * SOFTWARE. */ +import java.io.File; +import java.util.Arrays; + import org.codehaus.modello.core.ModelloCore; import org.codehaus.plexus.PlexusTestCase; -import org.sonatype.plexus.build.incremental.BuildContext; import org.codehaus.plexus.util.FileUtils; - -import java.io.File; -import java.util.Arrays; +import org.sonatype.plexus.build.incremental.BuildContext; /** * @author Trygve Laugstøl */ -public class ModelloJavaMojoTest - extends PlexusTestCase -{ - public void testModelloJavaMojo() - throws Exception - { - ModelloCore modelloCore = (ModelloCore) lookup( ModelloCore.ROLE ); +public class ModelloJavaMojoTest extends PlexusTestCase { + public void testModelloJavaMojo() throws Exception { + ModelloCore modelloCore = (ModelloCore) lookup(ModelloCore.ROLE); - BuildContext buildContext = (BuildContext) lookup( BuildContext.class ); + BuildContext buildContext = (BuildContext) lookup(BuildContext.class); ModelloJavaMojo mojo = new ModelloJavaMojo(); - File outputDirectory = getTestFile( "target/java-test" ); + File outputDirectory = getTestFile("target/java-test"); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); // ---------------------------------------------------------------------- // Call the mojo // ---------------------------------------------------------------------- - mojo.setOutputDirectory( outputDirectory ); + mojo.setOutputDirectory(outputDirectory); String models[] = new String[1]; - models[0] = getTestPath( "src/test/resources/java-model.mdo" ); - mojo.setModels( models ); + models[0] = getTestPath("src/test/resources/java-model.mdo"); + mojo.setModels(models); + + mojo.setVersion("1.0.0"); - mojo.setVersion( "1.0.0" ); + mojo.setPackageWithVersion(false); - mojo.setPackageWithVersion( false ); + mojo.setPackagedVersions(Arrays.asList(new String[] {"0.9.0", "1.0.0"})); - mojo.setPackagedVersions( Arrays.asList( new String[] { "0.9.0", "1.0.0" } ) ); + mojo.setModelloCore(modelloCore); - mojo.setModelloCore( modelloCore ); - - mojo.setBuildContext( buildContext ); + mojo.setBuildContext(buildContext); mojo.execute(); @@ -75,29 +71,29 @@ public void testModelloJavaMojo() // Assert // ---------------------------------------------------------------------- - File javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/Model.java" ); + File javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/Model.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/NewModel.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/NewModel.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/Model.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/Model.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/NewModel.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v1_0_0/NewModel.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/Model.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/Model.java"); - assertTrue( "The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists() ); + assertTrue("The generated java file doesn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); - javaFile = new File( outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/NewModel.java" ); + javaFile = new File(outputDirectory, "org/codehaus/mojo/modello/javatest/v0_9_0/NewModel.java"); - assertFalse( "The generated java file shouldn't exist: '" + javaFile.getAbsolutePath() + "'.", - javaFile.exists() ); + assertFalse( + "The generated java file shouldn't exist: '" + javaFile.getAbsolutePath() + "'.", javaFile.exists()); } } diff --git a/modello-plugins/modello-plugin-converters/pom.xml b/modello-plugins/modello-plugin-converters/pom.xml index 6727e5c5d..b8a3d86e5 100644 --- a/modello-plugins/modello-plugin-converters/pom.xml +++ b/modello-plugins/modello-plugin-converters/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-converters Modello Model Version Converter Plugin - - Modello Model Version Converter Plugin generates code to transform a model between two versions. - + Modello Model Version Converter Plugin generates code to transform a model between two versions. diff --git a/modello-plugins/modello-plugin-converters/src/main/java/org/codehaus/modello/plugin/converters/ConverterGenerator.java b/modello-plugins/modello-plugin-converters/src/main/java/org/codehaus/modello/plugin/converters/ConverterGenerator.java index 56409dded..c18aa98f5 100644 --- a/modello-plugins/modello-plugin-converters/src/main/java/org/codehaus/modello/plugin/converters/ConverterGenerator.java +++ b/modello-plugins/modello-plugin-converters/src/main/java/org/codehaus/modello/plugin/converters/ConverterGenerator.java @@ -22,6 +22,12 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.ModelloRuntimeException; @@ -47,462 +53,392 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.IOUtil; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - /** * Generate a basic conversion class between two versions of a model. */ -@Component( role = ModelloGenerator.class, hint = "converters" ) -public class ConverterGenerator - extends AbstractJavaModelloGenerator -{ - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); - - String[] versions = parameters.getProperty( ModelloParameterConstants.ALL_VERSIONS ).split( "," ); - - List allVersions = new ArrayList( versions.length ); - for ( String version : versions ) - { - allVersions.add( new Version( version ) ); +@Component(role = ModelloGenerator.class, hint = "converters") +public class ConverterGenerator extends AbstractJavaModelloGenerator { + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + String[] versions = + parameters.getProperty(ModelloParameterConstants.ALL_VERSIONS).split(","); + + List allVersions = new ArrayList(versions.length); + for (String version : versions) { + allVersions.add(new Version(version)); } - Collections.sort( allVersions ); + Collections.sort(allVersions); Version nextVersion = null; - for ( Version v : allVersions ) - { - if ( v.greaterThan( getGeneratedVersion() ) ) - { + for (Version v : allVersions) { + if (v.greaterThan(getGeneratedVersion())) { nextVersion = v; break; } } - try - { + try { // if nextVersion remains null, there is none greater so we are converting back to the unpackaged version - generateConverters( nextVersion ); + generateConverters(nextVersion); - if ( nextVersion == null ) - { - generateConverterTool( allVersions ); + if (nextVersion == null) { + generateConverterTool(allVersions); } - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating model converters.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating model converters.", ex); } } - private void generateConverters( Version toVersion ) - throws ModelloException, IOException - { + private void generateConverters(Version toVersion) throws ModelloException, IOException { Model objectModel = getModel(); Version fromVersion = getGeneratedVersion(); - String packageName = objectModel.getDefaultPackageName( true, fromVersion ) + ".convert"; + String packageName = objectModel.getDefaultPackageName(true, fromVersion) + ".convert"; - Version effectiveToVersion = ( toVersion == null ) ? fromVersion : toVersion; + Version effectiveToVersion = (toVersion == null) ? fromVersion : toVersion; String jDoc = "Converts from version " + fromVersion + " (with version in package name) to version " - + effectiveToVersion + " (with" + ( toVersion != null ? "" : "out" ) - + " version in package name) of the model."; + + effectiveToVersion + " (with" + (toVersion != null ? "" : "out") + + " version in package name) of the model."; - JInterface conversionInterface = new JInterface( packageName + ".VersionConverter" ); - initHeader( conversionInterface ); - suppressAllWarnings( objectModel, conversionInterface ); - conversionInterface.getJDocComment().setComment( jDoc ); + JInterface conversionInterface = new JInterface(packageName + ".VersionConverter"); + initHeader(conversionInterface); + suppressAllWarnings(objectModel, conversionInterface); + conversionInterface.getJDocComment().setComment(jDoc); - JClass basicConverterClass = new JClass( packageName + ".BasicVersionConverter" ); - initHeader( basicConverterClass ); - suppressAllWarnings( objectModel, basicConverterClass ); - basicConverterClass.getJDocComment().setComment( jDoc ); - basicConverterClass.addInterface( conversionInterface ); + JClass basicConverterClass = new JClass(packageName + ".BasicVersionConverter"); + initHeader(basicConverterClass); + suppressAllWarnings(objectModel, basicConverterClass); + basicConverterClass.getJDocComment().setComment(jDoc); + basicConverterClass.addInterface(conversionInterface); VersionDefinition versionDefinition = objectModel.getVersionDefinition(); - for ( ModelClass modelClass : objectModel.getClasses( fromVersion ) ) - { - JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID ); + for (ModelClass modelClass : objectModel.getClasses(fromVersion)) { + JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.ID); - if ( !javaClassMetadata.isEnabled() ) - { + if (!javaClassMetadata.isEnabled()) { // Skip generation of those classes that are not enabled for the java plugin. continue; } // check if it's present in the next version - if ( toVersion != null && !toVersion.inside( modelClass.getVersionRange() ) ) - { + if (toVersion != null && !toVersion.inside(modelClass.getVersionRange())) { // Don't convert - it's not there in the next one continue; } String methodName = "convert" + modelClass.getName(); - String parameterName = uncapitalise( modelClass.getName() ); - String sourceClass = getSourceClassName( modelClass, fromVersion ); - String targetClass = - modelClass.getPackageName( toVersion != null, toVersion ) + "." + modelClass.getName(); + String parameterName = uncapitalise(modelClass.getName()); + String sourceClass = getSourceClassName(modelClass, fromVersion); + String targetClass = modelClass.getPackageName(toVersion != null, toVersion) + "." + modelClass.getName(); - if ( !javaClassMetadata.isAbstract() ) - { + if (!javaClassMetadata.isAbstract()) { // Don't generate converter for abstract classes. - JMethodSignature methodSig = new JMethodSignature( methodName, new JType( targetClass ) ); - methodSig.addParameter( new JParameter( new JType( sourceClass ), parameterName ) ); - conversionInterface.addMethod( methodSig ); + JMethodSignature methodSig = new JMethodSignature(methodName, new JType(targetClass)); + methodSig.addParameter(new JParameter(new JType(sourceClass), parameterName)); + conversionInterface.addMethod(methodSig); // Method from interface, delegates to converter with the given implementation of the target class - JMethod jMethod = new JMethod( methodName, new JType( targetClass ), null ); - jMethod.addParameter( new JParameter( new JType( sourceClass ), parameterName ) ); - basicConverterClass.addMethod( jMethod ); + JMethod jMethod = new JMethod(methodName, new JType(targetClass), null); + jMethod.addParameter(new JParameter(new JType(sourceClass), parameterName)); + basicConverterClass.addMethod(jMethod); JSourceCode sc = jMethod.getSourceCode(); - sc.add( "return " + methodName + "( " + parameterName + ", new " + targetClass + "() );" ); + sc.add("return " + methodName + "( " + parameterName + ", new " + targetClass + "() );"); } // Actual conversion method, takes implementation as a parameter to facilitate being called as a superclass - JMethod jMethod = new JMethod( methodName, new JType( targetClass ), null ); - jMethod.addParameter( new JParameter( new JType( sourceClass ), parameterName ) ); - jMethod.addParameter( new JParameter( new JType( targetClass ), "value" ) ); - basicConverterClass.addMethod( jMethod ); + JMethod jMethod = new JMethod(methodName, new JType(targetClass), null); + jMethod.addParameter(new JParameter(new JType(sourceClass), parameterName)); + jMethod.addParameter(new JParameter(new JType(targetClass), "value")); + basicConverterClass.addMethod(jMethod); JSourceCode sc = jMethod.getSourceCode(); - sc.add( "if ( " + parameterName + " == null )" ); + sc.add("if ( " + parameterName + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "return null;" ); + sc.add("return null;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( modelClass.getSuperClass() != null ) - { - sc.add( "// Convert super class" ); + if (modelClass.getSuperClass() != null) { + sc.add("// Convert super class"); - sc.add( "value = (" + targetClass + ") convert" + modelClass.getSuperClass() + "( " + parameterName - + ", value );" ); + sc.add("value = (" + targetClass + ") convert" + modelClass.getSuperClass() + "( " + parameterName + + ", value );"); - sc.add( "" ); + sc.add(""); } - for ( ModelField modelField : modelClass.getFields( fromVersion ) ) - { - String name = capitalise( modelField.getName() ); - - if ( toVersion != null ) - { - if ( versionDefinition != null && versionDefinition.isFieldType() ) - { - if ( versionDefinition.getValue().equals( modelField.getName() ) - || versionDefinition.getValue().equals( modelField.getAlias() ) ) - { - sc.add( "value.set" + name + "( \"" + toVersion + "\" );" ); + for (ModelField modelField : modelClass.getFields(fromVersion)) { + String name = capitalise(modelField.getName()); + + if (toVersion != null) { + if (versionDefinition != null && versionDefinition.isFieldType()) { + if (versionDefinition.getValue().equals(modelField.getName()) + || versionDefinition.getValue().equals(modelField.getAlias())) { + sc.add("value.set" + name + "( \"" + toVersion + "\" );"); continue; } } } // check if it's present in the next version - if ( toVersion != null && !toVersion.inside( modelField.getVersionRange() ) ) - { + if (toVersion != null && !toVersion.inside(modelField.getVersionRange())) { // check if it is present in a new definition instead ModelField newField = null; - try - { - newField = modelClass.getField( modelField.getName(), toVersion ); - } - catch ( ModelloRuntimeException e ) - { + try { + newField = modelClass.getField(modelField.getName(), toVersion); + } catch (ModelloRuntimeException e) { // Don't convert - it's not there in the next one continue; } - if ( !newField.getType().equals( modelField.getType() ) ) - { + if (!newField.getType().equals(modelField.getType())) { // Don't convert - it's a different type in the next one continue; } } - if ( modelField instanceof ModelAssociation ) - { + if (modelField instanceof ModelAssociation) { ModelAssociation assoc = (ModelAssociation) modelField; - if ( assoc.isManyMultiplicity() ) - { + if (assoc.isManyMultiplicity()) { String type = assoc.getType(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( "{" ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add("{"); sc.indent(); - sc.add( assoc.getType() + " list = " + assoc.getDefaultValue() + ";" ); + sc.add(assoc.getType() + " list = " + assoc.getDefaultValue() + ";"); - sc.add( "for ( java.util.Iterator i = " + parameterName + ".get" + name - + "().iterator(); i.hasNext(); )" ); + sc.add("for ( java.util.Iterator i = " + parameterName + ".get" + name + + "().iterator(); i.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( isClassInModel( assoc.getTo(), modelClass.getModel() ) ) - { - String className = getSourceClassName( assoc.getToClass(), fromVersion ); - sc.add( className + " v = (" + className + ") i.next();" ); - } - else - { - sc.add( assoc.getTo() + " v = (" + assoc.getTo() + ") i.next();" ); + if (isClassInModel(assoc.getTo(), modelClass.getModel())) { + String className = getSourceClassName(assoc.getToClass(), fromVersion); + sc.add(className + " v = (" + className + ") i.next();"); + } else { + sc.add(assoc.getTo() + " v = (" + assoc.getTo() + ") i.next();"); } - if ( isClassInModel( assoc.getTo(), objectModel ) ) - { - sc.add( "list.add( convert" + assoc.getTo() + "( v ) );" ); - } - else - { - sc.add( "list.add( v );" ); + if (isClassInModel(assoc.getTo(), objectModel)) { + sc.add("list.add( convert" + assoc.getTo() + "( v ) );"); + } else { + sc.add("list.add( v );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "value.set" + name + "( list );" ); + sc.add("value.set" + name + "( list );"); sc.unindent(); - sc.add( "}" ); - } - else - { - sc.add( "{" ); + sc.add("}"); + } else { + sc.add("{"); sc.indent(); // Map or Properties - sc.add( assoc.getType() + " map = " + assoc.getDefaultValue() + ";" ); + sc.add(assoc.getType() + " map = " + assoc.getDefaultValue() + ";"); - sc.add( "for ( java.util.Iterator i = " + parameterName + ".get" + name - + "().entrySet().iterator(); i.hasNext(); )" ); + sc.add("for ( java.util.Iterator i = " + parameterName + ".get" + name + + "().entrySet().iterator(); i.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "java.util.Map.Entry entry = (java.util.Map.Entry) i.next();" ); + sc.add("java.util.Map.Entry entry = (java.util.Map.Entry) i.next();"); - if ( isClassInModel( assoc.getTo(), modelClass.getModel() ) ) - { - String className = getSourceClassName( assoc.getToClass(), fromVersion ); - sc.add( className + " v = (" + className + ") entry.getValue();" ); - } - else - { - sc.add( assoc.getTo() + " v = (" + assoc.getTo() + ") entry.getValue();" ); + if (isClassInModel(assoc.getTo(), modelClass.getModel())) { + String className = getSourceClassName(assoc.getToClass(), fromVersion); + sc.add(className + " v = (" + className + ") entry.getValue();"); + } else { + sc.add(assoc.getTo() + " v = (" + assoc.getTo() + ") entry.getValue();"); } - if ( isClassInModel( assoc.getTo(), objectModel ) ) - { - sc.add( "map.put( entry.getKey(), convert" + assoc.getTo() + "( v ) );" ); - } - else - { - sc.add( "map.put( entry.getKey(), v );" ); + if (isClassInModel(assoc.getTo(), objectModel)) { + sc.add("map.put( entry.getKey(), convert" + assoc.getTo() + "( v ) );"); + } else { + sc.add("map.put( entry.getKey(), v );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "value.set" + name + "( map );" ); + sc.add("value.set" + name + "( map );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } + } else { + sc.add("value.set" + name + "( convert" + assoc.getTo() + "( " + parameterName + ".get" + name + + "() ) );"); } - else - { - sc.add( "value.set" + name + "( convert" + assoc.getTo() + "( " + parameterName + ".get" + name - + "() ) );" ); - } - } - else - { - sc.add( "// Convert field " + modelField.getName() ); + } else { + sc.add("// Convert field " + modelField.getName()); JavaFieldMetadata javaFieldMetadata = - (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID ); - String value = parameterName + "." + getPrefix( javaFieldMetadata ) + name + "()"; - sc.add( "value.set" + name + "( " + value + " );" ); + (JavaFieldMetadata) modelField.getMetadata(JavaFieldMetadata.ID); + String value = parameterName + "." + getPrefix(javaFieldMetadata) + name + "()"; + sc.add("value.set" + name + "( " + value + " );"); } } - sc.add( "" ); + sc.add(""); - sc.add( "return value;" ); + sc.add("return value;"); } JSourceWriter interfaceWriter = null; JSourceWriter classWriter = null; - try - { - interfaceWriter = newJSourceWriter( packageName, conversionInterface.getName( true ) ); - classWriter = newJSourceWriter( packageName, basicConverterClass.getName( true ) ); + try { + interfaceWriter = newJSourceWriter(packageName, conversionInterface.getName(true)); + classWriter = newJSourceWriter(packageName, basicConverterClass.getName(true)); - conversionInterface.print( interfaceWriter ); - basicConverterClass.print( classWriter ); - } - finally - { - IOUtil.close( classWriter ); - IOUtil.close( interfaceWriter ); + conversionInterface.print(interfaceWriter); + basicConverterClass.print(classWriter); + } finally { + IOUtil.close(classWriter); + IOUtil.close(interfaceWriter); } } - private void generateConverterTool( List allVersions ) - throws ModelloException, IOException - { + private void generateConverterTool(List allVersions) throws ModelloException, IOException { Model objectModel = getModel(); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - - String basePackage = objectModel.getDefaultPackageName( false, null ); + String basePackage = objectModel.getDefaultPackageName(false, null); String packageName = basePackage + ".convert"; String jDoc = "Converts between the available versions of the model."; - JClass converterClass = new JClass( packageName + ".ConverterTool" ); - initHeader( converterClass ); - suppressAllWarnings( objectModel, converterClass ); - converterClass.getJDocComment().setComment( jDoc ); + JClass converterClass = new JClass(packageName + ".ConverterTool"); + initHeader(converterClass); + suppressAllWarnings(objectModel, converterClass); + converterClass.getJDocComment().setComment(jDoc); - converterClass.addImport( "java.io.File" ); - converterClass.addImport( "java.io.IOException" ); + converterClass.addImport("java.io.File"); + converterClass.addImport("java.io.IOException"); - converterClass.addImport( "javax.xml.stream.*" ); + converterClass.addImport("javax.xml.stream.*"); - for ( Version v : allVersions ) - { - writeConvertMethod( converterClass, objectModel, basePackage, allVersions, v, rootClass ); + for (Version v : allVersions) { + writeConvertMethod(converterClass, objectModel, basePackage, allVersions, v, rootClass); } - writeConvertMethod( converterClass, objectModel, basePackage, allVersions, null, rootClass ); + writeConvertMethod(converterClass, objectModel, basePackage, allVersions, null, rootClass); JSourceWriter classWriter = null; - try - { - classWriter = newJSourceWriter( packageName, converterClass.getName( true ) ); - converterClass.print( new JSourceWriter( classWriter ) ); - } - finally - { - IOUtil.close( classWriter ); + try { + classWriter = newJSourceWriter(packageName, converterClass.getName(true)); + converterClass.print(new JSourceWriter(classWriter)); + } finally { + IOUtil.close(classWriter); } } - private static void writeConvertMethod( JClass converterClass, Model objectModel, String basePackage, - List allVersions, Version v, ModelClass rootClass ) - { + private static void writeConvertMethod( + JClass converterClass, + Model objectModel, + String basePackage, + List allVersions, + Version v, + ModelClass rootClass) { String modelName = objectModel.getName(); String rootClassName = rootClass.getName(); - String targetPackage = objectModel.getDefaultPackageName( v != null, v ); + String targetPackage = objectModel.getDefaultPackageName(v != null, v); String targetClass = targetPackage + "." + rootClassName; String methodName = "convertFromFile"; - if ( v != null ) - { - methodName += "_" + v.toString( "v", "_" ); + if (v != null) { + methodName += "_" + v.toString("v", "_"); } - JMethod method = new JMethod( methodName, new JType( targetClass ), null ); - method.addParameter( new JParameter( new JType( "File" ), "f" ) ); - method.addException( new JClass( "IOException" ) ); - method.addException( new JClass( "XMLStreamException" ) ); - converterClass.addMethod( method ); + JMethod method = new JMethod(methodName, new JType(targetClass), null); + method.addParameter(new JParameter(new JType("File"), "f")); + method.addException(new JClass("IOException")); + method.addException(new JClass("XMLStreamException")); + converterClass.addMethod(method); JSourceCode sc = method.getSourceCode(); - sc.add( basePackage + ".io.stax." + modelName + "StaxReaderDelegate reader = new " + basePackage + ".io.stax." - + modelName + "StaxReaderDelegate();" ); + sc.add(basePackage + ".io.stax." + modelName + "StaxReaderDelegate reader = new " + basePackage + ".io.stax." + + modelName + "StaxReaderDelegate();"); - sc.add( "Object value = reader.read( f );" ); + sc.add("Object value = reader.read( f );"); String prefix = ""; - for ( Version sourceVersion : allVersions ) - { - String sourcePackage = objectModel.getDefaultPackageName( true, sourceVersion ); + for (Version sourceVersion : allVersions) { + String sourcePackage = objectModel.getDefaultPackageName(true, sourceVersion); String sourceClass = sourcePackage + "." + rootClassName; - sc.add( prefix + "if ( value instanceof " + sourceClass + " )" ); - sc.add( "{" ); + sc.add(prefix + "if ( value instanceof " + sourceClass + " )"); + sc.add("{"); sc.indent(); boolean foundFirst = false; - for ( Version targetVersion : allVersions ) - { - if ( !foundFirst ) - { - if ( targetVersion.equals( sourceVersion ) ) - { + for (Version targetVersion : allVersions) { + if (!foundFirst) { + if (targetVersion.equals(sourceVersion)) { foundFirst = true; - } - else - { + } else { continue; } } - if ( targetVersion.equals( v ) ) - { + if (targetVersion.equals(v)) { break; } // TODO: need to be able to specify converter class implementation - String p = objectModel.getDefaultPackageName( true, targetVersion ); + String p = objectModel.getDefaultPackageName(true, targetVersion); String c = p + "." + rootClassName; - sc.add( "value = new " + p + ".convert.BasicVersionConverter().convert" + rootClassName - + "( (" + c + ") value );" ); + sc.add("value = new " + p + ".convert.BasicVersionConverter().convert" + rootClassName + "( (" + c + + ") value );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); prefix = "else "; - if ( sourceVersion.equals( v ) ) - { + if (sourceVersion.equals(v)) { break; } } - sc.add( "else" ); - sc.add( "{" ); + sc.add("else"); + sc.add("{"); sc.indent(); - sc.add( "throw new IllegalStateException( \"Can't find converter for class '\" + value.getClass() + \"'\" );" ); + sc.add("throw new IllegalStateException( \"Can't find converter for class '\" + value.getClass() + \"'\" );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return (" + targetClass + ") value;" ); + sc.add("return (" + targetClass + ") value;"); } - private static String getSourceClassName( ModelClass modelClass, Version generatedVersion ) - { - return modelClass.getPackageName( true, generatedVersion ) + "." + modelClass.getName(); + private static String getSourceClassName(ModelClass modelClass, Version generatedVersion) { + return modelClass.getPackageName(true, generatedVersion) + "." + modelClass.getName(); } } diff --git a/modello-plugins/modello-plugin-converters/src/test/java/org/codehaus/modello/plugin/converters/ConverterGeneratorTest.java b/modello-plugins/modello-plugin-converters/src/test/java/org/codehaus/modello/plugin/converters/ConverterGeneratorTest.java index cab49175c..8976ffbad 100644 --- a/modello-plugins/modello-plugin-converters/src/test/java/org/codehaus/modello/plugin/converters/ConverterGeneratorTest.java +++ b/modello-plugins/modello-plugin-converters/src/test/java/org/codehaus/modello/plugin/converters/ConverterGeneratorTest.java @@ -22,71 +22,69 @@ * SOFTWARE. */ +import java.io.Reader; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.io.Reader; -import java.util.Properties; - /** */ -public class ConverterGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public ConverterGeneratorTest() - { - super( "converters" ); +public class ConverterGeneratorTest extends AbstractModelloJavaGeneratorTest { + public ConverterGeneratorTest() { + super("converters"); } - public void testConverterGenerator() - throws Throwable - { - generateConverterClasses( getXmlResourceReader( "/models/maven.mdo" ), "3.0.0", "4.0.0" ); + public void testConverterGenerator() throws Throwable { + generateConverterClasses(getXmlResourceReader("/models/maven.mdo"), "3.0.0", "4.0.0"); - generateConverterClasses( getXmlResourceReader( "/features.mdo" ), "1.0.0", "1.1.0" ); + generateConverterClasses(getXmlResourceReader("/features.mdo"), "1.0.0", "1.1.0"); - addDependency( "org.codehaus.woodstox", "stax2-api" ); - addDependency( "com.fasterxml.woodstox", "woodstox-core" ); + addDependency("org.codehaus.woodstox", "stax2-api"); + addDependency("com.fasterxml.woodstox", "woodstox-core"); compileGeneratedSources(); - verifyCompiledGeneratedSources( "ConvertersVerifier" ); + verifyCompiledGeneratedSources("ConvertersVerifier"); } - private void generateConverterClasses( Reader modelReader, String fromVersion, String toVersion ) - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + private void generateConverterClasses(Reader modelReader, String fromVersion, String toVersion) throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( modelReader ); + Model model = modello.loadModel(modelReader); Properties parameters = new Properties(); - parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, getOutputDirectory().getAbsolutePath() ); - parameters.setProperty( ModelloParameterConstants.ALL_VERSIONS, fromVersion + "," + toVersion ); - - generateClasses( parameters, modello, model, fromVersion, toVersion, "java" ); - generateClasses( parameters, modello, model, fromVersion, toVersion, "stax-reader" ); - generateClasses( parameters, modello, model, fromVersion, toVersion, "stax-writer" ); - generateClasses( parameters, modello, model, fromVersion, toVersion, "converters" ); + parameters.setProperty( + ModelloParameterConstants.OUTPUT_DIRECTORY, getOutputDirectory().getAbsolutePath()); + parameters.setProperty(ModelloParameterConstants.ALL_VERSIONS, fromVersion + "," + toVersion); + + generateClasses(parameters, modello, model, fromVersion, toVersion, "java"); + generateClasses(parameters, modello, model, fromVersion, toVersion, "stax-reader"); + generateClasses(parameters, modello, model, fromVersion, toVersion, "stax-writer"); + generateClasses(parameters, modello, model, fromVersion, toVersion, "converters"); } - private void generateClasses( Properties parameters, ModelloCore modello, Model model, String fromVersion, - String toVersion, String outputType ) - throws ModelloException - { - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( false ) ); - parameters.setProperty( ModelloParameterConstants.VERSION, toVersion ); - modello.generate( model, outputType, parameters ); - - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); - parameters.setProperty( ModelloParameterConstants.VERSION, fromVersion ); - modello.generate( model, outputType, parameters ); - - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); - parameters.setProperty( ModelloParameterConstants.VERSION, toVersion ); - modello.generate( model, outputType, parameters ); + private void generateClasses( + Properties parameters, + ModelloCore modello, + Model model, + String fromVersion, + String toVersion, + String outputType) + throws ModelloException { + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(false)); + parameters.setProperty(ModelloParameterConstants.VERSION, toVersion); + modello.generate(model, outputType, parameters); + + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); + parameters.setProperty(ModelloParameterConstants.VERSION, fromVersion); + modello.generate(model, outputType, parameters); + + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); + parameters.setProperty(ModelloParameterConstants.VERSION, toVersion); + modello.generate(model, outputType, parameters); } } diff --git a/modello-plugins/modello-plugin-dom4j/pom.xml b/modello-plugins/modello-plugin-dom4j/pom.xml index 09b65f2fd..d42c2db21 100644 --- a/modello-plugins/modello-plugin-dom4j/pom.xml +++ b/modello-plugins/modello-plugin-dom4j/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-dom4j Modello Dom4J Plugin - - Modello Dom4J Plugin generates XML readers and writers based on Dom4J API. - + Modello Dom4J Plugin generates XML readers and writers based on Dom4J API. diff --git a/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jReaderGenerator.java b/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jReaderGenerator.java index fcde29919..41835514d 100644 --- a/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jReaderGenerator.java +++ b/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jReaderGenerator.java @@ -22,6 +22,10 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -41,388 +45,373 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - /** * Generator that reads a model using dom4j. * TODO: chunks are lifted from xpp3, including the tests. Can we abstract it in some way? * * @author Brett Porter */ -@Component( role = ModelloGenerator.class, hint = "dom4j-reader" ) -public class Dom4jReaderGenerator - extends AbstractXmlJavaGenerator -{ +@Component(role = ModelloGenerator.class, hint = "dom4j-reader") +public class Dom4jReaderGenerator extends AbstractXmlJavaGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateDom4jReader(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating Dom4j Reader.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating Dom4j Reader.", ex); } } - private void generateDom4jReader() - throws ModelloException, IOException - { + private void generateDom4jReader() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.dom4j"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.dom4j"; - String unmarshallerName = getFileName( "Dom4jReader" ); + String unmarshallerName = getFileName("Dom4jReader"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + unmarshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "java.io.InputStream" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); - jClass.addImport( "java.net.URL" ); - jClass.addImport( "java.util.Date" ); - jClass.addImport( "java.util.Locale" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.text.ParsePosition" ); - jClass.addImport( "java.util.Iterator" ); - jClass.addImport( "org.dom4j.Attribute" ); - jClass.addImport( "org.dom4j.Document" ); - jClass.addImport( "org.dom4j.DocumentException" ); - jClass.addImport( "org.dom4j.Element" ); - jClass.addImport( "org.dom4j.Node" ); - jClass.addImport( "org.dom4j.io.SAXReader" ); + jClass.addImport("java.io.InputStream"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); + jClass.addImport("java.net.URL"); + jClass.addImport("java.util.Date"); + jClass.addImport("java.util.Locale"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.text.ParsePosition"); + jClass.addImport("java.util.Iterator"); + jClass.addImport("org.dom4j.Attribute"); + jClass.addImport("org.dom4j.Document"); + jClass.addImport("org.dom4j.DocumentException"); + jClass.addImport("org.dom4j.Element"); + jClass.addImport("org.dom4j.Node"); + jClass.addImport("org.dom4j.io.SAXReader"); - addModelImports( jClass, null ); + addModelImports(jClass, null); - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); - JClass rootType = new JClass( root.getName() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); + JClass rootType = new JClass(root.getName()); // ---------------------------------------------------------------------- // Write the read(XMLStreamReader,boolean) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod unmarshall = new JMethod( "read", rootType, null ); + JMethod unmarshall = new JMethod("read", rootType, null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "Document" ), "document" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("Document"), "document")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); JSourceCode sc = unmarshall.getSourceCode(); String className = root.getName(); - String variableName = uncapitalise( className ); + String variableName = uncapitalise(className); - sc.add( "String encoding = document.getXMLEncoding();" ); + sc.add("String encoding = document.getXMLEncoding();"); - sc.add( className + ' ' + variableName + " = parse" + root.getName() + "( \"" + resolveTagName( root ) - + "\", document.getRootElement(), strict );" ); + sc.add(className + ' ' + variableName + " = parse" + root.getName() + "( \"" + resolveTagName(root) + + "\", document.getRootElement(), strict );"); - sc.add( variableName + ".setModelEncoding( encoding );" ); + sc.add(variableName + ".setModelEncoding( encoding );"); - sc.add( "return " + variableName + ";" ); + sc.add("return " + variableName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(Reader[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "SAXReader parser = new SAXReader();" ); + sc.add("SAXReader parser = new SAXReader();"); - sc.add( "Document document = parser.read( reader );" ); + sc.add("Document document = parser.read( reader );"); - sc.add( "return read( document, strict );" ); + sc.add("return read( document, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( reader, true );" ); + sc.add("return read( reader, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(InputStream[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "stream" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "stream")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "SAXReader parser = new SAXReader();" ); + sc.add("SAXReader parser = new SAXReader();"); - sc.add( "Document document = parser.read( stream );" ); + sc.add("Document document = parser.read( stream );"); - sc.add( "return read( document, strict );" ); + sc.add("return read( document, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "stream" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "stream")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( stream, true );" ); + sc.add("return read( stream, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(URL[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "URL" ), "url" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("URL"), "url")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "SAXReader parser = new SAXReader();" ); + sc.add("SAXReader parser = new SAXReader();"); - sc.add( "Document document = parser.read( url );" ); + sc.add("Document document = parser.read( url );"); - sc.add( "return read( document, strict );" ); + sc.add("return read( document, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "URL" ), "url" ) ); + unmarshall.addParameter(new JParameter(new JClass("URL"), "url")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( url, true );" ); + sc.add("return read( url, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the class parsers // ---------------------------------------------------------------------- - writeAllClassesParser( objectModel, jClass ); + writeAllClassesParser(objectModel, jClass); // ---------------------------------------------------------------------- // Write helpers // ---------------------------------------------------------------------- - writeHelpers( jClass ); + writeHelpers(jClass); - if ( requiresDomSupport ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); - writeDomHelpers( jClass ); + if (requiresDomSupport) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); + writeDomHelpers(jClass); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClassesParser( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesParser(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) ); + for (ModelClass clazz : getClasses(objectModel)) { + writeClassParser(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassParser(ModelClass modelClass, JClass jClass, boolean rootElement) { String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null ); + JMethod unmarshall = new JMethod("parse" + capClassName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - unmarshall.addParameter( new JParameter( new JClass( "Element" ), "element" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("String"), "tagName")); + unmarshall.addParameter(new JParameter(new JClass("Element"), "element")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "DocumentException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("DocumentException")); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( className + " " + uncapClassName + " = new " + className + "();" ); + sc.add(className + " " + uncapClassName + " = new " + className + "();"); ModelField contentField = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // read all XML attributes first - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { String tagName = xmlFieldMetadata.getTagName(); - if ( tagName == null ) - { + if (tagName == null) { tagName = field.getName(); } - sc.add( "if ( element.attributeValue( \"" + tagName + "\" ) != null )" ); - sc.add( "{" ); + sc.add("if ( element.attributeValue( \"" + tagName + "\" ) != null )"); + sc.add("{"); sc.indent(); - writePrimitiveField( field, field.getType(), uncapClassName, "set" + capitalise( field.getName() ), sc, - jClass, "element", "childElement" ); + writePrimitiveField( + field, + field.getType(), + uncapClassName, + "set" + capitalise(field.getName()), + sc, + jClass, + "element", + "childElement"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } // TODO check if we have already one with this type and throws Exception - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; } } - if ( rootElement ) - { - sc.add( "if ( strict )" ); - sc.add( "{" ); + if (rootElement) { + sc.add("if ( strict )"); + sc.add("{"); sc.indent(); - sc.add( "if ( !element.getName().equals( tagName ) )" ); - sc.add( "{" ); + sc.add("if ( !element.getName().equals( tagName ) )"); + sc.add("{"); sc.addIndented( - "throw new DocumentException( \"Error parsing model: root element tag is '\" + element.getName() + \"' instead of '\" + tagName + \"'\" );" ); - sc.add( "}" ); + "throw new DocumentException( \"Error parsing model: root element tag is '\" + element.getName() + \"' instead of '\" + tagName + \"'\" );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - - if ( contentField != null ) - { - writePrimitiveField( contentField, contentField.getType(), uncapClassName, - "set" + capitalise( contentField.getName() ), sc, jClass, null, "element" ); + sc.add("}"); } - else - { - sc.add( "java.util.Set parsed = new java.util.HashSet();" ); - sc.add( "for ( Iterator i = element.nodeIterator(); i.hasNext(); )" ); - sc.add( "{" ); + if (contentField != null) { + writePrimitiveField( + contentField, + contentField.getType(), + uncapClassName, + "set" + capitalise(contentField.getName()), + sc, + jClass, + null, + "element"); + } else { + sc.add("java.util.Set parsed = new java.util.HashSet();"); + + sc.add("for ( Iterator i = element.nodeIterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "Node node = (Node) i.next();" ); + sc.add("Node node = (Node) i.next();"); - sc.add( "if ( node.getNodeType() == Node.ELEMENT_NODE )" ); + sc.add("if ( node.getNodeType() == Node.ELEMENT_NODE )"); // TODO: attach other NodeTypes to model in some way - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element childElement = (Element) node;" ); + sc.add("Element childElement = (Element) node;"); boolean addElse = false; - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( !xmlFieldMetadata.isAttribute() ) - { - processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass ); + if (!xmlFieldMetadata.isAttribute()) { + processField(field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass); addElse = true; } } - if ( addElse ) - { - sc.add( "else" ); + if (addElse) { + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.indent(); } - sc.add( "checkUnknownElement( childElement, strict );" ); + sc.add("checkUnknownElement( childElement, strict );"); - if ( addElse ) - { + if (addElse) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "return " + uncapClassName + ";" ); + sc.add("return " + uncapClassName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } /** @@ -435,665 +424,637 @@ private void writeClassParser( ModelClass modelClass, JClass jClass, boolean roo * @param objectName the object name in the source * @param jClass the generated class source file */ - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc, - String objectName, JClass jClass ) - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + boolean addElse, + JSourceCode sc, + String objectName, + JClass jClass) { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String capFieldName = capitalise( field.getName() ); + String capFieldName = capitalise(field.getName()); - String singularName = singular( field.getName() ); + String singularName = singular(field.getName()); String alias; - if ( StringUtils.isEmpty( field.getAlias() ) ) - { + if (StringUtils.isEmpty(field.getAlias())) { alias = "null"; - } - else - { + } else { alias = "\"" + field.getAlias() + "\""; } - String tagComparison = ( addElse ? "else " : "" ) - + "if ( checkFieldWithDuplicate( childElement, \"" + fieldTagName + "\", " + alias + ", parsed ) )"; + String tagComparison = (addElse ? "else " : "") + "if ( checkFieldWithDuplicate( childElement, \"" + + fieldTagName + "\", " + alias + ", parsed ) )"; - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( tagComparison ); + if (association.isOneMultiplicity()) { + sc.add(tagComparison); - sc.add( "{" ); - sc.addIndented( objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( \"" - + fieldTagName + "\", childElement, strict ) );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented(objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( \"" + + fieldTagName + "\", childElement, strict ) );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); String type = association.getType(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( wrappedItems ) - { - sc.add( tagComparison ); + if (wrappedItems) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( type + " " + associationName + " = " + association.getDefaultValue() + ";" ); + sc.add(type + " " + associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); - sc.add( "for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )" ); + sc.add("for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Node n = (Node) j.next();" ); + sc.add("Node n = (Node) j.next();"); - sc.add( "if ( n.getNodeType() == Node.ELEMENT_NODE )" ); + sc.add("if ( n.getNodeType() == Node.ELEMENT_NODE )"); // TODO: track the whitespace in the model (other NodeTypes) - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = (Element) n;" ); + sc.add("Element listElement = (Element) n;"); - sc.add( "if ( \"" + valuesTagName + "\".equals( listElement.getName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( listElement.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - } - else - { - sc.add( ( addElse ? "else " : "" ) - + "if ( \"" + valuesTagName + "\".equals( childElement.getName() ) )" ); + } else { + sc.add((addElse ? "else " : "") + "if ( \"" + valuesTagName + + "\".equals( childElement.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = childElement;" ); + sc.add("Element listElement = childElement;"); - sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" ); + sc.add(type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();"); - sc.add( "if ( " + associationName + " == null )" ); + sc.add("if ( " + associationName + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( associationName + " = " + association.getDefaultValue() + ";" ); + sc.add(associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - if ( isClassInModel( association.getTo(), field.getModelClass().getModel() ) ) - { - sc.add( associationName + ".add( parse" + association.getTo() + "( \"" + valuesTagName - + "\", listElement, strict ) );" ); - } - else - { - writePrimitiveField( association, association.getTo(), associationName, "add", sc, jClass, - "childElement", "listElement" ); + if (isClassInModel( + association.getTo(), field.getModelClass().getModel())) { + sc.add(associationName + ".add( parse" + association.getTo() + "( \"" + valuesTagName + + "\", listElement, strict ) );"); + } else { + writePrimitiveField( + association, + association.getTo(), + associationName, + "add", + sc, + jClass, + "childElement", + "listElement"); } - if ( wrappedItems ) - { + if (wrappedItems) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.add( "}" ); + sc.add("{"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - else - { + sc.add("}"); + } else { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - } - else - { - //Map or Properties + } else { + // Map or Properties - sc.add( tagComparison ); + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Node n = (Node) j.next();" ); + sc.add("Node n = (Node) j.next();"); - sc.add( "if ( n.getNodeType() == Node.ELEMENT_NODE )" ); + sc.add("if ( n.getNodeType() == Node.ELEMENT_NODE )"); // TODO: track the whitespace in the model (other NodeTypes) - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = (Element) n;" ); + sc.add("Element listElement = (Element) n;"); - sc.add( "if ( \"" + valuesTagName + "\".equals( listElement.getName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( listElement.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = null;" ); + sc.add("String key = null;"); - sc.add( "String value = null;" ); + sc.add("String value = null;"); - sc.add( "//" + xmlAssociationMetadata.getMapStyle() + " mode." ); + sc.add("//" + xmlAssociationMetadata.getMapStyle() + " mode."); - sc.add( "for ( Iterator k = listElement.nodeIterator(); k.hasNext(); )" ); + sc.add("for ( Iterator k = listElement.nodeIterator(); k.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Node nd = (Node) k.next();" ); + sc.add("Node nd = (Node) k.next();"); - sc.add( "if ( nd.getNodeType() == Node.ELEMENT_NODE )" ); + sc.add("if ( nd.getNodeType() == Node.ELEMENT_NODE )"); // TODO: track the whitespace in the model (other NodeTypes) - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element propertyElement = (Element) nd;" ); + sc.add("Element propertyElement = (Element) nd;"); - sc.add( "if ( \"key\".equals( propertyElement.getName() ) )" ); + sc.add("if ( \"key\".equals( propertyElement.getName() ) )"); - sc.add( "{" ); - sc.addIndented( "key = propertyElement.getText();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("key = propertyElement.getText();"); + sc.add("}"); - sc.add( "else if ( \"value\".equals( propertyElement.getName() ) )" ); + sc.add("else if ( \"value\".equals( propertyElement.getName() ) )"); - sc.add( "{" ); - sc.addIndented( "value = propertyElement.getText()" - + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("value = propertyElement.getText()" + + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.add( "}" ); + sc.add("{"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - else - { - //INLINE Mode + sc.add("}"); + } else { + // INLINE Mode - sc.add( "for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )" ); + sc.add("for ( Iterator j = childElement.nodeIterator(); j.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Node n = (Node) j.next();" ); + sc.add("Node n = (Node) j.next();"); - sc.add( "if ( n.getNodeType() == Node.ELEMENT_NODE )" ); + sc.add("if ( n.getNodeType() == Node.ELEMENT_NODE )"); // TODO: track the whitespace in the model (other NodeTypes) - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = (Element) n;" ); + sc.add("Element listElement = (Element) n;"); - sc.add( "String key = listElement.getName();" ); + sc.add("String key = listElement.getName();"); - sc.add( "String value = listElement.getText()" - + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + sc.add("String value = listElement.getText()" + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + + ";"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( tagComparison ); + } else { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - //ModelField - writePrimitiveField( field, field.getType(), objectName, "set" + capitalise( field.getName() ), sc, - jClass, "element", "childElement" ); + // ModelField + writePrimitiveField( + field, + field.getType(), + objectName, + "set" + capitalise(field.getName()), + sc, + jClass, + "element", + "childElement"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - private void writePrimitiveField( ModelField field, String type, String objectName, String setterName, - JSourceCode sc, JClass jClass, String parentElementName, String childElementName ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + private void writePrimitiveField( + ModelField field, + String type, + String objectName, + String setterName, + JSourceCode sc, + JClass jClass, + String parentElementName, + String childElementName) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - String tagName = resolveTagName( field, xmlFieldMetadata ); + String tagName = resolveTagName(field, xmlFieldMetadata); String parserGetter; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { parserGetter = parentElementName + ".attributeValue( \"" + tagName + "\" )"; - } - else - { + } else { parserGetter = childElementName + ".getText()"; } -// TODO: this and a default -// if ( fieldMetaData.isRequired() ) -// { -// parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict, encoding )"; -// } -// + // TODO: this and a default + // if ( fieldMetaData.isRequired() ) + // { + // parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, + // strict, encoding )"; + // } + // - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - if ( "boolean".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName + "\" ) );" ); - } - else if ( "char".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName + "\" ) );" ); - } - else if ( "double".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "float".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "int".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "long".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "short".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "byte".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName - + "\", strict ) );" ); - } - else if ( "String".equals( type ) || "Boolean".equals( type ) ) - { + if ("boolean".equals(type)) { + sc.add(objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName + "\" ) );"); + } else if ("char".equals(type)) { + sc.add(objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName + + "\" ) );"); + } else if ("double".equals(type)) { + sc.add(objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("float".equals(type)) { + sc.add(objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("int".equals(type)) { + sc.add(objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("long".equals(type)) { + sc.add(objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("short".equals(type)) { + sc.add(objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("byte".equals(type)) { + sc.add(objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName + + "\", strict ) );"); + } else if ("String".equals(type) || "Boolean".equals(type)) { // TODO: other Primitive types - sc.add( objectName + "." + setterName + "( " + parserGetter + " );" ); - } - else if ( "Date".equals( type ) ) - { - sc.add( "String dateFormat = " - + ( xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null" ) + ";" ); - sc.add( objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName - + "\", dateFormat ) );" ); - } - else if ( "DOM".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( writeElementToXpp3Dom( " + childElementName + " ) );" ); + sc.add(objectName + "." + setterName + "( " + parserGetter + " );"); + } else if ("Date".equals(type)) { + sc.add("String dateFormat = " + + (xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null") + + ";"); + sc.add(objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName + + "\", dateFormat ) );"); + } else if ("DOM".equals(type)) { + sc.add(objectName + "." + setterName + "( writeElementToXpp3Dom( " + childElementName + " ) );"); requiresDomSupport = true; - } - else - { - throw new IllegalArgumentException( "Unknown type: " + type ); + } else { + throw new IllegalArgumentException("Unknown type: " + type); } } - private void writeHelpers( JClass jClass ) - { - JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null ); + private void writeHelpers(JClass jClass) { + JMethod method = new JMethod("getTrimmedValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "s = s.trim();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = s.trim();"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- -/* TODO - method = new JMethod( new JClass( "String" ), "getRequiredAttributeValue" ); - method.addException( new JClass( "XmlPullParserException" ) ); - method.getModifiers().makePrivate(); + /* TODO + method = new JMethod( new JClass( "String" ), "getRequiredAttributeValue" ); + method.addException( new JClass( "XmlPullParserException" ) ); + method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( JClass.Boolean, "strict" ) ); + method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); + method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); + method.addParameter( new JParameter( JClass.Boolean, "strict" ) ); - sc = method.getSourceCode(); + sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add( "if ( s == null )" ); - sc.add( "{" ); - sc.indent(); + sc.add( "{" ); + sc.indent(); - sc.add( "if ( strict )" ); + sc.add( "if ( strict )" ); - sc.add( "{" ); - sc.addIndented( - "throw new XmlPullParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser, null );" ); - sc.add( "}" ); + sc.add( "{" ); + sc.addIndented( + "throw new XmlPullParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser, null );" ); + sc.add( "}" ); - sc.unindent(); - sc.add( "}" ); + sc.unindent(); + sc.add( "}" ); - sc.add( "return s;" ); + sc.add( "return s;" ); - jClass.addMethod( method ); -*/ + jClass.addMethod( method ); + */ // -------------------------------------------------------------------- - method = new JMethod( "getBooleanValue", JType.BOOLEAN, null ); + method = new JMethod("getBooleanValue", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return Boolean.valueOf( s ).booleanValue();"); + sc.add("}"); - sc.add( "return false;" ); + sc.add("return false;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getCharacterValue", JType.CHAR, null ); + method = new JMethod("getCharacterValue", JType.CHAR, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return s.charAt( 0 );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return s.charAt( 0 );"); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" ); + method = convertNumericalType("getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", - "a short integer" ); + method = convertNumericalType( + "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", "a short integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" ); + method = convertNumericalType("getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" ); + method = convertNumericalType("getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", - "a floating point number" ); + method = convertNumericalType( + "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", - "a floating point number" ); + method = convertNumericalType( + "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null ); + method = new JMethod("getDateValue", new JClass("java.util.Date"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "dateFormat" ) ); - method.addException( new JClass( "DocumentException" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("String"), "dateFormat")); + method.addException(new JClass("DocumentException")); - writeDateParsingHelper( method.getSourceCode(), "new DocumentException( e.getMessage(), e )" ); + writeDateParsingHelper(method.getSourceCode(), "new DocumentException( e.getMessage(), e )"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null ); + method = new JMethod("checkFieldWithDuplicate", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Element" ), "element" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "alias" ) ); - method.addParameter( new JParameter( new JClass( "java.util.Set" ), "parsed" ) ); - method.addException( new JClass( "DocumentException" ) ); + method.addParameter(new JParameter(new JClass("Element"), "element")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(new JClass("String"), "alias")); + method.addParameter(new JParameter(new JClass("java.util.Set"), "parsed")); + method.addException(new JClass("DocumentException")); sc = method.getSourceCode(); - sc.add( "if ( !( element.getName().equals( tagName ) || element.getName().equals( alias ) ) )" ); + sc.add("if ( !( element.getName().equals( tagName ) || element.getName().equals( alias ) ) )"); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); - sc.add( "if ( !parsed.add( tagName ) )" ); + sc.add("if ( !parsed.add( tagName ) )"); - sc.add( "{" ); - sc.addIndented( "throw new DocumentException( \"Duplicated tag: '\" + tagName + \"'\" );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new DocumentException( \"Duplicated tag: '\" + tagName + \"'\" );"); + sc.add("}"); - sc.add( "return true;" ); + sc.add("return true;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownElement", null, null ); + method = new JMethod("checkUnknownElement", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Element" ), "element" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "DocumentException" ) ); + method.addParameter(new JParameter(new JClass("Element"), "element")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("DocumentException")); sc = method.getSourceCode(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new DocumentException( \"Unrecognised tag: '\" + element.getName() + \"'\" );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new DocumentException( \"Unrecognised tag: '\" + element.getName() + \"'\" );"); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private void writeDomHelpers( JClass jClass ) - { - JMethod method = new JMethod( "writeElementToXpp3Dom", new JClass( "Xpp3Dom" ), null ); + private void writeDomHelpers(JClass jClass) { + JMethod method = new JMethod("writeElementToXpp3Dom", new JClass("Xpp3Dom"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Element" ), "element" ) ); + method.addParameter(new JParameter(new JClass("Element"), "element")); JSourceCode sc = method.getSourceCode(); - sc.add( "Xpp3Dom xpp3Dom = new Xpp3Dom( element.getName() );" ); + sc.add("Xpp3Dom xpp3Dom = new Xpp3Dom( element.getName() );"); - sc.add( "if ( element.elements().isEmpty() && element.getText() != null )" ); - sc.add( "{" ); - sc.addIndented( "xpp3Dom.setValue( element.getText() );" ); - sc.add( "}" ); + sc.add("if ( element.elements().isEmpty() && element.getText() != null )"); + sc.add("{"); + sc.addIndented("xpp3Dom.setValue( element.getText() );"); + sc.add("}"); - sc.add( "for ( Iterator i = element.attributeIterator(); i.hasNext(); )" ); - sc.add( "{" ); + sc.add("for ( Iterator i = element.attributeIterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "Attribute attribute = (Attribute) i.next();" ); - sc.add( "xpp3Dom.setAttribute( attribute.getName(), attribute.getValue() );" ); + sc.add("Attribute attribute = (Attribute) i.next();"); + sc.add("xpp3Dom.setAttribute( attribute.getName(), attribute.getValue() );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); // TODO: would be nice to track whitespace in here - sc.add( "for ( Iterator i = element.elementIterator(); i.hasNext(); )" ); - sc.add( "{" ); + sc.add("for ( Iterator i = element.elementIterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "Element child = (Element) i.next();" ); - sc.add( "xpp3Dom.addChild( writeElementToXpp3Dom( child ) );" ); + sc.add("Element child = (Element) i.next();"); + sc.add("xpp3Dom.addChild( writeElementToXpp3Dom( child ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return xpp3Dom;" ); + sc.add("return xpp3Dom;"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc ) - { - JMethod method = new JMethod( methodName, returnType, null ); - method.addException( new JClass( "DocumentException" ) ); + private JMethod convertNumericalType(String methodName, JType returnType, String expression, String typeDesc) { + JMethod method = new JMethod(methodName, returnType, null); + method.addException(new JClass("DocumentException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(JClass.BOOLEAN, "strict")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "try" ); + sc.add("try"); - sc.add( "{" ); - sc.addIndented( "return " + expression + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return " + expression + ";"); + sc.add("}"); - sc.add( "catch ( NumberFormatException nfe )" ); + sc.add("catch ( NumberFormatException nfe )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new DocumentException( \"Unable to parse element '\" + attribute + \"', must be " - + typeDesc + "\", nfe );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new DocumentException( \"Unable to parse element '\" + attribute + \"', must be " + + typeDesc + "\", nfe );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); return method; } diff --git a/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jWriterGenerator.java b/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jWriterGenerator.java index 49f4307af..98ebe1d61 100644 --- a/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jWriterGenerator.java +++ b/modello-plugins/modello-plugin-dom4j/src/main/java/org/codehaus/modello/plugin/dom4j/Dom4jWriterGenerator.java @@ -22,6 +22,10 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -42,10 +46,6 @@ import org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata; import org.codehaus.plexus.component.annotations.Component; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - /** *

* Generate a writer that uses Dom4J. @@ -54,443 +54,400 @@ * * @author Brett Porter */ -@Component( role = ModelloGenerator.class, hint = "dom4j-writer" ) -public class Dom4jWriterGenerator - extends AbstractXmlJavaGenerator -{ +@Component(role = ModelloGenerator.class, hint = "dom4j-writer") +public class Dom4jWriterGenerator extends AbstractXmlJavaGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateDom4jWriter(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating Dom4j Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating Dom4j Writer.", ex); } } - private void generateDom4jWriter() - throws ModelloException, IOException - { + private void generateDom4jWriter() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.dom4j"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.dom4j"; - String marshallerName = getFileName( "Dom4jWriter" ); + String marshallerName = getFileName("Dom4jWriter"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.Writer" ); - jClass.addImport( "java.util.Arrays" ); - jClass.addImport( "java.util.Iterator" ); - jClass.addImport( "java.util.Locale" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "org.dom4j.Document" ); - jClass.addImport( "org.dom4j.DocumentException" ); - jClass.addImport( "org.dom4j.DocumentFactory" ); - jClass.addImport( "org.dom4j.Element" ); - jClass.addImport( "org.dom4j.io.OutputFormat" ); - jClass.addImport( "org.dom4j.io.XMLWriter" ); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.Writer"); + jClass.addImport("java.util.Arrays"); + jClass.addImport("java.util.Iterator"); + jClass.addImport("java.util.Locale"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("org.dom4j.Document"); + jClass.addImport("org.dom4j.DocumentException"); + jClass.addImport("org.dom4j.DocumentFactory"); + jClass.addImport("org.dom4j.Element"); + jClass.addImport("org.dom4j.io.OutputFormat"); + jClass.addImport("org.dom4j.io.XMLWriter"); - addModelImports( jClass, null ); + addModelImports(jClass, null); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - String rootElement = resolveTagName( rootClass ); - String variableName = uncapitalise( root ); + String rootElement = resolveTagName(rootClass); + String variableName = uncapitalise(root); // ---------------------------------------------------------------------- // Write the write( Reader, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), variableName ) ); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), variableName)); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "Document document = new DocumentFactory().createDocument();" ); + sc.add("Document document = new DocumentFactory().createDocument();"); - sc.add( "write" + root + "( " + variableName + ", \"" + rootElement + "\", document );" ); + sc.add("write" + root + "( " + variableName + ", \"" + rootElement + "\", document );"); // TODO: pretty printing optional - sc.add( "OutputFormat format = OutputFormat.createPrettyPrint();" ); - sc.add( "format.setLineSeparator( System.getProperty( \"line.separator\" ) );" ); - sc.add( "XMLWriter serializer = new XMLWriter( writer, format );" ); + sc.add("OutputFormat format = OutputFormat.createPrettyPrint();"); + sc.add("format.setLineSeparator( System.getProperty( \"line.separator\" ) );"); + sc.add("XMLWriter serializer = new XMLWriter( writer, format );"); - sc.add( "serializer.write( document );" ); + sc.add("serializer.write( document );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), variableName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), variableName)); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); sc = marshall.getSourceCode(); - sc.add( "Document document = new DocumentFactory().createDocument();" ); + sc.add("Document document = new DocumentFactory().createDocument();"); - sc.add( "write" + root + "( " + variableName + ", \"" + rootElement + "\", document );" ); + sc.add("write" + root + "( " + variableName + ", \"" + rootElement + "\", document );"); // TODO: pretty printing optional - sc.add( "OutputFormat format = OutputFormat.createPrettyPrint();" ); - sc.add( "format.setLineSeparator( System.getProperty( \"line.separator\" ) );" ); - sc.add( "format.setEncoding( " + variableName + ".getModelEncoding() );" ); - sc.add( "XMLWriter serializer = new XMLWriter( stream, format );" ); + sc.add("OutputFormat format = OutputFormat.createPrettyPrint();"); + sc.add("format.setLineSeparator( System.getProperty( \"line.separator\" ) );"); + sc.add("format.setEncoding( " + variableName + ".getModelEncoding() );"); + sc.add("XMLWriter serializer = new XMLWriter( stream, format );"); - sc.add( "serializer.write( document );" ); + sc.add("serializer.write( document );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); - if ( requiresDomSupport ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); - writeDomHelpers( jClass ); + if (requiresDomSupport) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); + writeDomHelpers(jClass); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); marshall.getModifiers().makePrivate(); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("String"), "tagName")); - ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); - marshall.addParameter( new JParameter( new JClass( "org.dom4j.Branch" ), "parentElement" ) ); + marshall.addParameter(new JParameter(new JClass("org.dom4j.Branch"), "parentElement")); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "if ( " + uncapClassName + " != null )" ); + sc.add("if ( " + uncapClassName + " != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID ); + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) modelClass.getModel().getMetadata(XmlModelMetadata.ID); // add namespace information for root element only - if ( classMetadata.isRootElement() && ( xmlModelMetadata.getNamespace() != null ) ) - { - String namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() ); - sc.add( "Element element = parentElement.addElement( tagName, \"" + namespace + "\" );" ); - - if ( xmlModelMetadata.getSchemaLocation() != null ) - { - String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); - - sc.add( "element.addAttribute( \"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); - sc.add( - "element.addAttribute( \"xsi:schemaLocation\", \"" + namespace + " " + url + "\" );" ); + if (classMetadata.isRootElement() && (xmlModelMetadata.getNamespace() != null)) { + String namespace = xmlModelMetadata.getNamespace(getGeneratedVersion()); + sc.add("Element element = parentElement.addElement( tagName, \"" + namespace + "\" );"); + + if (xmlModelMetadata.getSchemaLocation() != null) { + String url = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); + + sc.add("element.addAttribute( \"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); + sc.add("element.addAttribute( \"xsi:schemaLocation\", \"" + namespace + " " + url + "\" );"); } - } - else - { - sc.add( "Element element = parentElement.addElement( tagName );" ); + } else { + sc.add("Element element = parentElement.addElement( tagName );"); } ModelField contentField = null; String contentValue = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // XML attributes - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); - sc.addIndented( "element.addAttribute( \"" + fieldTagName + "\", " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("element.addAttribute( \"" + fieldTagName + "\", " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("}"); } } - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - sc.add( "element.setText( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + " );" ); + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + sc.add("element.setText( " + getValue(contentField.getType(), contentValue, xmlFieldMetadata) + " );"); } // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // skip field with type Content continue; } - if ( !xmlFieldMetadata.isAttribute() ) - { - processField( field, xmlFieldMetadata, uncapClassName, sc, modelClass, jClass ); + if (!xmlFieldMetadata.isAttribute()) { + processField(field, xmlFieldMetadata, uncapClassName, sc, modelClass, jClass); } } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, String uncapClassName, - JSourceCode sc, ModelClass modelClass, JClass jClass ) - throws ModelloException - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + String uncapClassName, + JSourceCode sc, + ModelClass modelClass, + JClass jClass) + throws ModelloException { + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); - sc.addIndented( "write" + association.getTo() + "( " + value + ", \"" + fieldTagName + "\", element );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented("write" + association.getTo() + "( " + value + ", \"" + fieldTagName + "\", element );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); type = association.getType(); String toType = association.getTo(); boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( getValueChecker( type, value, association ) ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = element;" ); + sc.add("Element listElement = element;"); - if ( wrappedItems ) - { - sc.add( "listElement = element.addElement( \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("listElement = element.addElement( \"" + fieldTagName + "\" );"); } - sc.add( "for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( toType + " o = (" + toType + ") iter.next();" ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add(toType + " o = (" + toType + ") iter.next();"); - sc.add( "write" + toType + "( o, \"" + valuesTagName + "\", listElement );" ); - } - else - { - sc.add( toType + " " + singular( uncapitalise( field.getName() ) ) + " = (" + toType - + ") iter.next();" ); + sc.add("write" + toType + "( o, \"" + valuesTagName + "\", listElement );"); + } else { + sc.add(toType + " " + singular(uncapitalise(field.getName())) + " = (" + toType + + ") iter.next();"); - sc.add( "listElement.addElement( \"" + valuesTagName + "\" ).setText( " - + singular( uncapitalise( field.getName() ) ) + " );" ); + sc.add("listElement.addElement( \"" + valuesTagName + "\" ).setText( " + + singular(uncapitalise(field.getName())) + " );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = element;" ); + sc.add("Element listElement = element;"); - if ( wrappedItems ) - { - sc.add( "listElement = element.addElement( \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("listElement = element.addElement( \"" + fieldTagName + "\" );"); } - sc.add( "for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = (String) iter.next();" ); + sc.add("String key = (String) iter.next();"); - sc.add( "String value = (String) " + value + ".get( key );" ); + sc.add("String value = (String) " + value + ".get( key );"); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "Element assocElement = listElement.addElement( \"" + singular( associationName ) - + "\" );" ); - sc.add( "assocElement.addElement( \"key\" ).setText( key );" ); - sc.add( "assocElement.addElement( \"value\" ).setText( value );" ); - } - else - { - sc.add( "listElement.addElement( key ).setText( value );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("Element assocElement = listElement.addElement( \"" + singular(associationName) + + "\" );"); + sc.add("assocElement.addElement( \"key\" ).setText( key );"); + sc.add("assocElement.addElement( \"value\" ).setText( value );"); + } else { + sc.add("listElement.addElement( key ).setText( value );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); + } else { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( "DOM".equals( field.getType() ) ) - { - sc.add( "writeXpp3DomToElement( (Xpp3Dom) " + value + ", element );" ); + if ("DOM".equals(field.getType())) { + sc.add("writeXpp3DomToElement( (Xpp3Dom) " + value + ", element );"); requiresDomSupport = true; - } - else - { - sc.add( "element.addElement( \"" + fieldTagName + "\" ).setText( " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); + } else { + sc.add("element.addElement( \"" + fieldTagName + "\" ).setText( " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - private void writeDomHelpers( JClass jClass ) - { - JMethod method = new JMethod( "writeXpp3DomToElement" ); + private void writeDomHelpers(JClass jClass) { + JMethod method = new JMethod("writeXpp3DomToElement"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Xpp3Dom" ), "xpp3Dom" ) ); - method.addParameter( new JParameter( new JClass( "Element" ), "parentElement" ) ); + method.addParameter(new JParameter(new JClass("Xpp3Dom"), "xpp3Dom")); + method.addParameter(new JParameter(new JClass("Element"), "parentElement")); JSourceCode sc = method.getSourceCode(); - sc.add( "Element element = parentElement.addElement( xpp3Dom.getName() );" ); + sc.add("Element element = parentElement.addElement( xpp3Dom.getName() );"); - sc.add( "if ( xpp3Dom.getValue() != null )" ); - sc.add( "{" ); - sc.addIndented( "element.setText( xpp3Dom.getValue() );" ); - sc.add( "}" ); + sc.add("if ( xpp3Dom.getValue() != null )"); + sc.add("{"); + sc.addIndented("element.setText( xpp3Dom.getValue() );"); + sc.add("}"); - sc.add( "for ( Iterator i = Arrays.asList( xpp3Dom.getAttributeNames() ).iterator(); i.hasNext(); )" ); - sc.add( "{" ); + sc.add("for ( Iterator i = Arrays.asList( xpp3Dom.getAttributeNames() ).iterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "String name = (String) i.next();" ); - sc.add( "element.addAttribute( name, xpp3Dom.getAttribute( name ) );" ); + sc.add("String name = (String) i.next();"); + sc.add("element.addAttribute( name, xpp3Dom.getAttribute( name ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "for ( Iterator i = Arrays.asList( xpp3Dom.getChildren() ).iterator(); i.hasNext(); )" ); - sc.add( "{" ); + sc.add("for ( Iterator i = Arrays.asList( xpp3Dom.getChildren() ).iterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "Xpp3Dom child = (Xpp3Dom) i.next();" ); - sc.add( "writeXpp3DomToElement( child, element );" ); + sc.add("Xpp3Dom child = (Xpp3Dom) i.next();"); + sc.add("writeXpp3DomToElement( child, element );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); } } diff --git a/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/Dom4jGeneratorTest.java b/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/Dom4jGeneratorTest.java index 5da68baf8..d511c6112 100644 --- a/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/Dom4jGeneratorTest.java +++ b/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/Dom4jGeneratorTest.java @@ -22,6 +22,9 @@ * SOFTWARE. */ +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; @@ -30,70 +33,61 @@ import org.codehaus.modello.model.Version; import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata; -import java.util.List; -import java.util.Properties; - /** * Test the generators. * * @author Brett Porter */ -public class Dom4jGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public Dom4jGeneratorTest() - { - super( "dom4j" ); +public class Dom4jGeneratorTest extends AbstractModelloJavaGeneratorTest { + public Dom4jGeneratorTest() { + super("dom4j"); } - public void testDom4jGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testDom4jGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 27, classesList.size() ); + assertEquals(27, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "dom4j-writer", parameters ); - modello.generate( model, "dom4j-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "dom4j-writer", parameters); + modello.generate(model, "dom4j-reader", parameters); - addDependency( "dom4j", "dom4j" ); + addDependency("dom4j", "dom4j"); compileGeneratedSources(); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.dom4j.Dom4jVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.dom4j.Dom4jVerifier"); } - } diff --git a/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/FeaturesDom4jGeneratorTest.java b/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/FeaturesDom4jGeneratorTest.java index 52445ab72..675e06d83 100644 --- a/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/FeaturesDom4jGeneratorTest.java +++ b/modello-plugins/modello-plugin-dom4j/src/test/java/org/codehaus/modello/plugin/dom4j/FeaturesDom4jGeneratorTest.java @@ -22,40 +22,35 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesDom4jGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesDom4jGeneratorTest() - { - super( "features" ); +public class FeaturesDom4jGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesDom4jGeneratorTest() { + super("features"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "dom4j-writer", parameters ); - modello.generate( model, "dom4j-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "dom4j-writer", parameters); + modello.generate(model, "dom4j-reader", parameters); - addDependency( "dom4j", "dom4j" ); - addDependency( "org.xmlunit", "xmlunit-core" ); - compileGeneratedSources( 5 ); + addDependency("dom4j", "dom4j"); + addDependency("org.xmlunit", "xmlunit-core"); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.dom4j.Dom4jFeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.dom4j.Dom4jFeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-jackson/pom.xml b/modello-plugins/modello-plugin-jackson/pom.xml index 1efae7ad4..6a59bd5dc 100644 --- a/modello-plugins/modello-plugin-jackson/pom.xml +++ b/modello-plugins/modello-plugin-jackson/pom.xml @@ -1,28 +1,18 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-jackson Modello Jackson Plugin Modello Jackson Plugin generates JSON readers and writers based on Jackson Streaming APIs, plus reader delegates to be able to read multiple model versions. - - - - org.apache.maven.plugins - maven-dependency-plugin - - - - - - + @@ -50,4 +40,13 @@ jackson-annotations + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + diff --git a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/AbstractJacksonGenerator.java b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/AbstractJacksonGenerator.java index dda44d3a3..f8d87dcfc 100644 --- a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/AbstractJacksonGenerator.java +++ b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/AbstractJacksonGenerator.java @@ -27,7 +27,4 @@ /** * @author Simone Tripodi */ -public abstract class AbstractJacksonGenerator - extends AbstractXmlJavaGenerator -{ -} +public abstract class AbstractJacksonGenerator extends AbstractXmlJavaGenerator {} diff --git a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonExtendedReaderGenerator.java b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonExtendedReaderGenerator.java index f794eb21f..ccbd2c42e 100644 --- a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonExtendedReaderGenerator.java +++ b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonExtendedReaderGenerator.java @@ -29,20 +29,15 @@ * * @author Simone Tripodi */ -public class JacksonExtendedReaderGenerator - extends JacksonReaderGenerator -{ +public class JacksonExtendedReaderGenerator extends JacksonReaderGenerator { @Override - protected boolean isRelevant( ModelClass modelClass ) - { - return isJavaEnabled( modelClass ); + protected boolean isRelevant(ModelClass modelClass) { + return isJavaEnabled(modelClass); } @Override - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return true; } - } diff --git a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonReaderGenerator.java b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonReaderGenerator.java index c8e0a93a2..9e02ecb9f 100644 --- a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonReaderGenerator.java +++ b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonReaderGenerator.java @@ -53,10 +53,8 @@ /** * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "jackson-reader" ) -public class JacksonReaderGenerator - extends AbstractJacksonGenerator -{ +@Component(role = ModelloGenerator.class, hint = "jackson-reader") +public class JacksonReaderGenerator extends AbstractJacksonGenerator { private static final String SOURCE_PARAM = "source"; @@ -72,90 +70,74 @@ public class JacksonReaderGenerator private String trackingArgs; - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return false; } - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; locationTracker = sourceTracker = null; trackingArgs = locationField = ""; - if ( isLocationTracking() ) - { - locationTracker = model.getLocationTracker( getGeneratedVersion() ); - if ( locationTracker == null ) - { - throw new ModelloException( "No model class has been marked as location tracker" - + " via the attribute locationTracker=\"locations\"" - + ", cannot generate extended reader." ); + if (isLocationTracking()) { + locationTracker = model.getLocationTracker(getGeneratedVersion()); + if (locationTracker == null) { + throw new ModelloException("No model class has been marked as location tracker" + + " via the attribute locationTracker=\"locations\"" + + ", cannot generate extended reader."); } locationField = - ( (ModelClassMetadata) locationTracker.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); + ((ModelClassMetadata) locationTracker.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); - sourceTracker = model.getSourceTracker( getGeneratedVersion() ); + sourceTracker = model.getSourceTracker(getGeneratedVersion()); - if ( sourceTracker != null ) - { + if (sourceTracker != null) { trackingArgs += ", " + SOURCE_PARAM; } } - try - { + try { generateJacksonReader(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating Jackson Reader.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating Jackson Reader.", ex); } } - private void writeAllClassesReaders( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesReaders(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassReaders( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassReaders(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassReaders(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } - XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata( XmlClassMetadata.ID ); - if ( !rootElement && !xmlClassMetadata.isStandaloneRead() ) - { + XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata(XmlClassMetadata.ID); + if (!rootElement && !xmlClassMetadata.isStandaloneRead()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); String readerMethodName = "read"; - if ( !rootElement ) - { + if (!rootElement) { readerMethodName += capClassName; } @@ -163,278 +145,267 @@ private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean ro // Write the read(JsonParser) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + JMethod unmarshall = new JMethod(readerMethodName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); JSourceCode sc = unmarshall.getSourceCode(); - String variableName = uncapitalise( className ); + String variableName = uncapitalise(className); - sc.add( - className + ' ' + variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );" ); + sc.add(className + ' ' + variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );"); - if ( rootElement ) - { + if (rootElement) { // TODO // sc.add( variableName + ".setModelEncoding( parser.getInputEncoding() );" ); } - sc.add( "return " + variableName + ';' ); + sc.add("return " + variableName + ';'); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(Reader[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "JsonParser parser = factory.createParser( reader );" ); + sc.add("JsonParser parser = factory.createParser( reader );"); - sc.add( "return " + readerMethodName + "( parser, strict );" ); + sc.add("return " + readerMethodName + "( parser, strict );"); - jClass.addMethod( unmarshall );unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + jClass.addMethod(unmarshall); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( reader, true );" ); + sc.add("return " + readerMethodName + "( reader, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(InputStream[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( new InputStreamReader( in ), strict" + trackingArgs + " );" ); + sc.add("return " + readerMethodName + "( new InputStreamReader( in ), strict" + trackingArgs + " );"); - jClass.addMethod( unmarshall );unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + jClass.addMethod(unmarshall); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( in, true );" ); + sc.add("return " + readerMethodName + "( in, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // -------------------------------------------------------------------- } - private void generateJacksonReader() - throws ModelloException, IOException - { + private void generateJacksonReader() throws ModelloException, IOException { Model objectModel = getModel(); String packageName = - objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) + ".io.jackson"; + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.jackson"; - String unmarshallerName = getFileName( "JacksonReader" + ( isLocationTracking() ? "Ex" : "" ) ); + String unmarshallerName = getFileName("JacksonReader" + (isLocationTracking() ? "Ex" : "")); - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + unmarshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "com.fasterxml.jackson.core.JsonFactory" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonParser" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonParser.Feature" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonParseException" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonToken" ); - jClass.addImport( "java.io.InputStream" ); - jClass.addImport( "java.io.InputStreamReader" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.util.Set" ); - jClass.addImport( "java.util.HashSet" ); + jClass.addImport("com.fasterxml.jackson.core.JsonFactory"); + jClass.addImport("com.fasterxml.jackson.core.JsonParser"); + jClass.addImport("com.fasterxml.jackson.core.JsonParser.Feature"); + jClass.addImport("com.fasterxml.jackson.core.JsonParseException"); + jClass.addImport("com.fasterxml.jackson.core.JsonToken"); + jClass.addImport("java.io.InputStream"); + jClass.addImport("java.io.InputStreamReader"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.util.Set"); + jClass.addImport("java.util.HashSet"); - addModelImports( jClass, null ); + addModelImports(jClass, null); - JField factoryField = new JField( new JClass( "JsonFactory" ), "factory" ); - factoryField.getModifiers().setFinal( true ); - factoryField.setInitString( "new JsonFactory()" ); - jClass.addField( factoryField ); + JField factoryField = new JField(new JClass("JsonFactory"), "factory"); + factoryField.getModifiers().setFinal(true); + factoryField.setInitString("new JsonFactory()"); + jClass.addField(factoryField); - JConstructor jacksonReaderConstructor = new JConstructor( jClass ); + JConstructor jacksonReaderConstructor = new JConstructor(jClass); JSourceCode sc = jacksonReaderConstructor.getSourceCode(); - sc.add( "factory.enable( Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER );" ); - sc.add( "factory.enable( Feature.ALLOW_COMMENTS );" ); - sc.add( "factory.enable( Feature.ALLOW_NON_NUMERIC_NUMBERS );" ); - sc.add( "factory.enable( Feature.ALLOW_NUMERIC_LEADING_ZEROS );" ); - sc.add( "factory.enable( Feature.ALLOW_SINGLE_QUOTES );" ); - sc.add( "factory.enable( Feature.ALLOW_UNQUOTED_CONTROL_CHARS );" ); - sc.add( "factory.enable( Feature.ALLOW_UNQUOTED_FIELD_NAMES );" ); + sc.add("factory.enable( Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER );"); + sc.add("factory.enable( Feature.ALLOW_COMMENTS );"); + sc.add("factory.enable( Feature.ALLOW_NON_NUMERIC_NUMBERS );"); + sc.add("factory.enable( Feature.ALLOW_NUMERIC_LEADING_ZEROS );"); + sc.add("factory.enable( Feature.ALLOW_SINGLE_QUOTES );"); + sc.add("factory.enable( Feature.ALLOW_UNQUOTED_CONTROL_CHARS );"); + sc.add("factory.enable( Feature.ALLOW_UNQUOTED_FIELD_NAMES );"); - jClass.addConstructor( jacksonReaderConstructor ); + jClass.addConstructor(jacksonReaderConstructor); // ---------------------------------------------------------------------- // Write the class parsers // ---------------------------------------------------------------------- - writeAllClassesParser( objectModel, jClass ); + writeAllClassesParser(objectModel, jClass); // ---------------------------------------------------------------------- // Write the class readers // ---------------------------------------------------------------------- - writeAllClassesReaders( objectModel, jClass ); + writeAllClassesReaders(objectModel, jClass); // ---------------------------------------------------------------------- // Write helpers // ---------------------------------------------------------------------- - writeHelpers( jClass ); + writeHelpers(jClass); // ---------------------------------------------------------------------- // DOM support // ---------------------------------------------------------------------- - if ( requiresDomSupport ) - { - jClass.addImport( "com.fasterxml.jackson.databind.ObjectMapper" ); + if (requiresDomSupport) { + jClass.addImport("com.fasterxml.jackson.databind.ObjectMapper"); - sc.add( "factory.setCodec( new ObjectMapper() );" ); + sc.add("factory.setCodec( new ObjectMapper() );"); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClassesParser( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesParser(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassParser(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassParser(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null ); + JMethod unmarshall = new JMethod("parse" + capClassName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( "if ( JsonToken.START_OBJECT != parser.getCurrentToken() && JsonToken.START_OBJECT != parser.nextToken() )" ); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Expected '" - + className - + "' data to start with an Object\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + sc.add( + "if ( JsonToken.START_OBJECT != parser.getCurrentToken() && JsonToken.START_OBJECT != parser.nextToken() )"); + sc.add("{"); + sc.addIndented("throw new JsonParseException( \"Expected '" + + className + + "' data to start with an Object\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( className + " " + uncapClassName + " = new " + className + "();" ); + sc.add(className + " " + uncapClassName + " = new " + className + "();"); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + ";" ); - writeNewSetLocation( "\"\"", uncapClassName, null, sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + ";"); + writeNewSetLocation("\"\"", uncapClassName, null, sc); } - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); { - //Write other fields + // Write other fields - sc.add( "Set parsed = new HashSet();" ); + sc.add("Set parsed = new HashSet();"); - sc.add( "while ( JsonToken.END_OBJECT != parser.nextToken() )" ); + sc.add("while ( JsonToken.END_OBJECT != parser.nextToken() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); boolean addElse = false; - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass ); + processField(field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass); addElse = true; } - if ( addElse ) - { - sc.add( "else" ); + if (addElse) { + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.indent(); } - sc.add( "checkUnknownElement( parser, strict );" ); + sc.add("checkUnknownElement( parser, strict );"); - if ( addElse ) - { + if (addElse) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "return " + uncapClassName + ";" ); + sc.add("return " + uncapClassName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } /** @@ -447,570 +418,531 @@ private void writeClassParser( ModelClass modelClass, JClass jClass, boolean roo * @param objectName the object name in the source * @param jClass the generated class source file */ - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc, - String objectName, JClass jClass ) - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + boolean addElse, + JSourceCode sc, + String objectName, + JClass jClass) { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String capFieldName = capitalise( field.getName() ); + String capFieldName = capitalise(field.getName()); - String singularName = singular( field.getName() ); + String singularName = singular(field.getName()); String alias; - if ( StringUtils.isEmpty( field.getAlias() ) ) - { + if (StringUtils.isEmpty(field.getAlias())) { alias = "null"; - } - else - { + } else { alias = "\"" + field.getAlias() + "\""; } - String tagComparison = - ( addElse ? "else " : "" ) + "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + "\", " + alias - + ", parsed ) )"; + String tagComparison = (addElse ? "else " : "") + "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + + "\", " + alias + ", parsed ) )"; - if ( !( field instanceof ModelAssociation ) ) - { // model field - sc.add( tagComparison ); + if (!(field instanceof ModelAssociation)) { // model field + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writePrimitiveField( field, field.getType(), objectName, objectName, "\"" + field.getName() + "\"", - "set" + capFieldName, sc, false ); + writePrimitiveField( + field, + field.getType(), + objectName, + objectName, + "\"" + field.getName() + "\"", + "set" + capFieldName, + sc, + false); sc.unindent(); - sc.add( "}" ); - } - else - { // model association + sc.add("}"); + } else { // model association ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( tagComparison ); + if (association.isOneMultiplicity()) { + sc.add(tagComparison); - sc.add( "{" ); - sc.addIndented( - objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict" - + trackingArgs + " ) );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented(objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict" + + trackingArgs + " ) );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); String type = association.getType(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - boolean inModel = isClassInModel( association.getTo(), field.getModelClass().getModel() ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + boolean inModel = isClassInModel( + association.getTo(), field.getModelClass().getModel()); - sc.add( ( addElse ? "else " : "" ) + "if ( checkFieldWithDuplicate( parser, \"" + sc.add((addElse ? "else " : "") + "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + "\", " + alias - + ", parsed ) )" ); + + ", parsed ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( JsonToken.START_ARRAY != parser.nextToken() )" ); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Expected '" - + fieldTagName - + "' data to start with an Array\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + sc.add("if ( JsonToken.START_ARRAY != parser.nextToken() )"); + sc.add("{"); + sc.addIndented("throw new JsonParseException( \"Expected '" + + fieldTagName + + "' data to start with an Array\", parser.getCurrentLocation() );"); + sc.add("}"); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) association.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) association.getMetadata(JavaFieldMetadata.ID); String adder; - if ( javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter() ) - { - sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" ); + if (javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter()) { + sc.add(type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();"); - sc.add( "if ( " + associationName + " == null )" ); + sc.add("if ( " + associationName + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( associationName + " = " + association.getDefaultValue() + ";" ); + sc.add(associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } - if ( !inModel && locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" - + capitalise( singular( locationField ) ) + "( \"" + field.getName() - + "\" );" ); - sc.add( "if ( " + LOCATION_VAR + "s == null )" ); - sc.add( "{" ); + if (!inModel && locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" + + capitalise(singular(locationField)) + "( \"" + field.getName() + + "\" );"); + sc.add("if ( " + LOCATION_VAR + "s == null )"); + sc.add("{"); sc.indent(); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "while ( JsonToken.END_ARRAY != parser.nextToken() )" ); + sc.add("while ( JsonToken.END_ARRAY != parser.nextToken() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( inModel ) - { - sc.add( adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );" ); - } - else - { + if (inModel) { + sc.add(adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );"); + } else { String key; - if ( ModelDefault.SET.equals( type ) ) - { + if (ModelDefault.SET.equals(type)) { key = "?"; + } else { + key = (hasJavaSourceSupport(5) ? "Integer.valueOf" : "new java.lang.Integer") + "( " + + associationName + ".size() )"; } - else - { - key = ( hasJavaSourceSupport( 5 ) ? "Integer.valueOf" : "new java.lang.Integer" ) + "( " + associationName - + ".size() )"; - } - writePrimitiveField( association, association.getTo(), associationName, LOCATION_VAR + "s", key, - "add", sc, true ); + writePrimitiveField( + association, + association.getTo(), + associationName, + LOCATION_VAR + "s", + key, + "add", + sc, + true); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( tagComparison ); + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s;" ); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s;"); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); } - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "if ( JsonToken.START_ARRAY != parser.nextToken() )" ); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Expected '" - + fieldTagName - + "' data to start with an Array\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("if ( JsonToken.START_ARRAY != parser.nextToken() )"); + sc.add("{"); + sc.addIndented("throw new JsonParseException( \"Expected '" + + fieldTagName + + "' data to start with an Array\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( "// " + xmlAssociationMetadata.getMapStyle() + " mode." ); + sc.add("// " + xmlAssociationMetadata.getMapStyle() + " mode."); - sc.add( "while ( JsonToken.END_ARRAY != parser.nextToken() )" ); + sc.add("while ( JsonToken.END_ARRAY != parser.nextToken() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( JsonToken.START_OBJECT != parser.getCurrentToken() && JsonToken.START_OBJECT != parser.nextToken() )" ); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Expected '" - + fieldTagName - + "' item data to start with an Object\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + sc.add( + "if ( JsonToken.START_OBJECT != parser.getCurrentToken() && JsonToken.START_OBJECT != parser.nextToken() )"); + sc.add("{"); + sc.addIndented("throw new JsonParseException( \"Expected '" + + fieldTagName + + "' item data to start with an Object\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( "String key = null;" ); + sc.add("String key = null;"); - sc.add( "String value = null;" ); + sc.add("String value = null;"); - sc.add( "Set parsedPropertiesElements = new HashSet();" ); + sc.add("Set parsedPropertiesElements = new HashSet();"); - sc.add( "while ( JsonToken.END_OBJECT != parser.nextToken() )" ); + sc.add("while ( JsonToken.END_OBJECT != parser.nextToken() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( checkFieldWithDuplicate( parser, \"key\", \"\", parsedPropertiesElements ) )" ); + sc.add("if ( checkFieldWithDuplicate( parser, \"key\", \"\", parsedPropertiesElements ) )"); - sc.add( "{" ); - sc.addIndented( "parser.nextToken();" ); + sc.add("{"); + sc.addIndented("parser.nextToken();"); String parserGetter = "parser.getText()"; - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - sc.addIndented( "key = " + parserGetter + ";" ); - sc.add( "}" ); + sc.addIndented("key = " + parserGetter + ";"); + sc.add("}"); - sc.add( "else if ( checkFieldWithDuplicate( parser, \"value\", \"\", parsedPropertiesElements ) )" ); + sc.add( + "else if ( checkFieldWithDuplicate( parser, \"value\", \"\", parsedPropertiesElements ) )"); - sc.add( "{" ); - sc.addIndented( "parser.nextToken();" ); + sc.add("{"); + sc.addIndented("parser.nextToken();"); parserGetter = "parser.getText()"; - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - sc.addIndented( "value = " + parserGetter + ";" ); - sc.add( "}" ); + sc.addIndented("value = " + parserGetter + ";"); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.addIndented( "checkUnknownElement( parser, strict );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("checkUnknownElement( parser, strict );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); - } - else - { - //INLINE Mode + sc.add("}"); + } else { + // INLINE Mode - sc.add( "if ( JsonToken.START_OBJECT != parser.nextToken() )" ); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Expected '" - + fieldTagName - + "' data to start with an Object\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + sc.add("if ( JsonToken.START_OBJECT != parser.nextToken() )"); + sc.add("{"); + sc.addIndented("throw new JsonParseException( \"Expected '" + + fieldTagName + + "' data to start with an Object\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( "while ( JsonToken.END_OBJECT != parser.nextToken() )" ); + sc.add("while ( JsonToken.END_OBJECT != parser.nextToken() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = parser.getCurrentName();" ); + sc.add("String key = parser.getCurrentName();"); - writeNewSetLocation( "key", LOCATION_VAR + "s", null, sc ); + writeNewSetLocation("key", LOCATION_VAR + "s", null, sc); - sc.add( - "String value = parser.nextTextValue()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + sc.add("String value = parser.nextTextValue()" + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + + ";"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } } } - private void writePrimitiveField( ModelField field, String type, String objectName, String locatorName, - String locationKey, String setterName, JSourceCode sc, boolean wrappedItem ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + private void writePrimitiveField( + ModelField field, + String type, + String objectName, + String locatorName, + String locationKey, + String setterName, + JSourceCode sc, + boolean wrappedItem) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); String parserGetter = null; - if ( "boolean".equals( type ) || "Boolean".equals( type ) ) - { + if ("boolean".equals(type) || "Boolean".equals(type)) { parserGetter = "parser.getBooleanValue()"; - } - else if ( "int".equals( type ) || "Integer".equals( type ) ) - { + } else if ("int".equals(type) || "Integer".equals(type)) { parserGetter = "parser.getIntValue()"; - } - else if ( "short".equals( type ) || "Short".equals( type ) ) - { + } else if ("short".equals(type) || "Short".equals(type)) { parserGetter = "parser.getShortValue()"; - } - else if ( "long".equals( type ) || "Long".equals( type ) ) - { + } else if ("long".equals(type) || "Long".equals(type)) { parserGetter = "parser.getLongValue()"; - } - else if ( "double".equals( type ) || "Double".equals( type ) ) - { + } else if ("double".equals(type) || "Double".equals(type)) { parserGetter = "parser.getDoubleValue()"; - } - else if ( "float".equals( type ) || "Float".equals( type ) ) - { + } else if ("float".equals(type) || "Float".equals(type)) { parserGetter = "parser.getFloatValue()"; - } - else if ( "byte".equals( type ) ) - { + } else if ("byte".equals(type)) { parserGetter = "parser.getByteValue()"; - } - else if ( "String".equals( type ) ) - { + } else if ("String".equals(type)) { parserGetter = "parser.getText()"; - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - } - else if ( "DOM".equals( type ) ) - { + } else if ("DOM".equals(type)) { requiresDomSupport = true; parserGetter = "parser.readValueAsTree()"; - } - else - { - throw new IllegalArgumentException( "Unknown type " - + type - + " for field " - + field.getModelClass().getName() - + "." - + field.getName() ); + } else { + throw new IllegalArgumentException("Unknown type " + + type + + " for field " + + field.getModelClass().getName() + + "." + + field.getName()); } String keyCapture = ""; - writeNewLocation( null, sc ); - if ( locationTracker != null && "?".equals( locationKey ) ) - { - sc.add( "Object _key;" ); + writeNewLocation(null, sc); + if (locationTracker != null && "?".equals(locationKey)) { + sc.add("Object _key;"); locationKey = "_key"; keyCapture = "_key = "; - } - else - { - writeSetLocation( locationKey, locatorName, null, sc ); + } else { + writeSetLocation(locationKey, locatorName, null, sc); } // primitives token already consumed when in ARRAY loop - if ( !wrappedItem ) - { - sc.add( "parser.nextToken();" ); + if (!wrappedItem) { + sc.add("parser.nextToken();"); } - sc.add( objectName + "." + setterName + "( " + keyCapture + parserGetter + " );" ); + sc.add(objectName + "." + setterName + "( " + keyCapture + parserGetter + " );"); - if ( keyCapture.length() > 0 ) - { - writeSetLocation( locationKey, locatorName, null, sc ); + if (keyCapture.length() > 0) { + writeSetLocation(locationKey, locatorName, null, sc); } } - private void writeHelpers( JClass jClass ) - { - JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null ); + private void writeHelpers(JClass jClass) { + JMethod method = new JMethod("getTrimmedValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "s = s.trim();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = s.trim();"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null ); - method.addException( new JClass( "JsonParseException" ) ); + method = new JMethod("getRequiredAttributeValue", new JClass("String"), null); + method.addException(new JClass("JsonParseException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + method.addParameter(new JParameter(JClass.BOOLEAN, "strict")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new JsonParseException( \"Missing required value for attribute '\" + attribute + \"'\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + "throw new JsonParseException( \"Missing required value for attribute '\" + attribute + \"'\", parser.getCurrentLocation() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null ); + method = new JMethod("checkFieldWithDuplicate", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "alias" ) ); - method.addParameter( new JParameter( new JClass( "Set" ), "parsed" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(new JClass("String"), "alias")); + method.addParameter(new JParameter(new JClass("Set"), "parsed")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "String currentName = parser.getCurrentName();" ); + sc.add("String currentName = parser.getCurrentName();"); - sc.add( "" ); + sc.add(""); - sc.add( "if ( !( currentName.equals( tagName ) || currentName.equals( alias ) ) )" ); + sc.add("if ( !( currentName.equals( tagName ) || currentName.equals( alias ) ) )"); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); - sc.add( "if ( !parsed.add( tagName ) )" ); + sc.add("if ( !parsed.add( tagName ) )"); - sc.add( "{" ); - sc.addIndented( "throw new JsonParseException( \"Duplicated tag: '\" + tagName + \"'\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented( + "throw new JsonParseException( \"Duplicated tag: '\" + tagName + \"'\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( "return true;" ); + sc.add("return true;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownElement", null, null ); + method = new JMethod("checkUnknownElement", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new JsonParseException( \"Unrecognised tag: '\" + parser.getCurrentName() + \"'\", parser.getCurrentLocation() );" ); - sc.add( "}" ); + "throw new JsonParseException( \"Unrecognised tag: '\" + parser.getCurrentName() + \"'\", parser.getCurrentLocation() );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( "for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )" ); - sc.add( "{" ); + sc.add("for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )"); + sc.add("{"); sc.indent(); - sc.add( "JsonToken eventType = parser.nextToken();" ); - sc.add( "if ( eventType == JsonToken.START_OBJECT )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount++;" ); - sc.add( "}" ); - sc.add( "else if ( eventType == JsonToken.END_OBJECT )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount--;" ); - sc.add( "}" ); + sc.add("JsonToken eventType = parser.nextToken();"); + sc.add("if ( eventType == JsonToken.START_OBJECT )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount++;"); + sc.add("}"); + sc.add("else if ( eventType == JsonToken.END_OBJECT )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount--;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownAttribute", null, null ); + method = new JMethod("checkUnknownAttribute", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "JsonParser" ), "parser" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("JsonParser"), "parser")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - if ( strictXmlAttributes ) - { + if (strictXmlAttributes) { sc.add( - "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too" ); - sc.add( "if ( strict )" ); + "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too"); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new JsonParseException( \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser.getCurrentLocation() );" ); - sc.add( "}" ); - } - else - { + "throw new JsonParseException( \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser.getCurrentLocation() );"); + sc.add("}"); + } else { sc.add( - "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true" ); + "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true"); } - jClass.addMethod( method ); + jClass.addMethod(method); } - private void addTrackingParameters( JMethod method ) - { - if ( sourceTracker != null ) - { - method.addParameter( new JParameter( new JClass( sourceTracker.getName() ), SOURCE_PARAM ) ); + private void addTrackingParameters(JMethod method) { + if (sourceTracker != null) { + method.addParameter(new JParameter(new JClass(sourceTracker.getName()), SOURCE_PARAM)); } } - private void writeNewSetLocation( ModelField field, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewSetLocation( "\"" + field.getName() + "\"", objectName, trackerVariable, sc ); + private void writeNewSetLocation(ModelField field, String objectName, String trackerVariable, JSourceCode sc) { + writeNewSetLocation("\"" + field.getName() + "\"", objectName, trackerVariable, sc); } - private void writeNewSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewLocation( trackerVariable, sc ); - writeSetLocation( key, objectName, trackerVariable, sc ); + private void writeNewSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + writeNewLocation(trackerVariable, sc); + writeSetLocation(key, objectName, trackerVariable, sc); } - private void writeNewLocation( String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeNewLocation(String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } String constr = "new " + locationTracker.getName() + "( parser.getLineNumber(), parser.getColumnNumber()"; - constr += ( sourceTracker != null ) ? ", " + SOURCE_PARAM : ""; + constr += (sourceTracker != null) ? ", " + SOURCE_PARAM : ""; constr += " )"; - sc.add( ( ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR ) + " = " + constr + ";" ); + sc.add(((trackerVariable != null) ? trackerVariable : LOCATION_VAR) + " = " + constr + ";"); } - private void writeSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } - String variable = ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR; + String variable = (trackerVariable != null) ? trackerVariable : LOCATION_VAR; - sc.add( objectName + ".set" + capitalise( singular( locationField ) ) + "( " + key + ", " + variable + " );" ); + sc.add(objectName + ".set" + capitalise(singular(locationField)) + "( " + key + ", " + variable + " );"); } - } diff --git a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonWriterGenerator.java b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonWriterGenerator.java index 18768e7cb..11f37f8bb 100644 --- a/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonWriterGenerator.java +++ b/modello-plugins/modello-plugin-jackson/src/main/java/org/codehaus/modello/plugin/jackson/JacksonWriterGenerator.java @@ -48,365 +48,314 @@ /** * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "jackson-writer" ) -public class JacksonWriterGenerator - extends AbstractJacksonGenerator -{ +@Component(role = ModelloGenerator.class, hint = "jackson-writer") +public class JacksonWriterGenerator extends AbstractJacksonGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = true; - try - { + try { generateJacksonWriter(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating JSON Jackson Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating JSON Jackson Writer.", ex); } } - private void generateJacksonWriter() - throws ModelloException, IOException - { + private void generateJacksonWriter() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.jackson"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.jackson"; - String marshallerName = getFileName( "JacksonWriter" ); + String marshallerName = getFileName("JacksonWriter"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); - jClass.addImport( "com.fasterxml.jackson.core.JsonFactory" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonGenerator" ); - jClass.addImport( "com.fasterxml.jackson.core.JsonGenerator.Feature" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.OutputStreamWriter" ); - jClass.addImport( "java.io.Writer" ); + jClass.addImport("com.fasterxml.jackson.core.JsonFactory"); + jClass.addImport("com.fasterxml.jackson.core.JsonGenerator"); + jClass.addImport("com.fasterxml.jackson.core.JsonGenerator.Feature"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.OutputStreamWriter"); + jClass.addImport("java.io.Writer"); - addModelImports( jClass, null ); + addModelImports(jClass, null); - JField factoryField = new JField( new JClass( "JsonFactory" ), "factory" ); - factoryField.getModifiers().setFinal( true ); - factoryField.setInitString( "new JsonFactory()" ); - jClass.addField( factoryField ); + JField factoryField = new JField(new JClass("JsonFactory"), "factory"); + factoryField.getModifiers().setFinal(true); + factoryField.setInitString("new JsonFactory()"); + jClass.addField(factoryField); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - JConstructor jacksonWriterConstructor = new JConstructor( jClass ); + JConstructor jacksonWriterConstructor = new JConstructor(jClass); JSourceCode sc = jacksonWriterConstructor.getSourceCode(); - sc.add( "factory.enable( Feature.AUTO_CLOSE_JSON_CONTENT );" ); - sc.add( "factory.enable( Feature.AUTO_CLOSE_TARGET );" ); - sc.add( "factory.enable( Feature.ESCAPE_NON_ASCII );" ); - sc.add( "factory.enable( Feature.FLUSH_PASSED_TO_STREAM );" ); - sc.add( "factory.enable( Feature.QUOTE_FIELD_NAMES );" ); - sc.add( "factory.enable( Feature.QUOTE_NON_NUMERIC_NUMBERS );" ); - sc.add( "factory.disable( Feature.WRITE_NUMBERS_AS_STRINGS );" ); + sc.add("factory.enable( Feature.AUTO_CLOSE_JSON_CONTENT );"); + sc.add("factory.enable( Feature.AUTO_CLOSE_TARGET );"); + sc.add("factory.enable( Feature.ESCAPE_NON_ASCII );"); + sc.add("factory.enable( Feature.FLUSH_PASSED_TO_STREAM );"); + sc.add("factory.enable( Feature.QUOTE_FIELD_NAMES );"); + sc.add("factory.enable( Feature.QUOTE_NON_NUMERIC_NUMBERS );"); + sc.add("factory.disable( Feature.WRITE_NUMBERS_AS_STRINGS );"); - jClass.addConstructor( jacksonWriterConstructor ); + jClass.addConstructor(jacksonWriterConstructor); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); // ---------------------------------------------------------------------- // DOM support // ---------------------------------------------------------------------- - if ( requiresDomSupport ) - { - jClass.addImport( "com.fasterxml.jackson.databind.ObjectMapper" ); + if (requiresDomSupport) { + jClass.addImport("com.fasterxml.jackson.databind.ObjectMapper"); - sc.add( "factory.setCodec( new ObjectMapper() );" ); + sc.add("factory.setCodec( new ObjectMapper() );"); } // ---------------------------------------------------------------------- // Write the write( Writer, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - String rootElementParameterName = uncapitalise( root ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + String rootElementParameterName = uncapitalise(root); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); sc = marshall.getSourceCode(); - sc.add( "JsonGenerator generator = factory.createGenerator( writer );" ); + sc.add("JsonGenerator generator = factory.createGenerator( writer );"); - sc.add( "generator.useDefaultPrettyPrinter();" ); + sc.add("generator.useDefaultPrettyPrinter();"); - sc.add( "write" + root + "( " + rootElementParameterName + ", generator );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", generator );"); - sc.add( "generator.close();" ); + sc.add("generator.close();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); sc = marshall.getSourceCode(); - sc.add( "write( new OutputStreamWriter( stream, " - + rootElementParameterName - + ".getModelEncoding() ), " - + rootElementParameterName - + " );" ); + sc.add("write( new OutputStreamWriter( stream, " + + rootElementParameterName + + ".getModelEncoding() ), " + + rootElementParameterName + + " );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "JsonGenerator" ), "generator" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("JsonGenerator"), "generator")); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); marshall.getModifiers().makePrivate(); JSourceCode sc = marshall.getSourceCode(); - sc.add( "generator.writeStartObject();" ); + sc.add("generator.writeStartObject();"); - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); - final boolean useJava5 = hasJavaSourceSupport( 5 ); + final boolean useJava5 = hasJavaSourceSupport(5); // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); - sc.addIndented( "generator.writeFieldName( \"" + fieldTagName + "\" );" ); - sc.addIndented( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", generator );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented("generator.writeFieldName( \"" + fieldTagName + "\" );"); + sc.addIndented("write" + association.getTo() + "( (" + association.getTo() + ") " + value + + ", generator );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); type = association.getType(); String toType = association.getTo(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( getValueChecker( type, value, association ) ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "generator.writeArrayFieldStart( \"" + fieldTagName + "\" );" ); + sc.add("generator.writeArrayFieldStart( \"" + fieldTagName + "\" );"); - if ( useJava5 ) - { - sc.add( "for ( " + toType + " o : " + value + " )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + value + ".iterator(); it.hasNext(); )" ); + if (useJava5) { + sc.add("for ( " + toType + " o : " + value + " )"); + } else { + sc.add("for ( java.util.Iterator it = " + value + ".iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( !useJava5 ) - { - sc.add( toType + " o = (" + toType + " ) it.next();" ); + if (!useJava5) { + sc.add(toType + " o = (" + toType + " ) it.next();"); } - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( "write" + toType + "( o, generator );" ); - } - else - { - sc.add( "generator.writeObject( o ); " ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add("write" + toType + "( o, generator );"); + } else { + sc.add("generator.writeObject( o ); "); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "generator.writeEndArray();" ); + sc.add("generator.writeEndArray();"); sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.writeArrayFieldStart( \"" + fieldTagName + "\" );" ); - } - else - { - sc.add( "generator.writeObjectFieldStart( \"" + fieldTagName + "\" );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("generator.writeArrayFieldStart( \"" + fieldTagName + "\" );"); + } else { + sc.add("generator.writeObjectFieldStart( \"" + fieldTagName + "\" );"); } - StringBuilder entryTypeBuilder = new StringBuilder( "java.util.Map.Entry" ); + StringBuilder entryTypeBuilder = new StringBuilder("java.util.Map.Entry"); - if ( useJava5 ) - { - entryTypeBuilder.append( '<' ); + if (useJava5) { + entryTypeBuilder.append('<'); - if ( association.getType().equals( ModelDefault.PROPERTIES ) ) - { - entryTypeBuilder.append( "Object, Object" ); - } - else - { - entryTypeBuilder.append( "String, " ).append( association.getTo() ); + if (association.getType().equals(ModelDefault.PROPERTIES)) { + entryTypeBuilder.append("Object, Object"); + } else { + entryTypeBuilder.append("String, ").append(association.getTo()); } - entryTypeBuilder.append( '>' ); + entryTypeBuilder.append('>'); } - if ( useJava5 ) - { - sc.add( "for ( " + entryTypeBuilder + " entry : " + value + ".entrySet() )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + value + ".entrySet().iterator(); it.hasNext(); )" ); + if (useJava5) { + sc.add("for ( " + entryTypeBuilder + " entry : " + value + ".entrySet() )"); + } else { + sc.add("for ( java.util.Iterator it = " + value + + ".entrySet().iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( !useJava5 ) - { - sc.add( entryTypeBuilder + " entry = (" + entryTypeBuilder + ") it.next();" ); + if (!useJava5) { + sc.add(entryTypeBuilder + " entry = (" + entryTypeBuilder + ") it.next();"); } - sc.add( "final String key = String.valueOf( entry.getKey() );" ); - sc.add( "final String value = String.valueOf( entry.getValue() );" ); + sc.add("final String key = String.valueOf( entry.getKey() );"); + sc.add("final String value = String.valueOf( entry.getValue() );"); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.writeStartObject();" ); - sc.add( "generator.writeStringField( \"key\", key );" ); - sc.add( "generator.writeStringField( \"value\", value );" ); - sc.add( "generator.writeEndObject();" ); - } - else - { - sc.add( "generator.writeStringField( key, value );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("generator.writeStartObject();"); + sc.add("generator.writeStringField( \"key\", key );"); + sc.add("generator.writeStringField( \"value\", value );"); + sc.add("generator.writeEndObject();"); + } else { + sc.add("generator.writeStringField( key, value );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.writeEndArray();" ); - } - else - { - sc.add( "generator.writeEndObject();" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("generator.writeEndArray();"); + } else { + sc.add("generator.writeEndObject();"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); - - sc.add( "{" ); - if ( "DOM".equals( field.getType() ) ) - { - if ( domAsXpp3 ) - { - getLogger().warn( "Xpp3Dom not supported for " - + modelClass.getName() - + "#" - + field.getName() - + ", it will be treated as a regular Java Object." ); + } else { + sc.add(getValueChecker(type, value, field)); + + sc.add("{"); + if ("DOM".equals(field.getType())) { + if (domAsXpp3) { + getLogger() + .warn("Xpp3Dom not supported for " + + modelClass.getName() + + "#" + + field.getName() + + ", it will be treated as a regular Java Object."); } requiresDomSupport = true; - sc.addIndented( "generator.writeObjectField( \"" + fieldTagName + "\", " + value + " );" ); - } - else - { - sc.addIndented( "generator.writeObjectField( \"" + fieldTagName + "\", " + value + " );" ); + sc.addIndented("generator.writeObjectField( \"" + fieldTagName + "\", " + value + " );"); + } else { + sc.addIndented("generator.writeObjectField( \"" + fieldTagName + "\", " + value + " );"); } - sc.add( "}" ); + sc.add("}"); } } - sc.add( "generator.writeEndObject();" ); + sc.add("generator.writeEndObject();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - } diff --git a/modello-plugins/modello-plugin-jackson/src/test/java/org/codehaus/modello/plugin/jackson/JacksonGeneratorTest.java b/modello-plugins/modello-plugin-jackson/src/test/java/org/codehaus/modello/plugin/jackson/JacksonGeneratorTest.java index 0041a1599..8ddb009e2 100644 --- a/modello-plugins/modello-plugin-jackson/src/test/java/org/codehaus/modello/plugin/jackson/JacksonGeneratorTest.java +++ b/modello-plugins/modello-plugin-jackson/src/test/java/org/codehaus/modello/plugin/jackson/JacksonGeneratorTest.java @@ -34,42 +34,37 @@ /** * @author Simone Tripodi */ -public class JacksonGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public JacksonGeneratorTest() - { - super( "jackson" ); +public class JacksonGeneratorTest extends AbstractModelloJavaGeneratorTest { + public JacksonGeneratorTest() { + super("jackson"); } - public void testJacksonGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJacksonGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); // check some elements read from the model - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 28, classesList.size() ); + assertEquals(28, classesList.size()); // now generate sources and test them - Properties parameters = getModelloParameters( "4.0.0", 5 ); + Properties parameters = getModelloParameters("4.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "jackson-writer", parameters ); - modello.generate( model, "jackson-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "jackson-writer", parameters); + modello.generate(model, "jackson-reader", parameters); - addDependency( "com.fasterxml.jackson.core", "jackson-core" ); - addDependency( "com.fasterxml.jackson.core", "jackson-databind" ); + addDependency("com.fasterxml.jackson.core", "jackson-core"); + addDependency("com.fasterxml.jackson.core", "jackson-databind"); // looks like jackson-databind requires jackson-annotations to run... - addDependency( "com.fasterxml.jackson.core", "jackson-annotations" ); - compileGeneratedSources( 5 ); + addDependency("com.fasterxml.jackson.core", "jackson-annotations"); + compileGeneratedSources(5); // TODO: see why without this, version system property is set to "2.4.1" value after verify - System.setProperty( "version", getModelloVersion() ); + System.setProperty("version", getModelloVersion()); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.jackson.JacksonVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.jackson.JacksonVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/pom.xml b/modello-plugins/modello-plugin-java/pom.xml index 83259942b..3efc100e2 100644 --- a/modello-plugins/modello-plugin-java/pom.xml +++ b/modello-plugins/modello-plugin-java/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-java Modello Java Plugin - - Modello Java Plugin generates Java POJOs for the model. - + Modello Java Plugin generates Java POJOs for the model. diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java index 41a06b672..1446a0131 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java @@ -24,9 +24,6 @@ import java.io.File; import java.io.IOException; -import java.io.Writer; -import java.nio.charset.Charset; -import java.nio.file.Path; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -65,21 +62,18 @@ * * @author Joakim Erdfelt */ -public abstract class AbstractJavaModelloGenerator - extends AbstractModelloGenerator -{ +public abstract class AbstractJavaModelloGenerator extends AbstractModelloGenerator { private Optional javaSource; protected boolean domAsXpp3 = true; - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { - super.initialize( model, parameters ); + protected void initialize(Model model, Properties parameters) throws ModelloException { + super.initialize(model, parameters); - javaSource = Optional.ofNullable( getParameter( parameters, ModelloParameterConstants.OUTPUT_JAVA_SOURCE, null ) ).map( Integer::valueOf ); + javaSource = Optional.ofNullable(getParameter(parameters, ModelloParameterConstants.OUTPUT_JAVA_SOURCE, null)) + .map(Integer::valueOf); - domAsXpp3 = !"false".equals( parameters.getProperty( ModelloParameterConstants.DOM_AS_XPP3 ) ); + domAsXpp3 = !"false".equals(parameters.getProperty(ModelloParameterConstants.DOM_AS_XPP3)); } /** @@ -90,97 +84,78 @@ protected void initialize( Model model, Properties parameters ) * @return a JSourceWriter with configured encoding * @throws IOException */ - protected JSourceWriter newJSourceWriter( String packageName, String className ) - throws IOException - { - String directory = packageName.replace( '.', File.separatorChar ); + protected JSourceWriter newJSourceWriter(String packageName, String className) throws IOException { + String directory = packageName.replace('.', File.separatorChar); - File f = new File( new File( getOutputDirectory(), directory ), className + ".java" ); + File f = new File(new File(getOutputDirectory(), directory), className + ".java"); - if ( !f.getParentFile().exists() ) - { + if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } - return new JSourceWriter( newWriter( f.toPath() ) ); + return new JSourceWriter(newWriter(f.toPath())); } - private JComment getHeaderComment() - { + private JComment getHeaderComment() { JComment comment = new JComment(); - comment.setComment( getHeader() ); + comment.setComment(getHeader()); return comment; } - protected void initHeader( JClass clazz ) - { - clazz.setHeader( getHeaderComment() ); + protected void initHeader(JClass clazz) { + clazz.setHeader(getHeaderComment()); } - protected void initHeader( JInterface interfaze ) - { - interfaze.setHeader( getHeaderComment() ); + protected void initHeader(JInterface interfaze) { + interfaze.setHeader(getHeaderComment()); } - - protected final boolean hasJavaSourceSupport( int source ) - { - return javaSource.map( i -> i >= source ).orElse( false ); + + protected final boolean hasJavaSourceSupport(int source) { + return javaSource.map(i -> i >= source).orElse(false); } - protected void suppressAllWarnings( Model objectModel, JStructure structure ) - { - JavaModelMetadata javaModelMetadata = (JavaModelMetadata) objectModel.getMetadata( JavaModelMetadata.ID ); + protected void suppressAllWarnings(Model objectModel, JStructure structure) { + JavaModelMetadata javaModelMetadata = (JavaModelMetadata) objectModel.getMetadata(JavaModelMetadata.ID); - if ( hasJavaSourceSupport( 5 ) && javaModelMetadata.isSuppressAllWarnings() ) - { - structure.appendAnnotation( "@SuppressWarnings( \"all\" )" ); + if (hasJavaSourceSupport(5) && javaModelMetadata.isSuppressAllWarnings()) { + structure.appendAnnotation("@SuppressWarnings( \"all\" )"); } } - protected void addModelImports( JClass jClass, BaseElement baseElem ) - throws ModelloException - { + protected void addModelImports(JClass jClass, BaseElement baseElem) throws ModelloException { String basePackageName = null; - if ( baseElem instanceof ModelType ) - { - basePackageName = ( (ModelType) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + if (baseElem instanceof ModelType) { + basePackageName = ((ModelType) baseElem).getPackageName(isPackageWithVersion(), getGeneratedVersion()); } // import interfaces - for ( ModelInterface modelInterface : getModel().getInterfaces( getGeneratedVersion() ) ) - { - addModelImport( jClass, modelInterface, basePackageName ); + for (ModelInterface modelInterface : getModel().getInterfaces(getGeneratedVersion())) { + addModelImport(jClass, modelInterface, basePackageName); } // import classes - for ( ModelClass modelClass : getClasses( getModel() ) ) - { - addModelImport( jClass, modelClass, basePackageName ); + for (ModelClass modelClass : getClasses(getModel())) { + addModelImport(jClass, modelClass, basePackageName); } } - protected void addModelImport( JClass jClass, ModelType modelType, String basePackageName ) - { - String packageName = modelType.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + protected void addModelImport(JClass jClass, ModelType modelType, String basePackageName) { + String packageName = modelType.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - if ( !packageName.equals( basePackageName ) ) - { - jClass.addImport( packageName + '.' + modelType.getName() ); + if (!packageName.equals(basePackageName)) { + jClass.addImport(packageName + '.' + modelType.getName()); } } - protected String getPrefix( JavaFieldMetadata javaFieldMetadata ) - { + protected String getPrefix(JavaFieldMetadata javaFieldMetadata) { return javaFieldMetadata.isBooleanGetter() ? "is" : "get"; } - protected String getDefaultValue( ModelAssociation association ) - { + protected String getDefaultValue(ModelAssociation association) { String value = association.getDefaultValue(); - if ( hasJavaSourceSupport( 5 ) ) - { - value = StringUtils.replaceOnce( StringUtils.replaceOnce( value, "/*", "" ), "*/", "" ); + if (hasJavaSourceSupport(5)) { + value = StringUtils.replaceOnce(StringUtils.replaceOnce(value, "/*", ""), "*/", ""); } return value; @@ -188,192 +163,142 @@ protected String getDefaultValue( ModelAssociation association ) protected static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"; - protected String getJavaDefaultValue( ModelField modelField ) - throws ModelloException - { + protected String getJavaDefaultValue(ModelField modelField) throws ModelloException { String type = modelField.getType(); String value = modelField.getDefaultValue(); - if ( "String".equals( type ) ) - { - return '"' + escapeStringLiteral( value ) + '"'; - } - else if ( "char".equals( type ) ) - { - return '\'' + escapeStringLiteral( value ) + '\''; - } - else if ( "long".equals( type ) ) - { + if ("String".equals(type)) { + return '"' + escapeStringLiteral(value) + '"'; + } else if ("char".equals(type)) { + return '\'' + escapeStringLiteral(value) + '\''; + } else if ("long".equals(type)) { return value + 'L'; - } - else if ( "float".equals( type ) ) - { + } else if ("float".equals(type)) { return value + 'f'; - } - else if ( "Date".equals( type ) ) - { - DateFormat format = new SimpleDateFormat( DEFAULT_DATE_FORMAT, Locale.US ); - try - { - Date date = format.parse( value ); + } else if ("Date".equals(type)) { + DateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Locale.US); + try { + Date date = format.parse(value); return "new java.util.Date( " + date.getTime() + "L )"; + } catch (ParseException pe) { + throw new ModelloException("Unparseable default date: " + value, pe); } - catch ( ParseException pe ) - { - throw new ModelloException( "Unparseable default date: " + value, pe ); - } - } - else if ( value != null && value.length() > 0 ) - { - boolean useJava5 = hasJavaSourceSupport( 5 ); - if ( "Character".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, "'" + escapeStringLiteral( value ) + "'", useJava5 ); - } - else if ( "Boolean".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, value, true ); - } - else if ( "Byte".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, "(byte) " + value, useJava5 ); - } - else if ( "Short".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, "(short) " + value, useJava5 ); - } - else if ( "Integer".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, value, useJava5 ); - } - else if ( "Long".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, value + 'L', useJava5 ); - } - else if ( "Float".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, value + 'f', useJava5 ); - } - else if ( "Double".equals( type ) && !value.contains( type ) ) - { - return newPrimitiveWrapper( type, value, useJava5 ); + } else if (value != null && value.length() > 0) { + boolean useJava5 = hasJavaSourceSupport(5); + if ("Character".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, "'" + escapeStringLiteral(value) + "'", useJava5); + } else if ("Boolean".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, value, true); + } else if ("Byte".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, "(byte) " + value, useJava5); + } else if ("Short".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, "(short) " + value, useJava5); + } else if ("Integer".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, value, useJava5); + } else if ("Long".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, value + 'L', useJava5); + } else if ("Float".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, value + 'f', useJava5); + } else if ("Double".equals(type) && !value.contains(type)) { + return newPrimitiveWrapper(type, value, useJava5); } } return value; } - private String newPrimitiveWrapper( String type, String value, boolean useJava5 ) - { - if ( useJava5 ) - { + private String newPrimitiveWrapper(String type, String value, boolean useJava5) { + if (useJava5) { return type + ".valueOf( " + value + " )"; - } - else - { + } else { return "new " + type + "( " + value + " )"; } } - private String escapeStringLiteral( String str ) - { - StringBuilder buffer = new StringBuilder( str.length() + 32 ); + private String escapeStringLiteral(String str) { + StringBuilder buffer = new StringBuilder(str.length() + 32); - for ( int i = 0, n = str.length(); i < n; i++ ) - { - char c = str.charAt( i ); - switch ( c ) - { + for (int i = 0, n = str.length(); i < n; i++) { + char c = str.charAt(i); + switch (c) { case '\0': - buffer.append( "\\0" ); + buffer.append("\\0"); break; case '\t': - buffer.append( "\\t" ); + buffer.append("\\t"); break; case '\r': - buffer.append( "\\r" ); + buffer.append("\\r"); break; case '\n': - buffer.append( "\\n" ); + buffer.append("\\n"); break; case '\\': - buffer.append( "\\\\" ); + buffer.append("\\\\"); break; default: - buffer.append( c ); + buffer.append(c); } } return buffer.toString(); } - protected String getValueChecker( String type, String value, ModelField field ) - throws ModelloException - { + protected String getValueChecker(String type, String value, ModelField field) throws ModelloException { String retVal; - if ( "boolean".equals( type ) || "double".equals( type ) || "float".equals( type ) || "int".equals( type ) - || "long".equals( type ) || "short".equals( type ) || "byte".equals( type ) || "char".equals( type ) ) - { - retVal = "if ( " + value + " != " + getJavaDefaultValue( field ) + " )"; - } - else if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) - || ModelDefault.MAP.equals( type ) || ModelDefault.PROPERTIES.equals( type ) ) - { + if ("boolean".equals(type) + || "double".equals(type) + || "float".equals(type) + || "int".equals(type) + || "long".equals(type) + || "short".equals(type) + || "byte".equals(type) + || "char".equals(type)) { + retVal = "if ( " + value + " != " + getJavaDefaultValue(field) + " )"; + } else if (ModelDefault.LIST.equals(type) + || ModelDefault.SET.equals(type) + || ModelDefault.MAP.equals(type) + || ModelDefault.PROPERTIES.equals(type)) { retVal = "if ( ( " + value + " != null ) && ( " + value + ".size() > 0 ) )"; - } - else if ( "String".equals( type ) && field.getDefaultValue() != null ) - { + } else if ("String".equals(type) && field.getDefaultValue() != null) { retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( \"" + field.getDefaultValue() + "\" ) )"; - } - else if ( "Date".equals( type ) && field.getDefaultValue() != null ) - { - retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( " + getJavaDefaultValue( field ) + " ) )"; - } - else - { + } else if ("Date".equals(type) && field.getDefaultValue() != null) { + retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( " + getJavaDefaultValue(field) + " ) )"; + } else { retVal = "if ( " + value + " != null )"; } return retVal; } - protected List getClasses( Model model ) - { + protected List getClasses(Model model) { List modelClasses = new ArrayList(); - for ( ModelClass modelClass : model.getClasses( getGeneratedVersion() ) ) - { - if ( isRelevant( modelClass ) ) - { - modelClasses.add( modelClass ); + for (ModelClass modelClass : model.getClasses(getGeneratedVersion())) { + if (isRelevant(modelClass)) { + modelClasses.add(modelClass); } } return modelClasses; } - protected boolean isRelevant( ModelClass modelClass ) - { - return isJavaEnabled( modelClass ) && !isTrackingSupport( modelClass ); + protected boolean isRelevant(ModelClass modelClass) { + return isJavaEnabled(modelClass) && !isTrackingSupport(modelClass); } - protected boolean isJavaEnabled( ModelClass modelClass ) - { - JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID ); + protected boolean isJavaEnabled(ModelClass modelClass) { + JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.ID); return javaClassMetadata.isEnabled(); } - protected boolean isTrackingSupport( ModelClass modelClass ) - { - ModelClassMetadata modelClassMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); - if ( StringUtils.isNotEmpty( modelClassMetadata.getLocationTracker() ) ) - { + protected boolean isTrackingSupport(ModelClass modelClass) { + ModelClassMetadata modelClassMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); + if (StringUtils.isNotEmpty(modelClassMetadata.getLocationTracker())) { return true; } - if ( StringUtils.isNotEmpty( modelClassMetadata.getSourceTracker() ) ) - { + if (StringUtils.isNotEmpty(modelClassMetadata.getSourceTracker())) { return true; } return false; } - } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/JavaModelloGenerator.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/JavaModelloGenerator.java index 97a4d8135..df21b7750 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/JavaModelloGenerator.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/JavaModelloGenerator.java @@ -66,115 +66,110 @@ /** * @author Jason van Zyl */ -@Component( role = ModelloGenerator.class, hint = "java" ) -public class JavaModelloGenerator - extends AbstractJavaModelloGenerator -{ - - private Collection immutableTypes = new HashSet( Arrays.asList( - new String[]{ "boolean", "Boolean", "byte", "Byte", "char", "Character", "short", "Short", "int", "Integer", - "long", "Long", "float", "Float", "double", "Double", "String" } ) ); - - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); - - try - { +@Component(role = ModelloGenerator.class, hint = "java") +public class JavaModelloGenerator extends AbstractJavaModelloGenerator { + + private Collection immutableTypes = new HashSet(Arrays.asList(new String[] { + "boolean", + "Boolean", + "byte", + "Byte", + "char", + "Character", + "short", + "Short", + "int", + "Integer", + "long", + "Long", + "float", + "Float", + "double", + "Double", + "String" + })); + + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + try { generateJava(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating Java.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating Java.", ex); } } - private void generateJava() - throws ModelloException, IOException - { + private void generateJava() throws ModelloException, IOException { Model objectModel = getModel(); - ModelClass locationTrackerClass = objectModel.getLocationTracker( getGeneratedVersion() ); - ModelClass sourceTrackerClass = objectModel.getSourceTracker( getGeneratedVersion() ); + ModelClass locationTrackerClass = objectModel.getLocationTracker(getGeneratedVersion()); + ModelClass sourceTrackerClass = objectModel.getSourceTracker(getGeneratedVersion()); // ---------------------------------------------------------------------- // Generate the interfaces. // ---------------------------------------------------------------------- - for ( ModelInterface modelInterface : objectModel.getInterfaces( getGeneratedVersion() ) ) - { - generateInterface( modelInterface ); + for (ModelInterface modelInterface : objectModel.getInterfaces(getGeneratedVersion())) { + generateInterface(modelInterface); } - String locationTrackerInterface = generateLocationTracker( objectModel, locationTrackerClass ); + String locationTrackerInterface = generateLocationTracker(objectModel, locationTrackerClass); // ---------------------------------------------------------------------- // Generate the classes. // ---------------------------------------------------------------------- - for ( ModelClass modelClass : objectModel.getClasses( getGeneratedVersion() ) ) - { - JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID ); + for (ModelClass modelClass : objectModel.getClasses(getGeneratedVersion())) { + JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.ID); - if ( !javaClassMetadata.isEnabled() ) - { + if (!javaClassMetadata.isEnabled()) { // Skip generation of those classes that are not enabled for the java plugin. continue; } - String packageName = modelClass.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + String packageName = modelClass.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - JSourceWriter sourceWriter = newJSourceWriter( packageName, modelClass.getName() ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, modelClass.getName()); - JClass jClass = new JClass( packageName + '.' + modelClass.getName() ); + JClass jClass = new JClass(packageName + '.' + modelClass.getName()); - initHeader( jClass ); + initHeader(jClass); - suppressAllWarnings( objectModel, jClass ); + suppressAllWarnings(objectModel, jClass); - if ( StringUtils.isNotEmpty( modelClass.getDescription() ) ) - { - jClass.getJDocComment().setComment( appendPeriod( modelClass.getDescription() ) ); + if (StringUtils.isNotEmpty(modelClass.getDescription())) { + jClass.getJDocComment().setComment(appendPeriod(modelClass.getDescription())); } - addModelImports( jClass, modelClass ); + addModelImports(jClass, modelClass); - jClass.getModifiers().setAbstract( javaClassMetadata.isAbstract() ); + jClass.getModifiers().setAbstract(javaClassMetadata.isAbstract()); boolean superClassInModel = false; - if ( modelClass.getSuperClass() != null ) - { - jClass.setSuperClass( modelClass.getSuperClass() ); - superClassInModel = isClassInModel( modelClass.getSuperClass(), objectModel ); + if (modelClass.getSuperClass() != null) { + jClass.setSuperClass(modelClass.getSuperClass()); + superClassInModel = isClassInModel(modelClass.getSuperClass(), objectModel); } - for ( String implementedInterface : modelClass.getInterfaces() ) - { - jClass.addInterface( implementedInterface ); + for (String implementedInterface : modelClass.getInterfaces()) { + jClass.addInterface(implementedInterface); } - jClass.addInterface( Serializable.class.getName() ); + jClass.addInterface(Serializable.class.getName()); - if (hasJavaSourceSupport( 5 ) && !modelClass.getAnnotations().isEmpty() ) - { - for ( String annotation : modelClass.getAnnotations() ) - { - jClass.appendAnnotation( annotation ); + if (hasJavaSourceSupport(5) && !modelClass.getAnnotations().isEmpty()) { + for (String annotation : modelClass.getAnnotations()) { + jClass.appendAnnotation(annotation); } } JSourceCode jConstructorSource = new JSourceCode(); - for ( ModelField modelField : modelClass.getFields( getGeneratedVersion() ) ) - { - if ( modelField instanceof ModelAssociation ) - { - createAssociation( jClass, (ModelAssociation) modelField, jConstructorSource ); - } - else - { - createField( jClass, modelField ); + for (ModelField modelField : modelClass.getFields(getGeneratedVersion())) { + if (modelField instanceof ModelAssociation) { + createAssociation(jClass, (ModelAssociation) modelField, jConstructorSource); + } else { + createField(jClass, modelField); } } @@ -182,47 +177,41 @@ private void generateJava() // needed to understand if the instance can be created with empty ctor or not JConstructor jConstructor = null; - if ( !jConstructorSource.isEmpty() ) - { + if (!jConstructorSource.isEmpty()) { // Ironic that we are doing lazy init huh? jConstructor = jClass.createConstructor(); - jConstructor.setSourceCode( jConstructorSource ); - jClass.addConstructor( jConstructor ); + jConstructor.setSourceCode(jConstructorSource); + jClass.addConstructor(jConstructor); } // ---------------------------------------------------------------------- // equals() / hashCode() / toString() // ---------------------------------------------------------------------- - List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() ); + List identifierFields = modelClass.getIdentifierFields(getGeneratedVersion()); - if ( identifierFields.size() != 0 ) - { - JMethod equals = generateEquals( modelClass ); + if (identifierFields.size() != 0) { + JMethod equals = generateEquals(modelClass); - jClass.addMethod( equals ); + jClass.addMethod(equals); - JMethod hashCode = generateHashCode( modelClass ); + JMethod hashCode = generateHashCode(modelClass); - jClass.addMethod( hashCode ); + jClass.addMethod(hashCode); // backward compat - if ( !javaClassMetadata.isGenerateToString() ) - { - JMethod toString = generateToString( modelClass, true ); + if (!javaClassMetadata.isGenerateToString()) { + JMethod toString = generateToString(modelClass, true); - jClass.addMethod( toString ); + jClass.addMethod(toString); } - } - if ( javaClassMetadata.isGenerateToString() ) - { + if (javaClassMetadata.isGenerateToString()) { - JMethod toString = generateToString( modelClass, false ); - - jClass.addMethod( toString ); + JMethod toString = generateToString(modelClass, false); + jClass.addMethod(toString); } // ---------------------------------------------------------------------- @@ -230,9 +219,8 @@ private void generateJava() // since 1.8 // ---------------------------------------------------------------------- - if ( javaClassMetadata.isGenerateBuilder() ) - { - generateBuilder( modelClass, jClass.createInnerClass( "Builder" ), jConstructor ); + if (javaClassMetadata.isGenerateBuilder()) { + generateBuilder(modelClass, jClass.createInnerClass("Builder"), jConstructor); } // ---------------------------------------------------------------------- @@ -240,1018 +228,902 @@ private void generateJava() // since 1.8 // ---------------------------------------------------------------------- - if ( javaClassMetadata.isGenerateStaticCreators() ) - { - generateStaticCreator( modelClass, jClass, jConstructor ); + if (javaClassMetadata.isGenerateStaticCreators()) { + generateStaticCreator(modelClass, jClass, jConstructor); } boolean cloneLocations = !superClassInModel && modelClass != sourceTrackerClass; - JMethod[] cloneMethods = generateClone( modelClass, cloneLocations ? locationTrackerClass : null ); - if ( cloneMethods.length > 0 ) - { - jClass.addInterface( Cloneable.class.getName() ); - jClass.addMethods( cloneMethods ); - } - - if ( modelClass.getCodeSegments( getGeneratedVersion() ) != null ) - { - for ( CodeSegment codeSegment : modelClass.getCodeSegments( getGeneratedVersion() ) ) - { - jClass.addSourceCode( codeSegment.getCode() ); + JMethod[] cloneMethods = generateClone(modelClass, cloneLocations ? locationTrackerClass : null); + if (cloneMethods.length > 0) { + jClass.addInterface(Cloneable.class.getName()); + jClass.addMethods(cloneMethods); + } + + if (modelClass.getCodeSegments(getGeneratedVersion()) != null) { + for (CodeSegment codeSegment : modelClass.getCodeSegments(getGeneratedVersion())) { + jClass.addSourceCode(codeSegment.getCode()); } } - ModelClassMetadata modelClassMetadata = - (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata modelClassMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); - if ( modelClassMetadata != null ) - { - if ( modelClassMetadata.isRootElement() ) - { - ModelField modelEncoding = new ModelField( modelClass, "modelEncoding" ); - modelEncoding.setType( "String" ); - modelEncoding.setDefaultValue( "UTF-8" ); - modelEncoding.addMetadata( new JavaFieldMetadata() ); - createField( jClass, modelEncoding ); + if (modelClassMetadata != null) { + if (modelClassMetadata.isRootElement()) { + ModelField modelEncoding = new ModelField(modelClass, "modelEncoding"); + modelEncoding.setType("String"); + modelEncoding.setDefaultValue("UTF-8"); + modelEncoding.addMetadata(new JavaFieldMetadata()); + createField(jClass, modelEncoding); } } - if ( modelClass == locationTrackerClass ) - { - jClass.addInterface( locationTrackerInterface ); + if (modelClass == locationTrackerClass) { + jClass.addInterface(locationTrackerInterface); - generateLocationBean( jClass, modelClass, sourceTrackerClass ); + generateLocationBean(jClass, modelClass, sourceTrackerClass); - generateLocationTracking( jClass, modelClass, locationTrackerClass ); - } - else if ( locationTrackerClass != null && modelClass != sourceTrackerClass && !superClassInModel ) - { - jClass.addInterface( locationTrackerInterface ); + generateLocationTracking(jClass, modelClass, locationTrackerClass); + } else if (locationTrackerClass != null && modelClass != sourceTrackerClass && !superClassInModel) { + jClass.addInterface(locationTrackerInterface); - generateLocationTracking( jClass, modelClass, locationTrackerClass ); + generateLocationTracking(jClass, modelClass, locationTrackerClass); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } } - private void generateInterface( ModelInterface modelInterface ) - throws ModelloException, IOException - { + private void generateInterface(ModelInterface modelInterface) throws ModelloException, IOException { Model objectModel = modelInterface.getModel(); - String packageName = modelInterface.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + String packageName = modelInterface.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - JSourceWriter sourceWriter = newJSourceWriter( packageName, modelInterface.getName() ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, modelInterface.getName()); - JInterface jInterface = new JInterface( packageName + '.' + modelInterface.getName() ); + JInterface jInterface = new JInterface(packageName + '.' + modelInterface.getName()); - initHeader( jInterface ); + initHeader(jInterface); - suppressAllWarnings( objectModel, jInterface ); + suppressAllWarnings(objectModel, jInterface); - if ( modelInterface.getSuperInterface() != null ) - { + if (modelInterface.getSuperInterface() != null) { // check if we need an import: if it is a generated superInterface in another package - try - { + try { ModelInterface superInterface = - objectModel.getInterface( modelInterface.getSuperInterface(), getGeneratedVersion() ); - String superPackageName = - superInterface.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + objectModel.getInterface(modelInterface.getSuperInterface(), getGeneratedVersion()); + String superPackageName = superInterface.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - if ( !packageName.equals( superPackageName ) ) - { - jInterface.addImport( superPackageName + '.' + superInterface.getName() ); + if (!packageName.equals(superPackageName)) { + jInterface.addImport(superPackageName + '.' + superInterface.getName()); } - } - catch ( ModelloRuntimeException mre ) - { + } catch (ModelloRuntimeException mre) { // no problem if the interface does not exist in the model, it can be in the jdk } - jInterface.addInterface( modelInterface.getSuperInterface() ); + jInterface.addInterface(modelInterface.getSuperInterface()); } - if ( modelInterface.getCodeSegments( getGeneratedVersion() ) != null ) - { - for ( CodeSegment codeSegment : modelInterface.getCodeSegments( getGeneratedVersion() ) ) - { - jInterface.addSourceCode( codeSegment.getCode() ); + if (modelInterface.getCodeSegments(getGeneratedVersion()) != null) { + for (CodeSegment codeSegment : modelInterface.getCodeSegments(getGeneratedVersion())) { + jInterface.addSourceCode(codeSegment.getCode()); } } - if ( hasJavaSourceSupport( 5 ) && !modelInterface.getAnnotations().isEmpty() ) - { - for ( String annotation : modelInterface.getAnnotations() ) - { - jInterface.appendAnnotation( annotation ); + if (hasJavaSourceSupport(5) && !modelInterface.getAnnotations().isEmpty()) { + for (String annotation : modelInterface.getAnnotations()) { + jInterface.appendAnnotation(annotation); } } - jInterface.print( sourceWriter ); + jInterface.print(sourceWriter); sourceWriter.close(); } - private JMethod generateEquals( ModelClass modelClass ) - { - JMethod equals = new JMethod( "equals", JType.BOOLEAN, null ); + private JMethod generateEquals(ModelClass modelClass) { + JMethod equals = new JMethod("equals", JType.BOOLEAN, null); - equals.addParameter( new JParameter( new JClass( "Object" ), "other" ) ); + equals.addParameter(new JParameter(new JClass("Object"), "other")); JSourceCode sc = equals.getSourceCode(); - sc.add( "if ( this == other )" ); - sc.add( "{" ); - sc.addIndented( "return true;" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( "if ( !( other instanceof " + modelClass.getName() + " ) )" ); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( modelClass.getName() + " that = (" + modelClass.getName() + ") other;" ); - sc.add( "boolean result = true;" ); - - sc.add( "" ); - - for ( ModelField identifier : modelClass.getIdentifierFields( getGeneratedVersion() ) ) - { + sc.add("if ( this == other )"); + sc.add("{"); + sc.addIndented("return true;"); + sc.add("}"); + sc.add(""); + sc.add("if ( !( other instanceof " + modelClass.getName() + " ) )"); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); + sc.add(""); + sc.add(modelClass.getName() + " that = (" + modelClass.getName() + ") other;"); + sc.add("boolean result = true;"); + + sc.add(""); + + for (ModelField identifier : modelClass.getIdentifierFields(getGeneratedVersion())) { String name = identifier.getName(); - if ( "boolean".equals( identifier.getType() ) || "byte".equals( identifier.getType() ) || "char".equals( - identifier.getType() ) || "double".equals( identifier.getType() ) || "float".equals( - identifier.getType() ) || "int".equals( identifier.getType() ) || "short".equals( identifier.getType() ) - || "long".equals( identifier.getType() ) ) - { - sc.add( "result = result && " + name + " == that." + name + ";" ); - } - else - { - name = "get" + capitalise( name ) + "()"; - sc.add( - "result = result && ( " + name + " == null ? that." + name + " == null : " + name + ".equals( that." - + name + " ) );" ); + if ("boolean".equals(identifier.getType()) + || "byte".equals(identifier.getType()) + || "char".equals(identifier.getType()) + || "double".equals(identifier.getType()) + || "float".equals(identifier.getType()) + || "int".equals(identifier.getType()) + || "short".equals(identifier.getType()) + || "long".equals(identifier.getType())) { + sc.add("result = result && " + name + " == that." + name + ";"); + } else { + name = "get" + capitalise(name) + "()"; + sc.add("result = result && ( " + name + " == null ? that." + name + " == null : " + name + + ".equals( that." + name + " ) );"); } } - if ( modelClass.getSuperClass() != null ) - { - sc.add( "result = result && ( super.equals( other ) );" ); + if (modelClass.getSuperClass() != null) { + sc.add("result = result && ( super.equals( other ) );"); } - sc.add( "" ); + sc.add(""); - sc.add( "return result;" ); + sc.add("return result;"); return equals; } - private JMethod generateToString( ModelClass modelClass, boolean onlyIdentifierFields ) - { - JMethod toString = new JMethod( "toString", new JType( String.class.getName() ), null ); + private JMethod generateToString(ModelClass modelClass, boolean onlyIdentifierFields) { + JMethod toString = new JMethod("toString", new JType(String.class.getName()), null); - List fields = onlyIdentifierFields ? modelClass.getIdentifierFields( getGeneratedVersion() ) : modelClass.getFields( getGeneratedVersion() ); + List fields = onlyIdentifierFields + ? modelClass.getIdentifierFields(getGeneratedVersion()) + : modelClass.getFields(getGeneratedVersion()); JSourceCode sc = toString.getSourceCode(); - if ( fields.size() == 0 ) - { - sc.add( "return super.toString();" ); + if (fields.size() == 0) { + sc.add("return super.toString();"); return toString; } - sc.add( "StringBuilder buf = new StringBuilder( 128 );" ); + sc.add("StringBuilder buf = new StringBuilder( 128 );"); - sc.add( "" ); + sc.add(""); - for ( Iterator j = fields.iterator(); j.hasNext(); ) - { + for (Iterator j = fields.iterator(); j.hasNext(); ) { ModelField identifier = j.next(); - String getter = "boolean".equals( identifier.getType() ) ? "is" : "get"; + String getter = "boolean".equals(identifier.getType()) ? "is" : "get"; - sc.add( "buf.append( \"" + identifier.getName() + " = '\" );" ); - sc.add( "buf.append( " + getter + capitalise( identifier.getName() ) + "() );" ); - sc.add( "buf.append( \"'\" );" ); + sc.add("buf.append( \"" + identifier.getName() + " = '\" );"); + sc.add("buf.append( " + getter + capitalise(identifier.getName()) + "() );"); + sc.add("buf.append( \"'\" );"); - if ( j.hasNext() ) - { - sc.add( "buf.append( \"\\n\" ); " ); + if (j.hasNext()) { + sc.add("buf.append( \"\\n\" ); "); } } - if ( modelClass.getSuperClass() != null ) - { - sc.add( "buf.append( \"\\n\" );" ); - sc.add( "buf.append( super.toString() );" ); + if (modelClass.getSuperClass() != null) { + sc.add("buf.append( \"\\n\" );"); + sc.add("buf.append( super.toString() );"); } - sc.add( "" ); + sc.add(""); - sc.add( "return buf.toString();" ); + sc.add("return buf.toString();"); return toString; } - private JMethod generateHashCode( ModelClass modelClass ) - { - JMethod hashCode = new JMethod( "hashCode", JType.INT, null ); + private JMethod generateHashCode(ModelClass modelClass) { + JMethod hashCode = new JMethod("hashCode", JType.INT, null); - List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() ); + List identifierFields = modelClass.getIdentifierFields(getGeneratedVersion()); JSourceCode sc = hashCode.getSourceCode(); - if ( identifierFields.size() == 0 ) - { - sc.add( "return super.hashCode();" ); + if (identifierFields.size() == 0) { + sc.add("return super.hashCode();"); return hashCode; } - sc.add( "int result = 17;" ); + sc.add("int result = 17;"); - sc.add( "" ); + sc.add(""); - for ( ModelField identifier : identifierFields ) - { - sc.add( "result = 37 * result + " + createHashCodeForField( identifier ) + ";" ); + for (ModelField identifier : identifierFields) { + sc.add("result = 37 * result + " + createHashCodeForField(identifier) + ";"); } - if ( modelClass.getSuperClass() != null ) - { - sc.add( "result = 37 * result + super.hashCode();" ); + if (modelClass.getSuperClass() != null) { + sc.add("result = 37 * result + super.hashCode();"); } - sc.add( "" ); + sc.add(""); - sc.add( "return result;" ); + sc.add("return result;"); return hashCode; } - private JMethod[] generateClone( ModelClass modelClass, ModelClass locationClass ) - throws ModelloException - { - String cloneModeClass = getCloneMode( modelClass ); + private JMethod[] generateClone(ModelClass modelClass, ModelClass locationClass) throws ModelloException { + String cloneModeClass = getCloneMode(modelClass); - if ( JavaClassMetadata.CLONE_NONE.equals( cloneModeClass ) ) - { + if (JavaClassMetadata.CLONE_NONE.equals(cloneModeClass)) { return new JMethod[0]; } - boolean useJava5 = hasJavaSourceSupport( 5 ); - + boolean useJava5 = hasJavaSourceSupport(5); + JType returnType; - if ( useJava5 ) - { - returnType = new JClass( modelClass.getName() ); - } - else - { - returnType = new JClass( "Object" ); + if (useJava5) { + returnType = new JClass(modelClass.getName()); + } else { + returnType = new JClass("Object"); } - JMethod cloneMethod = new JMethod( "clone", returnType, null ); + JMethod cloneMethod = new JMethod("clone", returnType, null); JSourceCode sc = cloneMethod.getSourceCode(); - sc.add( "try" ); - sc.add( "{" ); + sc.add("try"); + sc.add("{"); sc.indent(); - sc.add( modelClass.getName() + " copy = (" + modelClass.getName() + ") super.clone();" ); + sc.add(modelClass.getName() + " copy = (" + modelClass.getName() + ") super.clone();"); - sc.add( "" ); + sc.add(""); - for ( ModelField modelField : modelClass.getFields( getGeneratedVersion() ) ) - { + for (ModelField modelField : modelClass.getFields(getGeneratedVersion())) { String thisField = "this." + modelField.getName(); String copyField = "copy." + modelField.getName(); - if ( "DOM".equals( modelField.getType() ) ) - { - sc.add( "if ( " + thisField + " != null )" ); - sc.add( "{" ); - if ( domAsXpp3 ) - { - sc.addIndented( copyField - + " = new org.codehaus.plexus.util.xml.Xpp3Dom( (org.codehaus.plexus.util.xml.Xpp3Dom) " - + thisField + " );" ); + if ("DOM".equals(modelField.getType())) { + sc.add("if ( " + thisField + " != null )"); + sc.add("{"); + if (domAsXpp3) { + sc.addIndented(copyField + + " = new org.codehaus.plexus.util.xml.Xpp3Dom( (org.codehaus.plexus.util.xml.Xpp3Dom) " + + thisField + " );"); + } else { + sc.addIndented(copyField + " = ( (org.w3c.dom.Node) " + thisField + ").cloneNode( true );"); } - else - { - sc.addIndented( copyField + " = ( (org.w3c.dom.Node) " + thisField + ").cloneNode( true );" ); - } - sc.add( "}" ); - sc.add( "" ); - } - else if ( "Date".equalsIgnoreCase( modelField.getType() ) || "java.util.Date".equals( - modelField.getType() ) ) - { - sc.add( "if ( " + thisField + " != null )" ); - sc.add( "{" ); - sc.addIndented( copyField + " = (java.util.Date) " + thisField + ".clone();" ); - sc.add( "}" ); - sc.add( "" ); - } - else if ( ModelDefault.PROPERTIES.equals( modelField.getType() ) ) - { - sc.add( "if ( " + thisField + " != null )" ); - sc.add( "{" ); - sc.addIndented( copyField + " = (" + ModelDefault.PROPERTIES + ") " + thisField + ".clone();" ); - sc.add( "}" ); - sc.add( "" ); - } - else if ( modelField instanceof ModelAssociation ) - { + sc.add("}"); + sc.add(""); + } else if ("Date".equalsIgnoreCase(modelField.getType()) || "java.util.Date".equals(modelField.getType())) { + sc.add("if ( " + thisField + " != null )"); + sc.add("{"); + sc.addIndented(copyField + " = (java.util.Date) " + thisField + ".clone();"); + sc.add("}"); + sc.add(""); + } else if (ModelDefault.PROPERTIES.equals(modelField.getType())) { + sc.add("if ( " + thisField + " != null )"); + sc.add("{"); + sc.addIndented(copyField + " = (" + ModelDefault.PROPERTIES + ") " + thisField + ".clone();"); + sc.add("}"); + sc.add(""); + } else if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; - String cloneModeAssoc = getCloneMode( modelAssociation, cloneModeClass ); - - boolean deepClone = - JavaAssociationMetadata.CLONE_DEEP.equals( cloneModeAssoc ) && !immutableTypes.contains( - modelAssociation.getTo() ); - - if ( modelAssociation.isOneMultiplicity() ) - { - if ( deepClone ) - { - sc.add( "if ( " + thisField + " != null )" ); - sc.add( "{" ); - sc.addIndented( - copyField + " = (" + modelAssociation.getTo() + ") " + thisField + ".clone();" ); - sc.add( "}" ); - sc.add( "" ); + String cloneModeAssoc = getCloneMode(modelAssociation, cloneModeClass); + + boolean deepClone = JavaAssociationMetadata.CLONE_DEEP.equals(cloneModeAssoc) + && !immutableTypes.contains(modelAssociation.getTo()); + + if (modelAssociation.isOneMultiplicity()) { + if (deepClone) { + sc.add("if ( " + thisField + " != null )"); + sc.add("{"); + sc.addIndented(copyField + " = (" + modelAssociation.getTo() + ") " + thisField + ".clone();"); + sc.add("}"); + sc.add(""); } - } - else - { - sc.add( "if ( " + thisField + " != null )" ); - sc.add( "{" ); + } else { + sc.add("if ( " + thisField + " != null )"); + sc.add("{"); sc.indent(); - JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata( modelAssociation ); - JType componentType = getComponentType( modelAssociation, javaAssociationMetadata ); + JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata(modelAssociation); + JType componentType = getComponentType(modelAssociation, javaAssociationMetadata); - sc.add( copyField + " = " + getDefaultValue( modelAssociation, componentType ) + ";" ); + sc.add(copyField + " = " + getDefaultValue(modelAssociation, componentType) + ";"); - if ( isCollection( modelField.getType() ) ) - { - if ( deepClone ) - { - if ( useJava5 ) - { - sc.add( "for ( " + componentType.getName() + " item : " + thisField + " )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + thisField + ".iterator(); it.hasNext(); )" ); + if (isCollection(modelField.getType())) { + if (deepClone) { + if (useJava5) { + sc.add("for ( " + componentType.getName() + " item : " + thisField + " )"); + } else { + sc.add("for ( java.util.Iterator it = " + thisField + ".iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( useJava5 ) - { - sc.add( copyField + ".add( ( (" + modelAssociation.getTo() + ") item).clone() );" ); - } - else - { - sc.add( - copyField + ".add( ( (" + modelAssociation.getTo() + ") it.next() ).clone() );" ); + if (useJava5) { + sc.add(copyField + ".add( ( (" + modelAssociation.getTo() + ") item).clone() );"); + } else { + sc.add(copyField + ".add( ( (" + modelAssociation.getTo() + ") it.next() ).clone() );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); + } else { + sc.add(copyField + ".addAll( " + thisField + " );"); } - else - { - sc.add( copyField + ".addAll( " + thisField + " );" ); - } - } - else if ( isMap( modelField.getType() ) ) - { - sc.add( copyField + ".clear();" ); - sc.add( copyField + ".putAll( " + thisField + " );" ); + } else if (isMap(modelField.getType())) { + sc.add(copyField + ".clear();"); + sc.add(copyField + ".putAll( " + thisField + " );"); } sc.unindent(); - sc.add( "}" ); - sc.add( "" ); + sc.add("}"); + sc.add(""); } } } - if ( locationClass != null ) - { + if (locationClass != null) { String locationField = - ( (ModelClassMetadata) locationClass.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); - sc.add( "if ( copy." + locationField + " != null )" ); - sc.add( "{" ); + ((ModelClassMetadata) locationClass.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); + sc.add("if ( copy." + locationField + " != null )"); + sc.add("{"); sc.indent(); - sc.add( "copy." + locationField + " = new java.util.LinkedHashMap" + "( copy." + locationField + " );" ); + sc.add("copy." + locationField + " = new java.util.LinkedHashMap" + "( copy." + locationField + " );"); sc.unindent(); - sc.add( "}" ); - sc.add( "" ); + sc.add("}"); + sc.add(""); } - String cloneHook = getCloneHook( modelClass ); + String cloneHook = getCloneHook(modelClass); - if ( StringUtils.isNotEmpty( cloneHook ) && !"false".equalsIgnoreCase( cloneHook ) ) - { - if ( "true".equalsIgnoreCase( cloneHook ) ) - { + if (StringUtils.isNotEmpty(cloneHook) && !"false".equalsIgnoreCase(cloneHook)) { + if ("true".equalsIgnoreCase(cloneHook)) { cloneHook = "cloneHook"; } - sc.add( cloneHook + "( copy );" ); - sc.add( "" ); + sc.add(cloneHook + "( copy );"); + sc.add(""); } - sc.add( "return copy;" ); + sc.add("return copy;"); sc.unindent(); - sc.add( "}" ); - sc.add( "catch ( " + Exception.class.getName() + " ex )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("catch ( " + Exception.class.getName() + " ex )"); + sc.add("{"); sc.indent(); - sc.add( "throw (" + RuntimeException.class.getName() + ") new " + UnsupportedOperationException.class.getName() - + "( getClass().getName()" ); - sc.addIndented( "+ \" does not support clone()\" ).initCause( ex );" ); + sc.add("throw (" + RuntimeException.class.getName() + ") new " + UnsupportedOperationException.class.getName() + + "( getClass().getName()"); + sc.addIndented("+ \" does not support clone()\" ).initCause( ex );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - return new JMethod[]{ cloneMethod }; + return new JMethod[] {cloneMethod}; } - private String getCloneMode( ModelClass modelClass ) - throws ModelloException - { + private String getCloneMode(ModelClass modelClass) throws ModelloException { String cloneMode = null; - for ( ModelClass currentClass = modelClass; ; ) - { - JavaClassMetadata javaClassMetadata = (JavaClassMetadata) currentClass.getMetadata( JavaClassMetadata.ID ); + for (ModelClass currentClass = modelClass; ; ) { + JavaClassMetadata javaClassMetadata = (JavaClassMetadata) currentClass.getMetadata(JavaClassMetadata.ID); cloneMode = javaClassMetadata.getCloneMode(); - if ( cloneMode != null ) - { + if (cloneMode != null) { break; } String superClass = currentClass.getSuperClass(); - if ( StringUtils.isEmpty( superClass ) || !isClassInModel( superClass, getModel() ) ) - { + if (StringUtils.isEmpty(superClass) || !isClassInModel(superClass, getModel())) { break; } - currentClass = getModel().getClass( superClass, getGeneratedVersion() ); + currentClass = getModel().getClass(superClass, getGeneratedVersion()); } - if ( cloneMode == null ) - { + if (cloneMode == null) { cloneMode = JavaClassMetadata.CLONE_NONE; - } - else if ( !JavaClassMetadata.CLONE_MODES.contains( cloneMode ) ) - { - throw new ModelloException( - "The Java Modello Generator cannot use '" + cloneMode + "' as a value for , " - + "only the following values are acceptable " + JavaClassMetadata.CLONE_MODES ); + } else if (!JavaClassMetadata.CLONE_MODES.contains(cloneMode)) { + throw new ModelloException("The Java Modello Generator cannot use '" + cloneMode + + "' as a value for , " + "only the following values are acceptable " + + JavaClassMetadata.CLONE_MODES); } return cloneMode; } - private String getCloneMode( ModelAssociation modelAssociation, String cloneModeClass ) - throws ModelloException - { + private String getCloneMode(ModelAssociation modelAssociation, String cloneModeClass) throws ModelloException { JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); String cloneModeAssoc = javaAssociationMetadata.getCloneMode(); - if ( cloneModeAssoc == null ) - { + if (cloneModeAssoc == null) { cloneModeAssoc = cloneModeClass; - } - else if ( !JavaAssociationMetadata.CLONE_MODES.contains( cloneModeAssoc ) ) - { - throw new ModelloException( "The Java Modello Generator cannot use '" + cloneModeAssoc - + "' as a value for , " - + "only the following values are acceptable " - + JavaAssociationMetadata.CLONE_MODES ); + } else if (!JavaAssociationMetadata.CLONE_MODES.contains(cloneModeAssoc)) { + throw new ModelloException("The Java Modello Generator cannot use '" + cloneModeAssoc + + "' as a value for , " + + "only the following values are acceptable " + + JavaAssociationMetadata.CLONE_MODES); } return cloneModeAssoc; } - private String getCloneHook( ModelClass modelClass ) - throws ModelloException - { - JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID ); + private String getCloneHook(ModelClass modelClass) throws ModelloException { + JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.ID); return javaClassMetadata.getCloneHook(); } - private String generateLocationTracker( Model objectModel, ModelClass locationClass ) - throws ModelloException, IOException - { - if ( locationClass == null ) - { + private String generateLocationTracker(Model objectModel, ModelClass locationClass) + throws ModelloException, IOException { + if (locationClass == null) { return null; } String locationField = - ( (ModelClassMetadata) locationClass.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); + ((ModelClassMetadata) locationClass.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); - String propertyName = capitalise( singular( locationField ) ); + String propertyName = capitalise(singular(locationField)); String interfaceName = locationClass.getName() + "Tracker"; - String packageName = locationClass.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + String packageName = locationClass.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - JSourceWriter sourceWriter = newJSourceWriter( packageName, interfaceName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, interfaceName); - JInterface jInterface = new JInterface( packageName + '.' + interfaceName ); + JInterface jInterface = new JInterface(packageName + '.' + interfaceName); - initHeader( jInterface ); + initHeader(jInterface); - suppressAllWarnings( objectModel, jInterface ); + suppressAllWarnings(objectModel, jInterface); - JMethodSignature jMethod = new JMethodSignature( "get" + propertyName, new JType( locationClass.getName() ) ); - jMethod.setComment( "Gets the location of the specified field in the input source." ); - addParameter( jMethod, "Object", "field", "The key of the field, must not be null." ); + JMethodSignature jMethod = new JMethodSignature("get" + propertyName, new JType(locationClass.getName())); + jMethod.setComment("Gets the location of the specified field in the input source."); + addParameter(jMethod, "Object", "field", "The key of the field, must not be null."); String returnDoc = "The location of the field in the input source or null if unknown."; - jMethod.getJDocComment().addDescriptor( JDocDescriptor.createReturnDesc( returnDoc ) ); - jInterface.addMethod( jMethod ); + jMethod.getJDocComment().addDescriptor(JDocDescriptor.createReturnDesc(returnDoc)); + jInterface.addMethod(jMethod); - jMethod = new JMethodSignature( "set" + propertyName, null ); - jMethod.setComment( "Sets the location of the specified field." ); - addParameter( jMethod, "Object", "field", "The key of the field, must not be null." ); - addParameter( jMethod, locationClass.getName(), singular( locationField ), - "The location of the field, may be null." ); - jInterface.addMethod( jMethod ); + jMethod = new JMethodSignature("set" + propertyName, null); + jMethod.setComment("Sets the location of the specified field."); + addParameter(jMethod, "Object", "field", "The key of the field, must not be null."); + addParameter( + jMethod, + locationClass.getName(), + singular(locationField), + "The location of the field, may be null."); + jInterface.addMethod(jMethod); - jInterface.print( sourceWriter ); + jInterface.print(sourceWriter); sourceWriter.close(); return jInterface.getName(); } - private void generateLocationTracking( JClass jClass, ModelClass modelClass, ModelClass locationClass ) - throws ModelloException - { - if ( locationClass == null ) - { + private void generateLocationTracking(JClass jClass, ModelClass modelClass, ModelClass locationClass) + throws ModelloException { + if (locationClass == null) { return; } String superClass = modelClass.getSuperClass(); - ModelClassMetadata metadata = (ModelClassMetadata) locationClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata metadata = (ModelClassMetadata) locationClass.getMetadata(ModelClassMetadata.ID); String locationField = metadata.getLocationTracker(); boolean hasModeSuperClass = StringUtils.isNotEmpty(superClass) && isClassInModel(superClass, getModel()); - if (!hasModeSuperClass) - { - boolean useJava5 = hasJavaSourceSupport( 5 ); - String fieldType = "java.util.Map" + ( useJava5 ? "" : "" ); - String fieldImpl = "java.util.LinkedHashMap" + ( useJava5 ? "" : "" ); + if (!hasModeSuperClass) { + boolean useJava5 = hasJavaSourceSupport(5); + String fieldType = "java.util.Map" + (useJava5 ? "" : ""); + String fieldImpl = + "java.util.LinkedHashMap" + (useJava5 ? "" : ""); // private java.util.Map locations; - JField jField = new JField( new JType( fieldType ), locationField ); - jClass.addField( jField ); + JField jField = new JField(new JType(fieldType), locationField); + jClass.addField(jField); // public Location getOtherLocation( Object key ) - JMethod getter = - new JMethod( "getOther" + capitalise( singular( locationField ) ), new JType( locationClass.getName() ), null ); - getter.addParameter( new JParameter( new JType( "Object" ), "key" ) ); + JMethod getter = new JMethod( + "getOther" + capitalise(singular(locationField)), new JType(locationClass.getName()), null); + getter.addParameter(new JParameter(new JType("Object"), "key")); getter.getModifiers().makePrivate(); JSourceCode getterSc = getter.getSourceCode(); - getterSc.add( "return ( " + locationField + " != null ) ? " + locationField + ".get( key ) : null;" ); - getter.setComment( "" ); - jClass.addMethod( getter ); + getterSc.add("return ( " + locationField + " != null ) ? " + locationField + ".get( key ) : null;"); + getter.setComment(""); + jClass.addMethod(getter); // public void setOtherLocation( Object key, Location location ) - JMethod setter = new JMethod( "setOther" + capitalise( singular( locationField ) ) ); - setter.addParameter( new JParameter( new JType( "Object" ), "key" ) ); - setter.addParameter( new JParameter( new JType( locationClass.getName() ), singular( locationField ) ) ); + JMethod setter = new JMethod("setOther" + capitalise(singular(locationField))); + setter.addParameter(new JParameter(new JType("Object"), "key")); + setter.addParameter(new JParameter(new JType(locationClass.getName()), singular(locationField))); JSourceCode setterSc = setter.getSourceCode(); - setterSc.add( "if ( " + singular( locationField ) + " != null )" ); - setterSc.add( "{" ); + setterSc.add("if ( " + singular(locationField) + " != null )"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( "if ( this." + locationField + " == null )" ); - setterSc.add( "{" ); - setterSc.addIndented( "this." + locationField + " = new " + fieldImpl + "();" ); - setterSc.add( "}" ); - setterSc.add( "this." + locationField + ".put( key, " + singular( locationField ) + " );" ); + setterSc.add("if ( this." + locationField + " == null )"); + setterSc.add("{"); + setterSc.addIndented("this." + locationField + " = new " + fieldImpl + "();"); + setterSc.add("}"); + setterSc.add("this." + locationField + ".put( key, " + singular(locationField) + " );"); setterSc.unindent(); - setterSc.add( "}" ); - setter.setComment( "" ); - jClass.addMethod( setter ); + setterSc.add("}"); + setter.setComment(""); + jClass.addMethod(setter); } - JField ownLocation = new JField( new JType( locationClass.getName() ), singular( locationField ) ); - jClass.addField( ownLocation ); - for (ModelField field : modelClass.getAllFields()) - { - JField fieldLocation = new JField( new JType( locationClass.getName() ), field.getName() + capitalise( singular( locationField ) ) ); - jClass.addField( fieldLocation ); + JField ownLocation = new JField(new JType(locationClass.getName()), singular(locationField)); + jClass.addField(ownLocation); + for (ModelField field : modelClass.getAllFields()) { + JField fieldLocation = new JField( + new JType(locationClass.getName()), field.getName() + capitalise(singular(locationField))); + jClass.addField(fieldLocation); } // public Location getLocation( Object key ) JMethod getter = - new JMethod( "get" + capitalise( singular( locationField ) ), new JType( locationClass.getName() ), null ); - getter.addParameter( new JParameter( new JType( "Object" ), "key" ) ); + new JMethod("get" + capitalise(singular(locationField)), new JType(locationClass.getName()), null); + getter.addParameter(new JParameter(new JType("Object"), "key")); JSourceCode getterSc = getter.getSourceCode(); - getterSc.add( "if ( key instanceof String )" ); - getterSc.add( "{" ); + getterSc.add("if ( key instanceof String )"); + getterSc.add("{"); getterSc.indent(); - if ( hasJavaSourceSupport( 7 ) ) - { - getterSc.add( "switch ( ( String ) key )" ); - getterSc.add( "{" ); + if (hasJavaSourceSupport(7)) { + getterSc.add("switch ( ( String ) key )"); + getterSc.add("{"); getterSc.indent(); - getterSc.add( "case \"\" :" ); - getterSc.add( "{" ); + getterSc.add("case \"\" :"); + getterSc.add("{"); getterSc.indent(); - getterSc.add( "return this." + singular( locationField ) + ";" ); + getterSc.add("return this." + singular(locationField) + ";"); getterSc.unindent(); - getterSc.add( "}" ); - for (ModelField field : modelClass.getAllFields()) - { - getterSc.add( "case \"" + field.getName() + "\" :" ); - getterSc.add( "{" ); + getterSc.add("}"); + for (ModelField field : modelClass.getAllFields()) { + getterSc.add("case \"" + field.getName() + "\" :"); + getterSc.add("{"); getterSc.indent(); - getterSc.add( "return " + field.getName() + capitalise( singular( locationField ) ) + ";" ); + getterSc.add("return " + field.getName() + capitalise(singular(locationField)) + ";"); getterSc.unindent(); - getterSc.add( "}" ); + getterSc.add("}"); } - getterSc.add( "default :" ); - getterSc.add( "{" ); + getterSc.add("default :"); + getterSc.add("{"); getterSc.indent(); - if (hasModeSuperClass) - { - getterSc.add( "return super.get" + capitalise( singular( locationField ) ) + "( key );" ); - } - else - { - getterSc.add( "return getOther" + capitalise( singular( locationField ) ) + "( key );" ); + if (hasModeSuperClass) { + getterSc.add("return super.get" + capitalise(singular(locationField)) + "( key );"); + } else { + getterSc.add("return getOther" + capitalise(singular(locationField)) + "( key );"); } getterSc.unindent(); - getterSc.add( "}" ); - getterSc.add( "}" ); - } - else - { - getterSc.add( "if ( \"\".equals( key ) )" ); - getterSc.add( "{" ); + getterSc.add("}"); + getterSc.add("}"); + } else { + getterSc.add("if ( \"\".equals( key ) )"); + getterSc.add("{"); getterSc.indent(); - getterSc.add( "return this." + singular( locationField ) + ";" ); + getterSc.add("return this." + singular(locationField) + ";"); getterSc.unindent(); - getterSc.add( "}" ); - for (ModelField field : modelClass.getAllFields()) - { - getterSc.add( "else if ( \"" + field.getName() + "\".equals( key ) )" ); - getterSc.add( "{" ); + getterSc.add("}"); + for (ModelField field : modelClass.getAllFields()) { + getterSc.add("else if ( \"" + field.getName() + "\".equals( key ) )"); + getterSc.add("{"); getterSc.indent(); - getterSc.add( "return " + field.getName() + capitalise( singular( locationField ) ) + ";" ); + getterSc.add("return " + field.getName() + capitalise(singular(locationField)) + ";"); getterSc.unindent(); - getterSc.add( "}" ); + getterSc.add("}"); } - getterSc.add( "else" ); - getterSc.add( "{" ); + getterSc.add("else"); + getterSc.add("{"); getterSc.indent(); - if (hasModeSuperClass) - { - getterSc.add( "return super.get" + capitalise( singular( locationField ) ) + "( key );" ); - } - else - { - getterSc.add( "return getOther" + capitalise( singular( locationField ) ) + "( key );" ); + if (hasModeSuperClass) { + getterSc.add("return super.get" + capitalise(singular(locationField)) + "( key );"); + } else { + getterSc.add("return getOther" + capitalise(singular(locationField)) + "( key );"); } getterSc.unindent(); - getterSc.add( "}" ); + getterSc.add("}"); } getterSc.unindent(); - getterSc.add( "}" ); - getterSc.add( "else" ); - getterSc.add( "{" ); + getterSc.add("}"); + getterSc.add("else"); + getterSc.add("{"); getterSc.indent(); - if (hasModeSuperClass) - { - getterSc.add( "return super.get" + capitalise( singular( locationField ) ) + "( key );" ); - } - else - { - getterSc.add( "return getOther" + capitalise( singular( locationField ) ) + "( key );" ); + if (hasModeSuperClass) { + getterSc.add("return super.get" + capitalise(singular(locationField)) + "( key );"); + } else { + getterSc.add("return getOther" + capitalise(singular(locationField)) + "( key );"); } getterSc.unindent(); - getterSc.add( "}" ); + getterSc.add("}"); - getter.setComment( "" ); - jClass.addMethod( getter ); + getter.setComment(""); + jClass.addMethod(getter); // public void setLocation( Object key, Location location ) - JMethod setter = new JMethod( "set" + capitalise( singular( locationField ) ) ); - setter.addParameter( new JParameter( new JType( "Object" ), "key" ) ); - setter.addParameter( new JParameter( new JType( locationClass.getName() ), singular( locationField ) ) ); + JMethod setter = new JMethod("set" + capitalise(singular(locationField))); + setter.addParameter(new JParameter(new JType("Object"), "key")); + setter.addParameter(new JParameter(new JType(locationClass.getName()), singular(locationField))); JSourceCode setterSc = setter.getSourceCode(); - setterSc.add( "if ( key instanceof String )" ); - setterSc.add( "{" ); + setterSc.add("if ( key instanceof String )"); + setterSc.add("{"); setterSc.indent(); - if ( hasJavaSourceSupport( 7 ) ) - { - setterSc.add( "switch ( ( String ) key )" ); - setterSc.add( "{" ); + if (hasJavaSourceSupport(7)) { + setterSc.add("switch ( ( String ) key )"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( "case \"\" :" ); - setterSc.add( "{" ); + setterSc.add("case \"\" :"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( "this." + singular( locationField ) + " = " + singular(locationField) + ";" ); + setterSc.add("this." + singular(locationField) + " = " + singular(locationField) + ";"); setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); - for (ModelField field : modelClass.getAllFields()) - { - setterSc.add( "case \"" + field.getName()+ "\" :" ); - setterSc.add( "{" ); + setterSc.add("}"); + for (ModelField field : modelClass.getAllFields()) { + setterSc.add("case \"" + field.getName() + "\" :"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( field.getName() + capitalise( singular( locationField ) ) + " = " + singular(locationField) + ";" ); + setterSc.add( + field.getName() + capitalise(singular(locationField)) + " = " + singular(locationField) + ";"); setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); + setterSc.add("}"); } - setterSc.add( "default :" ); - setterSc.add( "{" ); + setterSc.add("default :"); + setterSc.add("{"); setterSc.indent(); - if (hasModeSuperClass) - { - setterSc.add( "super.set" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); - } - else - { - setterSc.add( "setOther" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); + if (hasModeSuperClass) { + setterSc.add("super.set" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + + " );"); + } else { + setterSc.add( + "setOther" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + " );"); } setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); + setterSc.add("}"); setterSc.unindent(); - setterSc.add( "}" ); - } - else - { - setterSc.add( "if ( \"\".equals( key ) )" ); - setterSc.add( "{" ); + setterSc.add("}"); + } else { + setterSc.add("if ( \"\".equals( key ) )"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( "this." + singular( locationField ) + " = " + singular(locationField) + ";" ); + setterSc.add("this." + singular(locationField) + " = " + singular(locationField) + ";"); setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); - for ( ModelField field : modelClass.getAllFields() ) - { - setterSc.add( "else if ( \"" + field.getName()+ "\".equals( key ) )" ); - setterSc.add( "{" ); + setterSc.add("}"); + for (ModelField field : modelClass.getAllFields()) { + setterSc.add("else if ( \"" + field.getName() + "\".equals( key ) )"); + setterSc.add("{"); setterSc.indent(); - setterSc.add( field.getName() + capitalise( singular( locationField ) ) + " = " + singular(locationField) + ";" ); + setterSc.add( + field.getName() + capitalise(singular(locationField)) + " = " + singular(locationField) + ";"); setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); + setterSc.add("}"); } - setterSc.add( "else" ); - setterSc.add( "{" ); + setterSc.add("else"); + setterSc.add("{"); setterSc.indent(); - if (hasModeSuperClass) - { - setterSc.add( "super.set" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); - } - else - { - setterSc.add( "setOther" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); + if (hasModeSuperClass) { + setterSc.add("super.set" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + + " );"); + } else { + setterSc.add( + "setOther" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + " );"); } setterSc.add("return;"); setterSc.unindent(); - setterSc.add( "}" ); + setterSc.add("}"); } setterSc.unindent(); - setterSc.add( "}" ); - setterSc.add( "else" ); - setterSc.add( "{" ); + setterSc.add("}"); + setterSc.add("else"); + setterSc.add("{"); setterSc.indent(); - if (hasModeSuperClass) - { - setterSc.add( "super.set" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); - } - else - { - setterSc.add( "setOther" + capitalise( singular( locationField ) ) + "( key, " + singular(locationField) + " );" ); + if (hasModeSuperClass) { + setterSc.add( + "super.set" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + " );"); + } else { + setterSc.add( + "setOther" + capitalise(singular(locationField)) + "( key, " + singular(locationField) + " );"); } setterSc.unindent(); - setterSc.add( "}" ); + setterSc.add("}"); - setter.setComment( "" ); - jClass.addMethod( setter ); + setter.setComment(""); + jClass.addMethod(setter); } - private void generateLocationBean( JClass jClass, ModelClass locationClass, ModelClass sourceClass ) - throws ModelloException - { - jClass.getModifiers().setFinal( true ); + private void generateLocationBean(JClass jClass, ModelClass locationClass, ModelClass sourceClass) + throws ModelloException { + jClass.getModifiers().setFinal(true); String locationsField = - ( (ModelClassMetadata) locationClass.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); + ((ModelClassMetadata) locationClass.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); JavaFieldMetadata readOnlyField = new JavaFieldMetadata(); - readOnlyField.setSetter( false ); + readOnlyField.setSetter(false); // int lineNumber; - ModelField lineNumber = new ModelField( locationClass, "lineNumber" ); - lineNumber.setDescription( "The one-based line number. The value will be non-positive if unknown." ); - lineNumber.setType( "int" ); - lineNumber.setDefaultValue( "-1" ); - lineNumber.addMetadata( readOnlyField ); - createField( jClass, lineNumber ); + ModelField lineNumber = new ModelField(locationClass, "lineNumber"); + lineNumber.setDescription("The one-based line number. The value will be non-positive if unknown."); + lineNumber.setType("int"); + lineNumber.setDefaultValue("-1"); + lineNumber.addMetadata(readOnlyField); + createField(jClass, lineNumber); // int columnNumber; - ModelField columnNumber = new ModelField( locationClass, "columnNumber" ); - columnNumber.setDescription( "The one-based column number. The value will be non-positive if unknown." ); - columnNumber.setType( "int" ); - columnNumber.setDefaultValue( "-1" ); - columnNumber.addMetadata( readOnlyField ); - createField( jClass, columnNumber ); + ModelField columnNumber = new ModelField(locationClass, "columnNumber"); + columnNumber.setDescription("The one-based column number. The value will be non-positive if unknown."); + columnNumber.setType("int"); + columnNumber.setDefaultValue("-1"); + columnNumber.addMetadata(readOnlyField); + createField(jClass, columnNumber); // Source source; ModelField source = null; - if ( sourceClass != null ) - { - ModelClassMetadata metadata = (ModelClassMetadata) sourceClass.getMetadata( ModelClassMetadata.ID ); + if (sourceClass != null) { + ModelClassMetadata metadata = (ModelClassMetadata) sourceClass.getMetadata(ModelClassMetadata.ID); String sourceField = metadata.getSourceTracker(); - source = new ModelField( locationClass, sourceField ); - source.setType( sourceClass.getName() ); - source.addMetadata( readOnlyField ); - createField( jClass, source ); + source = new ModelField(locationClass, sourceField); + source.setType(sourceClass.getName()); + source.addMetadata(readOnlyField); + createField(jClass, source); } // Location( int lineNumber, int columnNumber ); JConstructor jConstructor = jClass.createConstructor(); JSourceCode sc = jConstructor.getSourceCode(); - jConstructor.addParameter( new JParameter( JType.INT, lineNumber.getName() ) ); - sc.add( "this." + lineNumber.getName() + " = " + lineNumber.getName() + ";" ); + jConstructor.addParameter(new JParameter(JType.INT, lineNumber.getName())); + sc.add("this." + lineNumber.getName() + " = " + lineNumber.getName() + ";"); - jConstructor.addParameter( new JParameter( JType.INT, columnNumber.getName() ) ); - sc.add( "this." + columnNumber.getName() + " = " + columnNumber.getName() + ";" ); + jConstructor.addParameter(new JParameter(JType.INT, columnNumber.getName())); + sc.add("this." + columnNumber.getName() + " = " + columnNumber.getName() + ";"); // Location( int lineNumber, int columnNumber, Source source ); - if ( sourceClass != null ) - { - jConstructor = jClass.createConstructor( jConstructor.getParameters() ); - sc.copyInto( jConstructor.getSourceCode() ); + if (sourceClass != null) { + jConstructor = jClass.createConstructor(jConstructor.getParameters()); + sc.copyInto(jConstructor.getSourceCode()); sc = jConstructor.getSourceCode(); - jConstructor.addParameter( new JParameter( new JType( sourceClass.getName() ), source.getName() ) ); - sc.add( "this." + source.getName() + " = " + source.getName() + ";" ); + jConstructor.addParameter(new JParameter(new JType(sourceClass.getName()), source.getName())); + sc.add("this." + source.getName() + " = " + source.getName() + ";"); } - boolean useJava5 = hasJavaSourceSupport( 5 ); - JType fieldType = new JMapType( "java.util.Map", new JType(locationClass.getName()), useJava5 ); - JType fieldImpl = new JMapType( "java.util.LinkedHashMap", new JType( locationClass.getName() ), useJava5 ); + boolean useJava5 = hasJavaSourceSupport(5); + JType fieldType = new JMapType("java.util.Map", new JType(locationClass.getName()), useJava5); + JType fieldImpl = new JMapType("java.util.LinkedHashMap", new JType(locationClass.getName()), useJava5); // public Map getLocations() - JMethod jMethod = new JMethod( "get" + capitalise( locationsField ), fieldType, null ); + JMethod jMethod = new JMethod("get" + capitalise(locationsField), fieldType, null); sc = jMethod.getSourceCode(); - sc.add( "return " + locationsField + ";" ); - jMethod.setComment( "" ); - jClass.addMethod( jMethod ); + sc.add("return " + locationsField + ";"); + jMethod.setComment(""); + jClass.addMethod(jMethod); // public void setLocations( Map locations ) - jMethod = new JMethod( "set" + capitalise( locationsField ) ); - jMethod.addParameter( new JParameter( fieldType, locationsField ) ); + jMethod = new JMethod("set" + capitalise(locationsField)); + jMethod.addParameter(new JParameter(fieldType, locationsField)); sc = jMethod.getSourceCode(); - sc.add( "this." + locationsField + " = " + locationsField + ";" ); - jMethod.setComment( "" ); - jClass.addMethod( jMethod ); + sc.add("this." + locationsField + " = " + locationsField + ";"); + jMethod.setComment(""); + jClass.addMethod(jMethod); // public static Location merge( Location target, Location source, boolean sourceDominant ) - jMethod = new JMethod( "merge", new JType( locationClass.getName() ), null ); - jMethod.getModifiers().setStatic( true ); - jMethod.addParameter( new JParameter( new JType( locationClass.getName() ), "target" ) ); - jMethod.addParameter( new JParameter( new JType( locationClass.getName() ), "source" ) ); - jMethod.addParameter( new JParameter( JType.BOOLEAN, "sourceDominant" ) ); + jMethod = new JMethod("merge", new JType(locationClass.getName()), null); + jMethod.getModifiers().setStatic(true); + jMethod.addParameter(new JParameter(new JType(locationClass.getName()), "target")); + jMethod.addParameter(new JParameter(new JType(locationClass.getName()), "source")); + jMethod.addParameter(new JParameter(JType.BOOLEAN, "sourceDominant")); sc = jMethod.getSourceCode(); - sc.add( "if ( source == null )" ); - sc.add( "{" ); - sc.addIndented( "return target;" ); - sc.add( "}" ); - sc.add( "else if ( target == null )" ); - sc.add( "{" ); - sc.addIndented( "return source;" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( locationClass.getName() + " result =" ); - sc.add( " new " + locationClass.getName() + "( target.getLineNumber(), target.getColumnNumber()" + ( - sourceClass != null - ? ", target.get" + capitalise( source.getName() ) + "()" - : "" ) + " );" ); - sc.add( "" ); - sc.add( fieldType + " locations;" ); - sc.add( fieldType + " sourceLocations = source.get" + capitalise( locationsField ) + "();" ); - sc.add( fieldType + " targetLocations = target.get" + capitalise( locationsField ) + "();" ); - sc.add( "if ( sourceLocations == null )" ); - sc.add( "{" ); - sc.addIndented( "locations = targetLocations;" ); - sc.add( "}" ); - sc.add( "else if ( targetLocations == null )" ); - sc.add( "{" ); - sc.addIndented( "locations = sourceLocations;" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "locations = new " + fieldImpl.getName() + "();" ); - sc.addIndented( "locations.putAll( sourceDominant ? targetLocations : sourceLocations );" ); - sc.addIndented( "locations.putAll( sourceDominant ? sourceLocations : targetLocations );" ); - sc.add( "}" ); - sc.add( "result.set" + capitalise( locationsField ) + "( locations );" ); - sc.add( "" ); - sc.add( "return result;" ); - jClass.addMethod( jMethod ); + sc.add("if ( source == null )"); + sc.add("{"); + sc.addIndented("return target;"); + sc.add("}"); + sc.add("else if ( target == null )"); + sc.add("{"); + sc.addIndented("return source;"); + sc.add("}"); + sc.add(""); + sc.add(locationClass.getName() + " result ="); + sc.add(" new " + locationClass.getName() + "( target.getLineNumber(), target.getColumnNumber()" + + (sourceClass != null ? ", target.get" + capitalise(source.getName()) + "()" : "") + " );"); + sc.add(""); + sc.add(fieldType + " locations;"); + sc.add(fieldType + " sourceLocations = source.get" + capitalise(locationsField) + "();"); + sc.add(fieldType + " targetLocations = target.get" + capitalise(locationsField) + "();"); + sc.add("if ( sourceLocations == null )"); + sc.add("{"); + sc.addIndented("locations = targetLocations;"); + sc.add("}"); + sc.add("else if ( targetLocations == null )"); + sc.add("{"); + sc.addIndented("locations = sourceLocations;"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("locations = new " + fieldImpl.getName() + "();"); + sc.addIndented("locations.putAll( sourceDominant ? targetLocations : sourceLocations );"); + sc.addIndented("locations.putAll( sourceDominant ? sourceLocations : targetLocations );"); + sc.add("}"); + sc.add("result.set" + capitalise(locationsField) + "( locations );"); + sc.add(""); + sc.add("return result;"); + jClass.addMethod(jMethod); // public static Location merge( Location target, Location source, Collection indices ) - jMethod = new JMethod( "merge", new JType( locationClass.getName() ), null ); - jMethod.getModifiers().setStatic( true ); - jMethod.addParameter( new JParameter( new JType( locationClass.getName() ), "target" ) ); - jMethod.addParameter( new JParameter( new JType( locationClass.getName() ), "source" ) ); + jMethod = new JMethod("merge", new JType(locationClass.getName()), null); + jMethod.getModifiers().setStatic(true); + jMethod.addParameter(new JParameter(new JType(locationClass.getName()), "target")); + jMethod.addParameter(new JParameter(new JType(locationClass.getName()), "source")); jMethod.addParameter( - new JParameter( new JCollectionType( "java.util.Collection", new JType( "Integer" ), useJava5 ), - "indices" ) ); + new JParameter(new JCollectionType("java.util.Collection", new JType("Integer"), useJava5), "indices")); String intWrap = useJava5 ? "Integer.valueOf" : "new Integer"; sc = jMethod.getSourceCode(); - sc.add( "if ( source == null )" ); - sc.add( "{" ); - sc.addIndented( "return target;" ); - sc.add( "}" ); - sc.add( "else if ( target == null )" ); - sc.add( "{" ); - sc.addIndented( "return source;" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( locationClass.getName() + " result =" ); - sc.add( " new " + locationClass.getName() + "( target.getLineNumber(), target.getColumnNumber()" + ( - sourceClass != null - ? ", target.get" + capitalise( source.getName() ) + "()" - : "" ) + " );" ); - sc.add( "" ); - sc.add( fieldType + " locations;" ); - sc.add( fieldType + " sourceLocations = source.get" + capitalise( locationsField ) + "();" ); - sc.add( fieldType + " targetLocations = target.get" + capitalise( locationsField ) + "();" ); - sc.add( "if ( sourceLocations == null )" ); - sc.add( "{" ); - sc.addIndented( "locations = targetLocations;" ); - sc.add( "}" ); - sc.add( "else if ( targetLocations == null )" ); - sc.add( "{" ); - sc.addIndented( "locations = sourceLocations;" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); + sc.add("if ( source == null )"); + sc.add("{"); + sc.addIndented("return target;"); + sc.add("}"); + sc.add("else if ( target == null )"); + sc.add("{"); + sc.addIndented("return source;"); + sc.add("}"); + sc.add(""); + sc.add(locationClass.getName() + " result ="); + sc.add(" new " + locationClass.getName() + "( target.getLineNumber(), target.getColumnNumber()" + + (sourceClass != null ? ", target.get" + capitalise(source.getName()) + "()" : "") + " );"); + sc.add(""); + sc.add(fieldType + " locations;"); + sc.add(fieldType + " sourceLocations = source.get" + capitalise(locationsField) + "();"); + sc.add(fieldType + " targetLocations = target.get" + capitalise(locationsField) + "();"); + sc.add("if ( sourceLocations == null )"); + sc.add("{"); + sc.addIndented("locations = targetLocations;"); + sc.add("}"); + sc.add("else if ( targetLocations == null )"); + sc.add("{"); + sc.addIndented("locations = sourceLocations;"); + sc.add("}"); + sc.add("else"); + sc.add("{"); sc.indent(); - sc.add( "locations = new " + fieldImpl + "();" ); - sc.add( "for ( java.util.Iterator" + ( useJava5 ? "" : "" ) - + " it = indices.iterator(); it.hasNext(); )" ); - sc.add( "{" ); + sc.add("locations = new " + fieldImpl + "();"); + sc.add("for ( java.util.Iterator" + (useJava5 ? "" : "") + + " it = indices.iterator(); it.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( locationClass.getName() + " location;" ); - sc.add( "Integer index = " + ( useJava5 ? "" : "(Integer) " ) + "it.next();" ); - sc.add( "if ( index.intValue() < 0 )" ); - sc.add( "{" ); - sc.addIndented( "location = sourceLocations.get( " + intWrap + "( ~index.intValue() ) );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "location = targetLocations.get( index );" ); - sc.add( "}" ); - sc.add( "locations.put( " + intWrap + "( locations.size() ), location );" ); + sc.add(locationClass.getName() + " location;"); + sc.add("Integer index = " + (useJava5 ? "" : "(Integer) ") + "it.next();"); + sc.add("if ( index.intValue() < 0 )"); + sc.add("{"); + sc.addIndented("location = sourceLocations.get( " + intWrap + "( ~index.intValue() ) );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("location = targetLocations.get( index );"); + sc.add("}"); + sc.add("locations.put( " + intWrap + "( locations.size() ), location );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "result.set" + capitalise( locationsField ) + "( locations );" ); - sc.add( "" ); - sc.add( "return result;" ); - jClass.addMethod( jMethod ); - - JClass stringFormatterClass = jClass.createInnerClass( "StringFormatter" ); - stringFormatterClass.getModifiers().setStatic( true ); - stringFormatterClass.getModifiers().setAbstract( true ); - - jMethod = new JMethod( "toString", new JType( "String" ), null ); - jMethod.getModifiers().setAbstract( true ); - jMethod.addParameter( new JParameter( new JType( locationClass.getName() ), "location" ) ); - stringFormatterClass.addMethod( jMethod ); + sc.add("}"); + sc.add("result.set" + capitalise(locationsField) + "( locations );"); + sc.add(""); + sc.add("return result;"); + jClass.addMethod(jMethod); + + JClass stringFormatterClass = jClass.createInnerClass("StringFormatter"); + stringFormatterClass.getModifiers().setStatic(true); + stringFormatterClass.getModifiers().setAbstract(true); + + jMethod = new JMethod("toString", new JType("String"), null); + jMethod.getModifiers().setAbstract(true); + jMethod.addParameter(new JParameter(new JType(locationClass.getName()), "location")); + stringFormatterClass.addMethod(jMethod); } /** @@ -1261,350 +1133,277 @@ private void generateLocationBean( JClass jClass, ModelClass locationClass, Mode * @param string The string to work with * @return The string that came in but with a period at the end */ - private String appendPeriod( String string ) - { - if ( string == null ) - { + private String appendPeriod(String string) { + if (string == null) { return string; } String trimmedString = string.trim(); - if ( trimmedString.endsWith( "." ) || trimmedString.endsWith( "!" ) || trimmedString.endsWith( "?" ) - || trimmedString.endsWith( ">" ) ) - { + if (trimmedString.endsWith(".") + || trimmedString.endsWith("!") + || trimmedString.endsWith("?") + || trimmedString.endsWith(">")) { return string; - } - else - { + } else { return string + "."; } } - private String createHashCodeForField( ModelField identifier ) - { + private String createHashCodeForField(ModelField identifier) { String name = identifier.getName(); String type = identifier.getType(); - if ( "boolean".equals( type ) ) - { + if ("boolean".equals(type)) { return "( " + name + " ? 0 : 1 )"; - } - else if ( "byte".equals( type ) || "char".equals( type ) || "short".equals( type ) || "int".equals( type ) ) - { + } else if ("byte".equals(type) || "char".equals(type) || "short".equals(type) || "int".equals(type)) { return "(int) " + name; - } - else if ( "long".equals( type ) ) - { + } else if ("long".equals(type)) { return "(int) ( " + name + " ^ ( " + name + " >>> 32 ) )"; - } - else if ( "float".equals( type ) ) - { + } else if ("float".equals(type)) { return "Float.floatToIntBits( " + name + " )"; - } - else if ( "double".equals( type ) ) - { + } else if ("double".equals(type)) { return "(int) ( Double.doubleToLongBits( " + identifier.getName() + " ) ^ ( Double.doubleToLongBits( " - + identifier.getName() + " ) >>> 32 ) )"; - } - else - { + + identifier.getName() + " ) >>> 32 ) )"; + } else { return "( " + name + " != null ? " + name + ".hashCode() : 0 )"; } } - private JField createField( ModelField modelField ) - throws ModelloException - { + private JField createField(ModelField modelField) throws ModelloException { JType type; String baseType = modelField.getType(); - if ( modelField.isArray() ) - { + if (modelField.isArray()) { // remove [] at the end of the type - baseType = baseType.substring( 0, baseType.length() - 2 ); + baseType = baseType.substring(0, baseType.length() - 2); } - if ( "boolean".equals( baseType ) ) - { + if ("boolean".equals(baseType)) { type = JType.BOOLEAN; - } - else if ( "byte".equals( baseType ) ) - { + } else if ("byte".equals(baseType)) { type = JType.BYTE; - } - else if ( "char".equals( baseType ) ) - { + } else if ("char".equals(baseType)) { type = JType.CHAR; - } - else if ( "double".equals( baseType ) ) - { + } else if ("double".equals(baseType)) { type = JType.DOUBLE; - } - else if ( "float".equals( baseType ) ) - { + } else if ("float".equals(baseType)) { type = JType.FLOAT; - } - else if ( "int".equals( baseType ) ) - { + } else if ("int".equals(baseType)) { type = JType.INT; - } - else if ( "short".equals( baseType ) ) - { + } else if ("short".equals(baseType)) { type = JType.SHORT; - } - else if ( "long".equals( baseType ) ) - { + } else if ("long".equals(baseType)) { type = JType.LONG; - } - else if ( "Date".equals( baseType ) ) - { - type = new JClass( "java.util.Date" ); - } - else if ( "DOM".equals( baseType ) ) - { + } else if ("Date".equals(baseType)) { + type = new JClass("java.util.Date"); + } else if ("DOM".equals(baseType)) { // TODO: maybe DOM is not how to specify it in the model, but just Object and markup Xpp3Dom for the // Xpp3Reader? // not sure how we'll treat it for the other sources, eg sql. - type = new JClass( "Object" ); - } - else - { - type = new JClass( baseType ); + type = new JClass("Object"); + } else { + type = new JClass(baseType); } - boolean useJava5 = hasJavaSourceSupport( 5 ); - if ( modelField.isArray() ) - { - type = new JArrayType( type, useJava5 ); + boolean useJava5 = hasJavaSourceSupport(5); + if (modelField.isArray()) { + type = new JArrayType(type, useJava5); } - JField field = new JField( type, modelField.getName() ); + JField field = new JField(type, modelField.getName()); - if ( modelField.isModelVersionField() ) - { - field.setInitString( "\"" + getGeneratedVersion() + "\"" ); + if (modelField.isModelVersionField()) { + field.setInitString("\"" + getGeneratedVersion() + "\""); } - if ( modelField.getDefaultValue() != null ) - { - field.setInitString( getJavaDefaultValue( modelField ) ); + if (modelField.getDefaultValue() != null) { + field.setInitString(getJavaDefaultValue(modelField)); } - if ( StringUtils.isNotEmpty( modelField.getDescription() ) ) - { - field.setComment( appendPeriod( modelField.getDescription() ) ); + if (StringUtils.isNotEmpty(modelField.getDescription())) { + field.setComment(appendPeriod(modelField.getDescription())); } - if ( useJava5 && !modelField.getAnnotations().isEmpty() ) - { - for ( String annotation : modelField.getAnnotations() ) - { - field.appendAnnotation( annotation ); + if (useJava5 && !modelField.getAnnotations().isEmpty()) { + for (String annotation : modelField.getAnnotations()) { + field.appendAnnotation(annotation); } } return field; } - private void createField( JClass jClass, ModelField modelField ) - throws ModelloException - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID ); + private void createField(JClass jClass, ModelField modelField) throws ModelloException { + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata(JavaFieldMetadata.ID); - JField field = createField( modelField ); + JField field = createField(modelField); - jClass.addField( field ); + jClass.addField(field); - if ( javaFieldMetadata.isGetter() ) - { - jClass.addMethod( createGetter( field, modelField ) ); + if (javaFieldMetadata.isGetter()) { + jClass.addMethod(createGetter(field, modelField)); } - if ( javaFieldMetadata.isSetter() ) - { - jClass.addMethod( createSetter( field, modelField ) ); + if (javaFieldMetadata.isSetter()) { + jClass.addMethod(createSetter(field, modelField)); } } - private JMethod createGetter( JField field, ModelField modelField ) - { - String propertyName = capitalise( field.getName() ); + private JMethod createGetter(JField field, ModelField modelField) { + String propertyName = capitalise(field.getName()); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata(JavaFieldMetadata.ID); String prefix = javaFieldMetadata.isBooleanGetter() ? "is" : "get"; JType returnType = field.getType(); String interfaceCast = ""; - if ( modelField instanceof ModelAssociation ) - { + if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); - if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) - && !javaFieldMetadata.isBooleanGetter() ) - { - returnType = new JClass( javaAssociationMetadata.getInterfaceName() ); + if (StringUtils.isNotEmpty(javaAssociationMetadata.getInterfaceName()) + && !javaFieldMetadata.isBooleanGetter()) { + returnType = new JClass(javaAssociationMetadata.getInterfaceName()); interfaceCast = "(" + javaAssociationMetadata.getInterfaceName() + ") "; } } - JMethod getter = new JMethod( prefix + propertyName, returnType, null ); + JMethod getter = new JMethod(prefix + propertyName, returnType, null); - StringBuilder comment = new StringBuilder( "Get " ); - if ( StringUtils.isEmpty( modelField.getDescription() ) ) - { - comment.append( "the " ); - comment.append( field.getName() ); - comment.append( " field" ); - } - else - { - comment.append( StringUtils.lowercaseFirstLetter( modelField.getDescription().trim() ) ); + StringBuilder comment = new StringBuilder("Get "); + if (StringUtils.isEmpty(modelField.getDescription())) { + comment.append("the "); + comment.append(field.getName()); + comment.append(" field"); + } else { + comment.append( + StringUtils.lowercaseFirstLetter(modelField.getDescription().trim())); } - getter.getJDocComment().setComment( appendPeriod( comment.toString() ) ); + getter.getJDocComment().setComment(appendPeriod(comment.toString())); - getter.getSourceCode().add( "return " + interfaceCast + "this." + field.getName() + ";" ); + getter.getSourceCode().add("return " + interfaceCast + "this." + field.getName() + ";"); return getter; } - private JMethod createSetter( JField field, ModelField modelField ) - throws ModelloException - { - return createSetter( field, modelField, false ); + private JMethod createSetter(JField field, ModelField modelField) throws ModelloException { + return createSetter(field, modelField, false); } // since 1.8 - private JMethod createSetter( JField field, ModelField modelField, boolean isBuilderMethod ) - throws ModelloException - { - String propertyName = capitalise( field.getName() ); + private JMethod createSetter(JField field, ModelField modelField, boolean isBuilderMethod) throws ModelloException { + String propertyName = capitalise(field.getName()); JMethod setter; - if ( isBuilderMethod ) - { - setter = new JMethod( "set" + propertyName, new JClass( "Builder" ), "this builder instance" ); - } - else - { - setter = new JMethod( "set" + propertyName ); + if (isBuilderMethod) { + setter = new JMethod("set" + propertyName, new JClass("Builder"), "this builder instance"); + } else { + setter = new JMethod("set" + propertyName); } - StringBuilder comment = new StringBuilder( "Set " ); - if ( StringUtils.isEmpty( modelField.getDescription() ) ) - { - comment.append( "the " ); - comment.append( field.getName() ); - comment.append( " field" ); + StringBuilder comment = new StringBuilder("Set "); + if (StringUtils.isEmpty(modelField.getDescription())) { + comment.append("the "); + comment.append(field.getName()); + comment.append(" field"); + } else { + comment.append( + StringUtils.lowercaseFirstLetter(modelField.getDescription().trim())); } - else - { - comment.append( StringUtils.lowercaseFirstLetter( modelField.getDescription().trim() ) ); - } - setter.getJDocComment().setComment( appendPeriod( comment.toString() ) ); + setter.getJDocComment().setComment(appendPeriod(comment.toString())); - JType parameterType = getDesiredType( modelField, false ); + JType parameterType = getDesiredType(modelField, false); - setter.addParameter( new JParameter( parameterType, field.getName() ) ); + setter.addParameter(new JParameter(parameterType, field.getName())); JSourceCode sc = setter.getSourceCode(); - if ( modelField instanceof ModelAssociation ) - { + if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); boolean isOneMultiplicity = - isBidirectionalAssociation( modelAssociation ) && modelAssociation.isOneMultiplicity(); + isBidirectionalAssociation(modelAssociation) && modelAssociation.isOneMultiplicity(); - if ( isOneMultiplicity && javaAssociationMetadata.isBidi() ) - { - sc.add( "if ( this." + field.getName() + " != null )" ); + if (isOneMultiplicity && javaAssociationMetadata.isBidi()) { + sc.add("if ( this." + field.getName() + " != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "this." + field.getName() + ".break" + modelAssociation.getModelClass().getName() - + "Association( this );" ); + sc.add("this." + field.getName() + ".break" + + modelAssociation.getModelClass().getName() + "Association( this );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); } String interfaceCast = ""; - if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) - && modelAssociation.isOneMultiplicity() ) - { + if (StringUtils.isNotEmpty(javaAssociationMetadata.getInterfaceName()) + && modelAssociation.isOneMultiplicity()) { interfaceCast = "(" + field.getType().getName() + ") "; - createClassCastAssertion( sc, modelAssociation, "set" ); + createClassCastAssertion(sc, modelAssociation, "set"); } - sc.add( "this." + field.getName() + " = " + interfaceCast + field.getName() + ";" ); + sc.add("this." + field.getName() + " = " + interfaceCast + field.getName() + ";"); - if ( isOneMultiplicity && javaAssociationMetadata.isBidi() ) - { - sc.add( "" ); + if (isOneMultiplicity && javaAssociationMetadata.isBidi()) { + sc.add(""); - sc.add( "if ( " + field.getName() + " != null )" ); + sc.add("if ( " + field.getName() + " != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "this." + field.getName() + ".create" + modelAssociation.getModelClass().getName() - + "Association( this );" ); + sc.add("this." + field.getName() + ".create" + + modelAssociation.getModelClass().getName() + "Association( this );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - } - else - { - sc.add( "this." + field.getName() + " = " + field.getName() + ";" ); + } else { + sc.add("this." + field.getName() + " = " + field.getName() + ";"); } - if ( isBuilderMethod ) - { - sc.add( "return this;" ); + if (isBuilderMethod) { + sc.add("return this;"); } return setter; } - private void createClassCastAssertion( JSourceCode sc, ModelAssociation modelAssociation, String crudModifier ) - throws ModelloException - { + private void createClassCastAssertion(JSourceCode sc, ModelAssociation modelAssociation, String crudModifier) + throws ModelloException { JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); - if ( StringUtils.isEmpty( javaAssociationMetadata.getInterfaceName() ) ) - { + if (StringUtils.isEmpty(javaAssociationMetadata.getInterfaceName())) { return; // java.useInterface feature not used, no class cast assertion needed } - String propertyName = capitalise( modelAssociation.getName() ); + String propertyName = capitalise(modelAssociation.getName()); - JField field = createField( modelAssociation ); + JField field = createField(modelAssociation); String fieldName = field.getName(); - JType type = new JClass( modelAssociation.getTo() ); + JType type = new JClass(modelAssociation.getTo()); - if ( modelAssociation.isManyMultiplicity() ) - { - fieldName = uncapitalise( modelAssociation.getTo() ); + if (modelAssociation.isManyMultiplicity()) { + fieldName = uncapitalise(modelAssociation.getTo()); } String instanceName = type.getName(); @@ -1612,540 +1411,452 @@ private void createClassCastAssertion( JSourceCode sc, ModelAssociation modelAss // Add sane class cast exception message // When will sun ever fix this? - sc.add( "if ( " + fieldName + " != null && !( " + fieldName + " instanceof " + instanceName + " ) )" ); + sc.add("if ( " + fieldName + " != null && !( " + fieldName + " instanceof " + instanceName + " ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "throw new ClassCastException( \"" + modelAssociation.getModelClass().getName() + "." + crudModifier - + propertyName + "( " + fieldName + " ) parameter must be instanceof \" + " + instanceName - + ".class.getName() );" ); + sc.add("throw new ClassCastException( \"" + + modelAssociation.getModelClass().getName() + "." + crudModifier + + propertyName + "( " + fieldName + " ) parameter must be instanceof \" + " + instanceName + + ".class.getName() );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - private void createAssociation( JClass jClass, ModelAssociation modelAssociation, JSourceCode jConstructorSource ) - throws ModelloException - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelAssociation.getMetadata( JavaFieldMetadata.ID ); + private void createAssociation(JClass jClass, ModelAssociation modelAssociation, JSourceCode jConstructorSource) + throws ModelloException { + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelAssociation.getMetadata(JavaFieldMetadata.ID); - JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata( modelAssociation ); + JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata(modelAssociation); - boolean useJava5 = hasJavaSourceSupport( 5 ); + boolean useJava5 = hasJavaSourceSupport(5); - if ( modelAssociation.isManyMultiplicity() ) - { - JType componentType = getComponentType( modelAssociation, javaAssociationMetadata ); + if (modelAssociation.isManyMultiplicity()) { + JType componentType = getComponentType(modelAssociation, javaAssociationMetadata); - String defaultValue = getDefaultValue( modelAssociation, componentType ); + String defaultValue = getDefaultValue(modelAssociation, componentType); JType type; - if ( modelAssociation.isGenericType() ) - { - type = new JCollectionType( modelAssociation.getType(), componentType, useJava5 ); - } - else if ( ModelDefault.MAP.equals( modelAssociation.getType() ) ) - { - JMapType mapType = new JMapType( modelAssociation.getType(), defaultValue, componentType, useJava5 ); + if (modelAssociation.isGenericType()) { + type = new JCollectionType(modelAssociation.getType(), componentType, useJava5); + } else if (ModelDefault.MAP.equals(modelAssociation.getType())) { + JMapType mapType = new JMapType(modelAssociation.getType(), defaultValue, componentType, useJava5); defaultValue = mapType.getInstanceName(); type = mapType; - } - else - { - type = new JClass( modelAssociation.getType() ); + } else { + type = new JClass(modelAssociation.getType()); } - JField jField = new JField( type, modelAssociation.getName() ); + JField jField = new JField(type, modelAssociation.getName()); - if ( !isEmpty( modelAssociation.getComment() ) ) - { - jField.setComment( modelAssociation.getComment() ); + if (!isEmpty(modelAssociation.getComment())) { + jField.setComment(modelAssociation.getComment()); } - if ( useJava5 && !modelAssociation.getAnnotations().isEmpty() ) - { - for ( String annotation : modelAssociation.getAnnotations() ) - { - jField.appendAnnotation( annotation ); + if (useJava5 && !modelAssociation.getAnnotations().isEmpty()) { + for (String annotation : modelAssociation.getAnnotations()) { + jField.appendAnnotation(annotation); } } - if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(), - JavaAssociationMetadata.FIELD_INIT ) ) - { - jField.setInitString( defaultValue ); + if (StringUtils.equals( + javaAssociationMetadata.getInitializationMode(), JavaAssociationMetadata.FIELD_INIT)) { + jField.setInitString(defaultValue); } - if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(), - JavaAssociationMetadata.CONSTRUCTOR_INIT ) ) - { - jConstructorSource.add( "this." + jField.getName() + " = " + defaultValue + ";" ); + if (StringUtils.equals( + javaAssociationMetadata.getInitializationMode(), JavaAssociationMetadata.CONSTRUCTOR_INIT)) { + jConstructorSource.add("this." + jField.getName() + " = " + defaultValue + ";"); } - jClass.addField( jField ); + jClass.addField(jField); - if ( javaFieldMetadata.isGetter() ) - { - String propertyName = capitalise( jField.getName() ); + if (javaFieldMetadata.isGetter()) { + String propertyName = capitalise(jField.getName()); - JMethod getter = new JMethod( "get" + propertyName, jField.getType(), null ); + JMethod getter = new JMethod("get" + propertyName, jField.getType(), null); JSourceCode sc = getter.getSourceCode(); - if ( StringUtils.equals( javaAssociationMetadata.getInitializationMode(), - JavaAssociationMetadata.LAZY_INIT ) ) - { - sc.add( "if ( this." + jField.getName() + " == null )" ); + if (StringUtils.equals( + javaAssociationMetadata.getInitializationMode(), JavaAssociationMetadata.LAZY_INIT)) { + sc.add("if ( this." + jField.getName() + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "this." + jField.getName() + " = " + defaultValue + ";" ); + sc.add("this." + jField.getName() + " = " + defaultValue + ";"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); } - sc.add( "return this." + jField.getName() + ";" ); + sc.add("return this." + jField.getName() + ";"); - jClass.addMethod( getter ); + jClass.addMethod(getter); } - if ( javaFieldMetadata.isSetter() ) - { - jClass.addMethod( createSetter( jField, modelAssociation ) ); + if (javaFieldMetadata.isSetter()) { + jClass.addMethod(createSetter(jField, modelAssociation)); } - if ( javaAssociationMetadata.isAdder() ) - { - createAdder( modelAssociation, jClass ); + if (javaAssociationMetadata.isAdder()) { + createAdder(modelAssociation, jClass); } - } - else - { - createField( jClass, modelAssociation ); + } else { + createField(jClass, modelAssociation); } - if ( isBidirectionalAssociation( modelAssociation ) ) - { - if ( javaAssociationMetadata.isBidi() ) - { - createCreateAssociation( jClass, modelAssociation ); - createBreakAssociation( jClass, modelAssociation ); + if (isBidirectionalAssociation(modelAssociation)) { + if (javaAssociationMetadata.isBidi()) { + createCreateAssociation(jClass, modelAssociation); + createBreakAssociation(jClass, modelAssociation); } } } - private String getDefaultValue( ModelAssociation modelAssociation, JType componentType ) - { - String defaultValue = getDefaultValue( modelAssociation ); + private String getDefaultValue(ModelAssociation modelAssociation, JType componentType) { + String defaultValue = getDefaultValue(modelAssociation); - if ( modelAssociation.isGenericType() ) - { - ModelDefault modelDefault = getModel().getDefault( modelAssociation.getType() ); + if (modelAssociation.isGenericType()) { + ModelDefault modelDefault = getModel().getDefault(modelAssociation.getType()); - if ( hasJavaSourceSupport( 5 ) ) - { + if (hasJavaSourceSupport(5)) { + defaultValue = StringUtils.replace(modelDefault.getValue(), "", "<" + componentType.getName() + ">"); + } else { defaultValue = - StringUtils.replace( modelDefault.getValue(), "", "<" + componentType.getName() + ">" ); - } - else - { - defaultValue = - StringUtils.replace( modelDefault.getValue(), "", "/*<" + componentType.getName() + ">*/" ); + StringUtils.replace(modelDefault.getValue(), "", "/*<" + componentType.getName() + ">*/"); } } return defaultValue; } - private JavaAssociationMetadata getJavaAssociationMetadata( ModelAssociation modelAssociation ) - throws ModelloException - { + private JavaAssociationMetadata getJavaAssociationMetadata(ModelAssociation modelAssociation) + throws ModelloException { JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); - if ( !JavaAssociationMetadata.INIT_TYPES.contains( javaAssociationMetadata.getInitializationMode() ) ) - { - throw new ModelloException( - "The Java Modello Generator cannot use '" + javaAssociationMetadata.getInitializationMode() + if (!JavaAssociationMetadata.INIT_TYPES.contains(javaAssociationMetadata.getInitializationMode())) { + throw new ModelloException("The Java Modello Generator cannot use '" + + javaAssociationMetadata.getInitializationMode() + "' as a " - + "value, the only the following are acceptable " + JavaAssociationMetadata.INIT_TYPES ); + + "value, the only the following are acceptable " + JavaAssociationMetadata.INIT_TYPES); } return javaAssociationMetadata; } - private JType getComponentType( ModelAssociation modelAssociation, JavaAssociationMetadata javaAssociationMetadata ) - { + private JType getComponentType(ModelAssociation modelAssociation, JavaAssociationMetadata javaAssociationMetadata) { JType componentType; - if ( javaAssociationMetadata.getInterfaceName() != null ) - { - componentType = new JClass( javaAssociationMetadata.getInterfaceName() ); - } - else - { - componentType = new JClass( modelAssociation.getTo() ); + if (javaAssociationMetadata.getInterfaceName() != null) { + componentType = new JClass(javaAssociationMetadata.getInterfaceName()); + } else { + componentType = new JClass(modelAssociation.getTo()); } return componentType; } - private void createCreateAssociation( JClass jClass, ModelAssociation modelAssociation ) - { - JMethod createMethod = new JMethod( "create" + modelAssociation.getTo() + "Association" ); + private void createCreateAssociation(JClass jClass, ModelAssociation modelAssociation) { + JMethod createMethod = new JMethod("create" + modelAssociation.getTo() + "Association"); JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); createMethod.addParameter( - new JParameter( new JClass( modelAssociation.getTo() ), uncapitalise( modelAssociation.getTo() ) ) ); + new JParameter(new JClass(modelAssociation.getTo()), uncapitalise(modelAssociation.getTo()))); // TODO: remove after tested // createMethod.addException( new JClass( "Exception" ) ); JSourceCode sc = createMethod.getSourceCode(); - if ( modelAssociation.isOneMultiplicity() ) - { - if ( javaAssociationMetadata.isBidi() ) - { - sc.add( "if ( this." + modelAssociation.getName() + " != null )" ); + if (modelAssociation.isOneMultiplicity()) { + if (javaAssociationMetadata.isBidi()) { + sc.add("if ( this." + modelAssociation.getName() + " != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( - "break" + modelAssociation.getTo() + "Association( this." + modelAssociation.getName() + " );" ); + sc.add("break" + modelAssociation.getTo() + "Association( this." + modelAssociation.getName() + " );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); } - sc.add( "this." + modelAssociation.getName() + " = " + uncapitalise( modelAssociation.getTo() ) + ";" ); - } - else - { - jClass.addImport( "java.util.Collection" ); + sc.add("this." + modelAssociation.getName() + " = " + uncapitalise(modelAssociation.getTo()) + ";"); + } else { + jClass.addImport("java.util.Collection"); - sc.add( "Collection " + modelAssociation.getName() + " = get" + capitalise( modelAssociation.getName() ) - + "();" ); + sc.add("Collection " + modelAssociation.getName() + " = get" + capitalise(modelAssociation.getName()) + + "();"); - sc.add( "" ); + sc.add(""); - sc.add( "if ( " + modelAssociation.getName() + ".contains( " + uncapitalise( modelAssociation.getTo() ) - + " ) )" ); + sc.add("if ( " + modelAssociation.getName() + ".contains( " + uncapitalise(modelAssociation.getTo()) + + " ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() ) - + " is already assigned.\" );" ); + sc.add("throw new IllegalStateException( \"" + uncapitalise(modelAssociation.getTo()) + + " is already assigned.\" );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( modelAssociation.getName() + ".add( " + uncapitalise( modelAssociation.getTo() ) + " );" ); + sc.add(modelAssociation.getName() + ".add( " + uncapitalise(modelAssociation.getTo()) + " );"); } - jClass.addMethod( createMethod ); + jClass.addMethod(createMethod); } - private void createBreakAssociation( JClass jClass, ModelAssociation modelAssociation ) - { + private void createBreakAssociation(JClass jClass, ModelAssociation modelAssociation) { JSourceCode sc; - JMethod breakMethod = new JMethod( "break" + modelAssociation.getTo() + "Association" ); + JMethod breakMethod = new JMethod("break" + modelAssociation.getTo() + "Association"); breakMethod.addParameter( - new JParameter( new JClass( modelAssociation.getTo() ), uncapitalise( modelAssociation.getTo() ) ) ); + new JParameter(new JClass(modelAssociation.getTo()), uncapitalise(modelAssociation.getTo()))); // TODO: remove after tested // breakMethod.addException( new JClass( "Exception" ) ); sc = breakMethod.getSourceCode(); - if ( modelAssociation.isOneMultiplicity() ) - { - sc.add( - "if ( this." + modelAssociation.getName() + " != " + uncapitalise( modelAssociation.getTo() ) + " )" ); + if (modelAssociation.isOneMultiplicity()) { + sc.add("if ( this." + modelAssociation.getName() + " != " + uncapitalise(modelAssociation.getTo()) + " )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() ) - + " isn't associated.\" );" ); + sc.add("throw new IllegalStateException( \"" + uncapitalise(modelAssociation.getTo()) + + " isn't associated.\" );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( "this." + modelAssociation.getName() + " = null;" ); - } - else - { + sc.add("this." + modelAssociation.getName() + " = null;"); + } else { JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); String reference; - if ( JavaAssociationMetadata.LAZY_INIT.equals( javaAssociationMetadata.getInitializationMode() ) ) - { - reference = "get" + capitalise( modelAssociation.getName() ) + "()"; - } - else - { + if (JavaAssociationMetadata.LAZY_INIT.equals(javaAssociationMetadata.getInitializationMode())) { + reference = "get" + capitalise(modelAssociation.getName()) + "()"; + } else { reference = modelAssociation.getName(); } - sc.add( "if ( !" + reference + ".contains( " + uncapitalise( - modelAssociation.getTo() ) + " ) )" ); + sc.add("if ( !" + reference + ".contains( " + uncapitalise(modelAssociation.getTo()) + " ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "throw new IllegalStateException( \"" + uncapitalise( modelAssociation.getTo() ) - + " isn't associated.\" );" ); + sc.add("throw new IllegalStateException( \"" + uncapitalise(modelAssociation.getTo()) + + " isn't associated.\" );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( reference + ".remove( " + uncapitalise( modelAssociation.getTo() ) + " );" ); + sc.add(reference + ".remove( " + uncapitalise(modelAssociation.getTo()) + " );"); } - jClass.addMethod( breakMethod ); + jClass.addMethod(breakMethod); } - private void createAdder( ModelAssociation modelAssociation, JClass jClass ) - throws ModelloException - { - createAdder( modelAssociation, jClass, false ); + private void createAdder(ModelAssociation modelAssociation, JClass jClass) throws ModelloException { + createAdder(modelAssociation, jClass, false); } /* * since 1.8 */ - private void createAdder( ModelAssociation modelAssociation, JClass jClass, boolean isBuilderMethod ) - throws ModelloException - { + private void createAdder(ModelAssociation modelAssociation, JClass jClass, boolean isBuilderMethod) + throws ModelloException { String fieldName = modelAssociation.getName(); JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); - String parameterName = uncapitalise( modelAssociation.getTo() ); + String parameterName = uncapitalise(modelAssociation.getTo()); String implementationParameterName = parameterName; - boolean bidirectionalAssociation = isBidirectionalAssociation( modelAssociation ); + boolean bidirectionalAssociation = isBidirectionalAssociation(modelAssociation); JType addType; - if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) ) - { - addType = new JClass( javaAssociationMetadata.getInterfaceName() ); + if (StringUtils.isNotEmpty(javaAssociationMetadata.getInterfaceName())) { + addType = new JClass(javaAssociationMetadata.getInterfaceName()); implementationParameterName = "( (" + modelAssociation.getTo() + ") " + parameterName + " )"; - } - else if ( modelAssociation.getToClass() != null ) - { - addType = new JClass( modelAssociation.getToClass().getName() ); - } - else - { - addType = new JClass( "String" ); + } else if (modelAssociation.getToClass() != null) { + addType = new JClass(modelAssociation.getToClass().getName()); + } else { + addType = new JClass("String"); } - if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES ) || modelAssociation.getType().equals( - ModelDefault.MAP ) ) - { - String adderName = "add" + capitalise( singular( fieldName ) ); + if (modelAssociation.getType().equals(ModelDefault.PROPERTIES) + || modelAssociation.getType().equals(ModelDefault.MAP)) { + String adderName = "add" + capitalise(singular(fieldName)); JMethod adder; - if ( isBuilderMethod ) - { - adder = new JMethod( adderName, new JClass( "Builder" ), "this builder instance" ); - } - else - { - adder = new JMethod( adderName ); + if (isBuilderMethod) { + adder = new JMethod(adderName, new JClass("Builder"), "this builder instance"); + } else { + adder = new JMethod(adderName); } - if ( modelAssociation.getType().equals( ModelDefault.MAP ) ) - { - adder.addParameter( new JParameter( new JClass( "Object" ), "key" ) ); - } - else - { - adder.addParameter( new JParameter( new JClass( "String" ), "key" ) ); + if (modelAssociation.getType().equals(ModelDefault.MAP)) { + adder.addParameter(new JParameter(new JClass("Object"), "key")); + } else { + adder.addParameter(new JParameter(new JClass("String"), "key")); } - adder.addParameter( new JParameter( new JClass( modelAssociation.getTo() ), "value" ) ); + adder.addParameter(new JParameter(new JClass(modelAssociation.getTo()), "value")); StringBuilder adderCode = new StringBuilder(); - if ( JavaAssociationMetadata.LAZY_INIT.equals( javaAssociationMetadata.getInitializationMode() ) - && !isBuilderMethod ) - { - adderCode.append( "get" ).append( capitalise( fieldName ) ).append( "()" ); - } - else - { - adderCode.append( fieldName ); + if (JavaAssociationMetadata.LAZY_INIT.equals(javaAssociationMetadata.getInitializationMode()) + && !isBuilderMethod) { + adderCode.append("get").append(capitalise(fieldName)).append("()"); + } else { + adderCode.append(fieldName); } - adderCode.append( ".put( key, value );" ); + adderCode.append(".put( key, value );"); - adder.getSourceCode().add( adderCode.toString() ); + adder.getSourceCode().add(adderCode.toString()); - if ( isBuilderMethod ) - { - adder.getSourceCode().add( "return this;" ); + if (isBuilderMethod) { + adder.getSourceCode().add("return this;"); } - jClass.addMethod( adder ); - } - else - { - String adderName = "add" + singular( capitalise( singular( fieldName ) ) ); + jClass.addMethod(adder); + } else { + String adderName = "add" + singular(capitalise(singular(fieldName))); JMethod adder; - if ( isBuilderMethod ) - { - adder = new JMethod( adderName, new JClass( "Builder" ), "this builder instance" ); - } - else - { - adder = new JMethod( adderName ); + if (isBuilderMethod) { + adder = new JMethod(adderName, new JClass("Builder"), "this builder instance"); + } else { + adder = new JMethod(adderName); } - adder.addParameter( new JParameter( addType, parameterName ) ); + adder.addParameter(new JParameter(addType, parameterName)); - createClassCastAssertion( adder.getSourceCode(), modelAssociation, "add" ); + createClassCastAssertion(adder.getSourceCode(), modelAssociation, "add"); StringBuilder adderCode = new StringBuilder(); - if ( JavaAssociationMetadata.LAZY_INIT.equals( javaAssociationMetadata.getInitializationMode() ) - && !isBuilderMethod ) - { - adderCode.append( "get" ).append( capitalise( fieldName ) ).append( "()" ); - } - else - { - adderCode.append( fieldName ); + if (JavaAssociationMetadata.LAZY_INIT.equals(javaAssociationMetadata.getInitializationMode()) + && !isBuilderMethod) { + adderCode.append("get").append(capitalise(fieldName)).append("()"); + } else { + adderCode.append(fieldName); } - adderCode.append( ".add( " ) - .append( implementationParameterName ) - .append( " );" ); + adderCode.append(".add( ").append(implementationParameterName).append(" );"); - adder.getSourceCode().add( adderCode.toString() ); + adder.getSourceCode().add(adderCode.toString()); - if ( bidirectionalAssociation && javaAssociationMetadata.isBidi() && !isBuilderMethod ) - { + if (bidirectionalAssociation && javaAssociationMetadata.isBidi() && !isBuilderMethod) { // TODO: remove after tested // adder.addException( new JClass( "Exception" ) ); - adder.getSourceCode().add( - implementationParameterName + ".create" + modelAssociation.getModelClass().getName() - + "Association( this );" ); + adder.getSourceCode() + .add(implementationParameterName + ".create" + + modelAssociation.getModelClass().getName() + "Association( this );"); } - if ( isBuilderMethod ) - { - adder.getSourceCode().add( "return this;" ); + if (isBuilderMethod) { + adder.getSourceCode().add("return this;"); } - jClass.addMethod( adder ); + jClass.addMethod(adder); // don't add the remover in the inner Builder class - if ( isBuilderMethod ) - { + if (isBuilderMethod) { return; } - JMethod remover = new JMethod( "remove" + singular( capitalise( fieldName ) ) ); + JMethod remover = new JMethod("remove" + singular(capitalise(fieldName))); - remover.addParameter( new JParameter( addType, parameterName ) ); + remover.addParameter(new JParameter(addType, parameterName)); - createClassCastAssertion( remover.getSourceCode(), modelAssociation, "remove" ); + createClassCastAssertion(remover.getSourceCode(), modelAssociation, "remove"); - if ( bidirectionalAssociation && javaAssociationMetadata.isBidi() ) - { + if (bidirectionalAssociation && javaAssociationMetadata.isBidi()) { // TODO: remove after tested // remover.addException( new JClass( "Exception" ) ); - remover.getSourceCode().add( - parameterName + ".break" + modelAssociation.getModelClass().getName() + "Association( this );" ); + remover.getSourceCode() + .add(parameterName + ".break" + + modelAssociation.getModelClass().getName() + "Association( this );"); } String reference; - if ( JavaAssociationMetadata.LAZY_INIT.equals( javaAssociationMetadata.getInitializationMode() ) ) - { - reference = "get" + capitalise( fieldName ) + "()"; - } - else - { + if (JavaAssociationMetadata.LAZY_INIT.equals(javaAssociationMetadata.getInitializationMode())) { + reference = "get" + capitalise(fieldName) + "()"; + } else { reference = fieldName; } - remover.getSourceCode().add( reference + ".remove( " + implementationParameterName + " );" ); + remover.getSourceCode().add(reference + ".remove( " + implementationParameterName + " );"); - jClass.addMethod( remover ); + jClass.addMethod(remover); } } - private boolean isBidirectionalAssociation( ModelAssociation association ) - { + private boolean isBidirectionalAssociation(ModelAssociation association) { Model model = association.getModelClass().getModel(); - if ( !isClassInModel( association.getTo(), model ) ) - { + if (!isClassInModel(association.getTo(), model)) { return false; } ModelClass toClass = association.getToClass(); - for ( ModelField modelField : toClass.getFields( getGeneratedVersion() ) ) - { - if ( !( modelField instanceof ModelAssociation ) ) - { + for (ModelField modelField : toClass.getFields(getGeneratedVersion())) { + if (!(modelField instanceof ModelAssociation)) { continue; } ModelAssociation modelAssociation = (ModelAssociation) modelField; - if ( association == modelAssociation ) - { + if (association == modelAssociation) { continue; } - if ( !isClassInModel( modelAssociation.getTo(), model ) ) - { + if (!isClassInModel(modelAssociation.getTo(), model)) { continue; } ModelClass totoClass = modelAssociation.getToClass(); - if ( association.getModelClass().equals( totoClass ) ) - { + if (association.getModelClass().equals(totoClass)) { return true; } } @@ -2153,41 +1864,32 @@ private boolean isBidirectionalAssociation( ModelAssociation association ) return false; } - private JType getDesiredType( ModelField modelField, boolean useTo ) - throws ModelloException - { - JField field = createField( modelField ); + private JType getDesiredType(ModelField modelField, boolean useTo) throws ModelloException { + JField field = createField(modelField); JType type = field.getType(); - if ( modelField instanceof ModelAssociation ) - { + if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; JavaAssociationMetadata javaAssociationMetadata = - (JavaAssociationMetadata) modelAssociation.getAssociationMetadata( JavaAssociationMetadata.ID ); + (JavaAssociationMetadata) modelAssociation.getAssociationMetadata(JavaAssociationMetadata.ID); - if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) - && !modelAssociation.isManyMultiplicity() ) - { - type = new JClass( javaAssociationMetadata.getInterfaceName() ); - } - else if ( modelAssociation.isManyMultiplicity() && modelAssociation.isGenericType() ) - { - JType componentType = getComponentType( modelAssociation, javaAssociationMetadata ); - type = new JCollectionType( modelAssociation.getType(), componentType,hasJavaSourceSupport( 5 ) ); - } - else if ( useTo ) - { - type = new JClass( modelAssociation.getTo() ); + if (StringUtils.isNotEmpty(javaAssociationMetadata.getInterfaceName()) + && !modelAssociation.isManyMultiplicity()) { + type = new JClass(javaAssociationMetadata.getInterfaceName()); + } else if (modelAssociation.isManyMultiplicity() && modelAssociation.isGenericType()) { + JType componentType = getComponentType(modelAssociation, javaAssociationMetadata); + type = new JCollectionType(modelAssociation.getType(), componentType, hasJavaSourceSupport(5)); + } else if (useTo) { + type = new JClass(modelAssociation.getTo()); } } return type; } - private void addParameter( JMethodSignature jMethod, String type, String name, String comment ) - { - jMethod.addParameter( new JParameter( new JType( type ), name ) ); - jMethod.getJDocComment().getParamDescriptor( name ).setDescription( comment ); + private void addParameter(JMethodSignature jMethod, String type, String name, String comment) { + jMethod.addParameter(new JParameter(new JType(type), name)); + jMethod.getJDocComment().getParamDescriptor(name).setDescription(comment); } // ---------------------------------------------------------------------- @@ -2195,262 +1897,211 @@ private void addParameter( JMethodSignature jMethod, String type, String name, S // since 1.8 // ---------------------------------------------------------------------- - private void generateBuilder( ModelClass modelClass, JClass builderClass, JConstructor outherClassConstructor ) - throws ModelloException - { - builderClass.getModifiers().setStatic( true ); - builderClass.getModifiers().setFinal( true ); + private void generateBuilder(ModelClass modelClass, JClass builderClass, JConstructor outherClassConstructor) + throws ModelloException { + builderClass.getModifiers().setStatic(true); + builderClass.getModifiers().setFinal(true); ModelClass reference = modelClass; // traverse the whole modelClass hierarchy to create the nested Builder - while ( reference != null ) - { + while (reference != null) { // create builder setters methods - for ( ModelField modelField : reference.getFields( getGeneratedVersion() ) ) - { - if ( modelField instanceof ModelAssociation ) - { - createBuilderAssociation( builderClass, (ModelAssociation) modelField ); - } - else - { - createBuilderField( builderClass, modelField ); + for (ModelField modelField : reference.getFields(getGeneratedVersion())) { + if (modelField instanceof ModelAssociation) { + createBuilderAssociation(builderClass, (ModelAssociation) modelField); + } else { + createBuilderField(builderClass, modelField); } } - if ( reference.hasSuperClass() ) - { - reference = reference.getModel().getClass( reference.getSuperClass(), getGeneratedVersion() ); - } - else - { + if (reference.hasSuperClass()) { + reference = reference.getModel().getClass(reference.getSuperClass(), getGeneratedVersion()); + } else { reference = null; } } // create and add the Model#build() method - JMethod build = new JMethod( "build", new JClass( modelClass.getName() ), "A new " - + modelClass.getName() - + " instance" ); - build.getJDocComment().setComment( "Creates a new " - + modelClass.getName() - + " instance." ); + JMethod build = new JMethod( + "build", new JClass(modelClass.getName()), "A new " + modelClass.getName() + " instance"); + build.getJDocComment().setComment("Creates a new " + modelClass.getName() + " instance."); JSourceCode sc = build.getSourceCode(); - createInstanceAndSetProperties( modelClass, outherClassConstructor, sc ); + createInstanceAndSetProperties(modelClass, outherClassConstructor, sc); - builderClass.addMethod( build ); + builderClass.addMethod(build); } - private void createInstanceAndSetProperties( ModelClass modelClass, JConstructor constructor, JSourceCode sc ) - throws ModelloException - { + private void createInstanceAndSetProperties(ModelClass modelClass, JConstructor constructor, JSourceCode sc) + throws ModelloException { final Set ctorArgs = new HashSet(); - StringBuilder ctor = new StringBuilder( modelClass.getName() ) - .append( " instance = new " ) - .append( modelClass.getName() ) - .append( '(' ); + StringBuilder ctor = new StringBuilder(modelClass.getName()) + .append(" instance = new ") + .append(modelClass.getName()) + .append('('); // understand if default empty ctor can be used or if it requires parameters - if ( constructor != null ) - { + if (constructor != null) { JParameter[] parameters = constructor.getParameters(); - for ( int i = 0; i < parameters.length; i++ ) - { - if ( i > 0 ) - { - ctor.append( ',' ); + for (int i = 0; i < parameters.length; i++) { + if (i > 0) { + ctor.append(','); } JParameter parameter = parameters[i]; - ctor.append( ' ' ) - .append( parameter.getName() ) - .append( ' ' ); + ctor.append(' ').append(parameter.getName()).append(' '); - ctorArgs.add( parameter.getName() ); + ctorArgs.add(parameter.getName()); } } - ctor.append( ");" ); + ctor.append(");"); - sc.add( ctor.toString() ); + sc.add(ctor.toString()); ModelClass reference = modelClass; // traverse the whole modelClass hierarchy to create the nested Builder instance - while ( reference != null ) - { + while (reference != null) { // collect parameters and set them in the instance object - for ( ModelField modelField : reference.getFields( getGeneratedVersion() ) ) - { - if ( modelField instanceof ModelAssociation ) - { + for (ModelField modelField : reference.getFields(getGeneratedVersion())) { + if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID ); - JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata( modelAssociation ); - - if ( modelAssociation.isManyMultiplicity() - && !javaFieldMetadata.isGetter() - && !javaFieldMetadata.isSetter() - && !javaAssociationMetadata.isAdder() ) - { - throw new ModelloException( "Exception while generating Java, Model inconsistency found: impossible to generate '" - + modelClass.getName() - + ".Builder#build()' method, '" - + modelClass.getName() - + "." - + modelAssociation.getName() - + "' field (" - + modelAssociation.getType() - + ") cannot be set, no getter/setter/adder method available." ); + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) modelField.getMetadata(JavaFieldMetadata.ID); + JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata(modelAssociation); + + if (modelAssociation.isManyMultiplicity() + && !javaFieldMetadata.isGetter() + && !javaFieldMetadata.isSetter() + && !javaAssociationMetadata.isAdder()) { + throw new ModelloException( + "Exception while generating Java, Model inconsistency found: impossible to generate '" + + modelClass.getName() + + ".Builder#build()' method, '" + + modelClass.getName() + + "." + + modelAssociation.getName() + + "' field (" + + modelAssociation.getType() + + ") cannot be set, no getter/setter/adder method available."); } - createSetBuilderAssociationToInstance( ctorArgs, modelAssociation, sc ); - } - else - { - createSetBuilderFieldToInstance( ctorArgs, modelField, sc ); + createSetBuilderAssociationToInstance(ctorArgs, modelAssociation, sc); + } else { + createSetBuilderFieldToInstance(ctorArgs, modelField, sc); } } - if ( reference.hasSuperClass() ) - { - reference = reference.getModel().getClass( reference.getSuperClass(), getGeneratedVersion() ); - } - else - { + if (reference.hasSuperClass()) { + reference = reference.getModel().getClass(reference.getSuperClass(), getGeneratedVersion()); + } else { reference = null; } } - sc.add( "return instance;" ); + sc.add("return instance;"); } - private void createBuilderField( JClass jClass, ModelField modelField ) - throws ModelloException - { - JField field = createField( modelField ); + private void createBuilderField(JClass jClass, ModelField modelField) throws ModelloException { + JField field = createField(modelField); - jClass.addField( field ); + jClass.addField(field); - jClass.addMethod( createSetter( field, modelField, true ) ); + jClass.addMethod(createSetter(field, modelField, true)); } - private boolean createSetBuilderFieldToInstance( Set ctorArgs, ModelField modelField, JSourceCode sc ) - throws ModelloException - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata( JavaFieldMetadata.ID ); + private boolean createSetBuilderFieldToInstance(Set ctorArgs, ModelField modelField, JSourceCode sc) + throws ModelloException { + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelField.getMetadata(JavaFieldMetadata.ID); // if it is not already set by the ctor and if the setter method is available - if ( !ctorArgs.contains( modelField.getName() ) && javaFieldMetadata.isSetter() ) - { - sc.add( "instance.set" - + capitalise( modelField.getName() ) - + "( " - + modelField.getName() - + " );" ); + if (!ctorArgs.contains(modelField.getName()) && javaFieldMetadata.isSetter()) { + sc.add("instance.set" + capitalise(modelField.getName()) + "( " + modelField.getName() + " );"); return true; } return false; } - private void createBuilderAssociation( JClass jClass, ModelAssociation modelAssociation ) - throws ModelloException - { - JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata( modelAssociation ); + private void createBuilderAssociation(JClass jClass, ModelAssociation modelAssociation) throws ModelloException { + JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata(modelAssociation); - if ( modelAssociation.isManyMultiplicity() ) - { - JType componentType = getComponentType( modelAssociation, javaAssociationMetadata ); - boolean useJava5 = hasJavaSourceSupport( 5 ); + if (modelAssociation.isManyMultiplicity()) { + JType componentType = getComponentType(modelAssociation, javaAssociationMetadata); + boolean useJava5 = hasJavaSourceSupport(5); - String defaultValue = getDefaultValue( modelAssociation, componentType ); + String defaultValue = getDefaultValue(modelAssociation, componentType); JType type; - if ( modelAssociation.isGenericType() ) - { - type = new JCollectionType( modelAssociation.getType(), componentType, useJava5 ); - } - else if ( ModelDefault.MAP.equals( modelAssociation.getType() ) ) - { - JMapType mapType = new JMapType( modelAssociation.getType(), defaultValue, componentType, useJava5 ); + if (modelAssociation.isGenericType()) { + type = new JCollectionType(modelAssociation.getType(), componentType, useJava5); + } else if (ModelDefault.MAP.equals(modelAssociation.getType())) { + JMapType mapType = new JMapType(modelAssociation.getType(), defaultValue, componentType, useJava5); defaultValue = mapType.getInstanceName(); type = mapType; - } - else - { - type = new JClass( modelAssociation.getType() ); + } else { + type = new JClass(modelAssociation.getType()); } - JField jField = new JField( type, modelAssociation.getName() ); - jField.getModifiers().setFinal( true ); + JField jField = new JField(type, modelAssociation.getName()); + jField.getModifiers().setFinal(true); - if ( !isEmpty( modelAssociation.getComment() ) ) - { - jField.setComment( modelAssociation.getComment() ); + if (!isEmpty(modelAssociation.getComment())) { + jField.setComment(modelAssociation.getComment()); } - if ( useJava5 && !modelAssociation.getAnnotations().isEmpty() ) - { - for ( String annotation : modelAssociation.getAnnotations() ) - { - jField.appendAnnotation( annotation ); + if (useJava5 && !modelAssociation.getAnnotations().isEmpty()) { + for (String annotation : modelAssociation.getAnnotations()) { + jField.appendAnnotation(annotation); } } - jField.setInitString( defaultValue ); + jField.setInitString(defaultValue); - jClass.addField( jField ); + jClass.addField(jField); - createAdder( modelAssociation, jClass, true ); - } - else - { - createBuilderField( jClass, modelAssociation ); + createAdder(modelAssociation, jClass, true); + } else { + createBuilderField(jClass, modelAssociation); } } - private void createSetBuilderAssociationToInstance( Set ctorArgs, ModelAssociation modelAssociation, JSourceCode sc ) - throws ModelloException - { - if ( modelAssociation.isManyMultiplicity() ) - { + private void createSetBuilderAssociationToInstance( + Set ctorArgs, ModelAssociation modelAssociation, JSourceCode sc) throws ModelloException { + if (modelAssociation.isManyMultiplicity()) { // Map/Properties don't have bidi association, they can be directly set - if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES ) - || modelAssociation.getType().equals( ModelDefault.MAP ) ) - { - if ( createSetBuilderFieldToInstance( ctorArgs, modelAssociation, sc ) ) - { + if (modelAssociation.getType().equals(ModelDefault.PROPERTIES) + || modelAssociation.getType().equals(ModelDefault.MAP)) { + if (createSetBuilderFieldToInstance(ctorArgs, modelAssociation, sc)) { return; } } // check if there's no bidi association, so - JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata( modelAssociation ); + JavaAssociationMetadata javaAssociationMetadata = getJavaAssociationMetadata(modelAssociation); - boolean bidirectionalAssociation = isBidirectionalAssociation( modelAssociation ); + boolean bidirectionalAssociation = isBidirectionalAssociation(modelAssociation); - if ( !bidirectionalAssociation || !javaAssociationMetadata.isBidi() ) - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) modelAssociation.getMetadata( JavaFieldMetadata.ID ); + if (!bidirectionalAssociation || !javaAssociationMetadata.isBidi()) { + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) modelAssociation.getMetadata(JavaFieldMetadata.ID); // just use the plain old setter - if ( createSetBuilderFieldToInstance( ctorArgs, modelAssociation, sc ) ) - { + if (createSetBuilderFieldToInstance(ctorArgs, modelAssociation, sc)) { return; } // or we can try to set by using the addAll if there is a getter available - else if ( javaFieldMetadata.isGetter() ) - { - String action = isMap( modelAssociation.getType() ) ? "put" : "add"; + else if (javaFieldMetadata.isGetter()) { + String action = isMap(modelAssociation.getType()) ? "put" : "add"; - sc.add( "instance.get" + capitalise( modelAssociation.getName() ) + "()." + action + "All( " + modelAssociation.getName() + " );" ); + sc.add("instance.get" + capitalise(modelAssociation.getName()) + "()." + action + "All( " + + modelAssociation.getName() + " );"); return; } } @@ -2463,204 +2114,167 @@ else if ( javaFieldMetadata.isGetter() ) String itemType; String targetField = modelAssociation.getName(); - boolean useJava5 = hasJavaSourceSupport( 5 ); + boolean useJava5 = hasJavaSourceSupport(5); - if ( StringUtils.isNotEmpty( javaAssociationMetadata.getInterfaceName() ) ) - { + if (StringUtils.isNotEmpty(javaAssociationMetadata.getInterfaceName())) { itemType = javaAssociationMetadata.getInterfaceName(); - } - else if ( modelAssociation.getToClass() != null ) - { + } else if (modelAssociation.getToClass() != null) { itemType = modelAssociation.getToClass().getName(); - } - else if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES ) - || modelAssociation.getType().equals( ModelDefault.MAP ) ) - { - StringBuilder itemTypeBuilder = new StringBuilder( "java.util.Map.Entry" ); + } else if (modelAssociation.getType().equals(ModelDefault.PROPERTIES) + || modelAssociation.getType().equals(ModelDefault.MAP)) { + StringBuilder itemTypeBuilder = new StringBuilder("java.util.Map.Entry"); - if ( useJava5 ) - { - itemTypeBuilder.append( '<' ); + if (useJava5) { + itemTypeBuilder.append('<'); - if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES ) ) - { - itemTypeBuilder.append( "Object, Object" ); - } - else - { - itemTypeBuilder.append( "String, " ).append( modelAssociation.getTo() ); + if (modelAssociation.getType().equals(ModelDefault.PROPERTIES)) { + itemTypeBuilder.append("Object, Object"); + } else { + itemTypeBuilder.append("String, ").append(modelAssociation.getTo()); } - itemTypeBuilder.append( '>' ); + itemTypeBuilder.append('>'); } itemType = itemTypeBuilder.toString(); targetField += ".entrySet()"; - } - else - { + } else { itemType = "String"; } - if ( useJava5 ) - { - sc.add( "for ( " + itemType + " item : " + targetField + " )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + targetField + ".iterator(); it.hasNext(); )" ); + if (useJava5) { + sc.add("for ( " + itemType + " item : " + targetField + " )"); + } else { + sc.add("for ( java.util.Iterator it = " + targetField + ".iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( !useJava5 ) - { - sc.add( itemType + " item = (" + itemType + ") it.next();" ); + if (!useJava5) { + sc.add(itemType + " item = (" + itemType + ") it.next();"); } - StringBuilder adder = new StringBuilder( "instance.add" ) - .append( capitalise( singular( modelAssociation.getName() ) ) ) - .append( "( " ); + StringBuilder adder = new StringBuilder("instance.add") + .append(capitalise(singular(modelAssociation.getName()))) + .append("( "); - if ( modelAssociation.getType().equals( ModelDefault.PROPERTIES ) - || modelAssociation.getType().equals( ModelDefault.MAP ) ) - { - appendEntryMethod( "String", "getKey()", adder, modelAssociation ); - adder.append( ", " ); - appendEntryMethod( modelAssociation.getTo(), "getValue()", adder, modelAssociation ); - } - else - { - adder.append( "item" ); + if (modelAssociation.getType().equals(ModelDefault.PROPERTIES) + || modelAssociation.getType().equals(ModelDefault.MAP)) { + appendEntryMethod("String", "getKey()", adder, modelAssociation); + adder.append(", "); + appendEntryMethod(modelAssociation.getTo(), "getValue()", adder, modelAssociation); + } else { + adder.append("item"); } - adder.append( " );" ); + adder.append(" );"); - sc.add( adder.toString() ); + sc.add(adder.toString()); sc.unindent(); - sc.add( "}" ); - } - else - { - createSetBuilderFieldToInstance( ctorArgs, modelAssociation, sc ); + sc.add("}"); + } else { + createSetBuilderFieldToInstance(ctorArgs, modelAssociation, sc); } } - private void appendEntryMethod( String type, String method, StringBuilder target, ModelAssociation modelAssociation ) - { - if ( !hasJavaSourceSupport( 5 ) || modelAssociation.getType().equals( ModelDefault.PROPERTIES ) ) - { - target.append( '(' ).append( type ).append( ") " ); + private void appendEntryMethod( + String type, String method, StringBuilder target, ModelAssociation modelAssociation) { + if (!hasJavaSourceSupport(5) || modelAssociation.getType().equals(ModelDefault.PROPERTIES)) { + target.append('(').append(type).append(") "); } - target.append( "item." ).append( method ); + target.append("item.").append(method); } - private void generateStaticCreator( ModelClass modelClass, JClass jClass, JConstructor constructor ) - throws ModelloException - { - JMethod creatorMethod = new JMethod( "new" + modelClass.getName() + "Instance", - new JClass( modelClass.getName() ), - "a new " + modelClass.getName() + " instance." ); - creatorMethod.getModifiers().setStatic( true ); - creatorMethod.getJDocComment().setComment( "Creates a new " + modelClass.getName() + " instance." ); + private void generateStaticCreator(ModelClass modelClass, JClass jClass, JConstructor constructor) + throws ModelloException { + JMethod creatorMethod = new JMethod( + "new" + modelClass.getName() + "Instance", + new JClass(modelClass.getName()), + "a new " + modelClass.getName() + " instance."); + creatorMethod.getModifiers().setStatic(true); + creatorMethod.getJDocComment().setComment("Creates a new " + modelClass.getName() + " instance."); ModelClass reference = modelClass; boolean hasDefaults = false; // traverse the whole modelClass hierarchy to create the static creator method - while ( reference != null ) - { - for ( ModelField modelField : reference.getFields( getGeneratedVersion() ) ) - { + while (reference != null) { + for (ModelField modelField : reference.getFields(getGeneratedVersion())) { // this is hacky - JField field = createField( modelField ); - creatorMethod.addParameter( new JParameter( field.getType(), field.getName() ) ); + JField field = createField(modelField); + creatorMethod.addParameter(new JParameter(field.getType(), field.getName())); - if ( !StringUtils.isEmpty( modelField.getDefaultValue() ) ) - { + if (!StringUtils.isEmpty(modelField.getDefaultValue())) { hasDefaults = true; } } - if ( reference.hasSuperClass() ) - { - reference = reference.getModel().getClass( reference.getSuperClass(), getGeneratedVersion() ); - } - else - { + if (reference.hasSuperClass()) { + reference = reference.getModel().getClass(reference.getSuperClass(), getGeneratedVersion()); + } else { reference = null; } } JSourceCode sc = creatorMethod.getSourceCode(); - createInstanceAndSetProperties( modelClass, constructor, sc ); + createInstanceAndSetProperties(modelClass, constructor, sc); - jClass.addMethod( creatorMethod ); + jClass.addMethod(creatorMethod); // creates a shortcut with default values only if necessary - if ( !hasDefaults ) - { + if (!hasDefaults) { return; } - creatorMethod = new JMethod( "new" + modelClass.getName() + "Instance", - new JClass( modelClass.getName() ), - "a new " + modelClass.getName() + " instance." ); - creatorMethod.getModifiers().setStatic( true ); - creatorMethod.getJDocComment().setComment( "Creates a new " + modelClass.getName() + " instance." ); + creatorMethod = new JMethod( + "new" + modelClass.getName() + "Instance", + new JClass(modelClass.getName()), + "a new " + modelClass.getName() + " instance."); + creatorMethod.getModifiers().setStatic(true); + creatorMethod.getJDocComment().setComment("Creates a new " + modelClass.getName() + " instance."); StringBuilder shortcutArgs = new StringBuilder(); reference = modelClass; - while ( reference != null ) - { - for ( ModelField modelField : reference.getFields( getGeneratedVersion() ) ) - { - if ( shortcutArgs.length() > 0 ) - { - shortcutArgs.append( ',' ); + while (reference != null) { + for (ModelField modelField : reference.getFields(getGeneratedVersion())) { + if (shortcutArgs.length() > 0) { + shortcutArgs.append(','); } - shortcutArgs.append( ' ' ); + shortcutArgs.append(' '); - if ( StringUtils.isEmpty( modelField.getDefaultValue() ) ) - { + if (StringUtils.isEmpty(modelField.getDefaultValue())) { // this is hacky - JField field = createField( modelField ); - creatorMethod.addParameter( new JParameter( field.getType(), field.getName() ) ); + JField field = createField(modelField); + creatorMethod.addParameter(new JParameter(field.getType(), field.getName())); - shortcutArgs.append( modelField.getName() ); - } - else - { - shortcutArgs.append( getJavaDefaultValue( modelField ) ); + shortcutArgs.append(modelField.getName()); + } else { + shortcutArgs.append(getJavaDefaultValue(modelField)); } - shortcutArgs.append( ' ' ); + shortcutArgs.append(' '); } - if ( reference.hasSuperClass() ) - { - reference = reference.getModel().getClass( reference.getSuperClass(), getGeneratedVersion() ); - } - else - { + if (reference.hasSuperClass()) { + reference = reference.getModel().getClass(reference.getSuperClass(), getGeneratedVersion()); + } else { reference = null; } } sc = creatorMethod.getSourceCode(); - sc.add( "return new" + modelClass.getName() + "Instance(" + shortcutArgs + ");" ); + sc.add("return new" + modelClass.getName() + "Instance(" + shortcutArgs + ");"); - jClass.addMethod( creatorMethod ); + jClass.addMethod(creatorMethod); } - } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JAnnotations.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JAnnotations.java index 224b07b7f..f6efa05a1 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JAnnotations.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JAnnotations.java @@ -4,48 +4,40 @@ import java.util.Iterator; import java.util.List; -public class JAnnotations -{ +public class JAnnotations { private List annotations; - public JAnnotations() - { + public JAnnotations() { this.annotations = new ArrayList(); } - public void appendAnnotation( String annotation ) - { - annotations.add( annotation ); + public void appendAnnotation(String annotation) { + annotations.add(annotation); } /** * Returns the String representation of this JAnnotations * @return the String representation of this JAnnotations **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - for ( Iterator iterator = annotations.iterator(); iterator.hasNext(); ) - { - sb.append( iterator.next() ); - if ( iterator.hasNext() ) - { - sb.append( ' ' ); + for (Iterator iterator = annotations.iterator(); iterator.hasNext(); ) { + sb.append(iterator.next()); + if (iterator.hasNext()) { + sb.append(' '); } } return sb.toString(); - } //-- toString + } // -- toString /** * prints this Annotations using the given JSourceWriter * * @param jsw the JSourceWriter to print to */ - public void print( JSourceWriter jsw ) - { - for ( String annotation : annotations ) - { - jsw.writeln( annotation.toString() ); + public void print(JSourceWriter jsw) { + for (String annotation : annotations) { + jsw.writeln(annotation.toString()); } } // -- print } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JArrayType.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JArrayType.java index d8812e8d5..5069fef62 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JArrayType.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JArrayType.java @@ -22,9 +22,7 @@ * @version $Revision$ $Date$ * @since 1.0.4 */ -public final class JArrayType - extends JComponentizedType -{ +public final class JArrayType extends JComponentizedType { // -------------------------------------------------------------------------- /** @@ -33,9 +31,8 @@ public final class JArrayType * @param componentType Component type. * @param useJava50 True if Java 5.0 should be generated. */ - public JArrayType( final JType componentType, final boolean useJava50 ) - { - super( componentType.getName(), componentType, useJava50 ); + public JArrayType(final JType componentType, final boolean useJava50) { + super(componentType.getName(), componentType, useJava50); } // -------------------------------------------------------------------------- @@ -45,8 +42,7 @@ public JArrayType( final JType componentType, final boolean useJava50 ) * * @return The String representation of this JType. */ - public String toString() - { + public String toString() { return getComponentType().toString() + "[]"; } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JClass.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JClass.java index 3de933976..da2f8bd5a 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JClass.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JClass.java @@ -49,7 +49,6 @@ * and revised to extend JStructure * */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -90,22 +89,18 @@ * @author Martin Skopp * @version $Revision$ $Date$ */ -public class JClass extends JStructure -{ - +public class JClass extends JStructure { /** * The list of constructors for this JClass */ private List _constructors = null; - /** * The list of member variables (fields) of this JClass */ private Map _fields = null; - private List _innerClasses = null; /** @@ -118,7 +113,6 @@ public class JClass extends JStructure */ private String _superClass = null; - /** * The source code for static initialization **/ @@ -130,19 +124,15 @@ public class JClass extends JStructure * @exception java.lang.IllegalArgumentException when the given name * is not a valid Class name **/ - public JClass( String name ) - throws IllegalArgumentException - { - super( name ); + public JClass(String name) throws IllegalArgumentException { + super(name); _constructors = new ArrayList(); _fields = new LinkedHashMap<>(); _methods = new ArrayList(); _innerClasses = new ArrayList(); - //-- initialize default Java doc - getJDocComment().appendComment( "Class " + getLocalName() + "." ); - - } //-- JClass - + // -- initialize default Java doc + getJDocComment().appendComment("Class " + getLocalName() + "."); + } // -- JClass /** * Adds the given Constructor to this classes list of constructors. @@ -152,26 +142,19 @@ public JClass( String name ) * @param constructor a constructor * @throws java.lang.IllegalArgumentException if {@code constructor} is {@code null} or invalid. */ - public void addConstructor( JConstructor constructor ) - throws IllegalArgumentException - { - if ( constructor == null ) - throw new IllegalArgumentException( "Constructors cannot be null" ); + public void addConstructor(JConstructor constructor) throws IllegalArgumentException { + if (constructor == null) throw new IllegalArgumentException("Constructors cannot be null"); - if ( constructor.getDeclaringClass() == this ) - { + if (constructor.getDeclaringClass() == this) { /** check signatures (add later) **/ - if ( !_constructors.contains( constructor ) ) - { - _constructors.add( constructor ); + if (!_constructors.contains(constructor)) { + _constructors.add(constructor); } - } - else - { + } else { String err = "The given JConstructor was not created "; err += "by this JClass"; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } } @@ -182,24 +165,19 @@ public void addConstructor( JConstructor constructor ) * @exception java.lang.IllegalArgumentException when the given * JField has a name of an existing JField **/ - public void addField( JField jField ) - throws IllegalArgumentException - { - if ( jField == null ) - { - throw new IllegalArgumentException( "Class members cannot be null" ); + public void addField(JField jField) throws IllegalArgumentException { + if (jField == null) { + throw new IllegalArgumentException("Class members cannot be null"); } String name = jField.getName(); - if ( _fields.get( name ) != null ) - { + if (_fields.get(name) != null) { String err = "duplicate name found: " + name; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - _fields.put( name, jField ); - - } //-- addField + _fields.put(name, jField); + } // -- addField /** * Adds the given JMember to this JClass @@ -210,38 +188,27 @@ public void addField( JField jField ) * or JMethod respectively, or if the JMember is of an * unrecognized class. **/ - public void addMember( JMember jMember ) - throws IllegalArgumentException - { - if ( jMember instanceof JField ) - addField( (JField) jMember ); - else if ( jMember instanceof JMethod ) - addMethod( (JMethod) jMember ); - else - { + public void addMember(JMember jMember) throws IllegalArgumentException { + if (jMember instanceof JField) addField((JField) jMember); + else if (jMember instanceof JMethod) addMethod((JMethod) jMember); + else { String error = null; - if ( jMember == null ) - { + if (jMember == null) { error = "the argument 'jMember' must not be null."; + } else { + error = "Cannot add JMember '" + jMember.getClass().getName() + "' to JClass, unrecognized type."; } - else - { - error = "Cannot add JMember '" + jMember.getClass().getName() + - "' to JClass, unrecognized type."; - } - throw new IllegalArgumentException( error ); + throw new IllegalArgumentException(error); } - - } //-- addMember + } // -- addMember /** * Adds the given JMethod to this JClass * * @param jMethod the JMethod to add **/ - public void addMethod( JMethod jMethod ) - { - addMethod( jMethod, true ); + public void addMethod(JMethod jMethod) { + addMethod(jMethod, true); } /** @@ -254,52 +221,43 @@ public void addMethod( JMethod jMethod ) * @throws java.lang.IllegalArgumentException when the given * JMethod has the same name of an existing JMethod. **/ - public void addMethod( JMethod jMethod, boolean importReturnType ) - throws IllegalArgumentException - { - if ( jMethod == null ) - { - throw new IllegalArgumentException( "Class methods cannot be null" ); + public void addMethod(JMethod jMethod, boolean importReturnType) throws IllegalArgumentException { + if (jMethod == null) { + throw new IllegalArgumentException("Class methods cannot be null"); } - //-- check method name and signatures *add later* + // -- check method name and signatures *add later* - //-- keep method list sorted for esthetics when printing - //-- START SORT :-) + // -- keep method list sorted for esthetics when printing + // -- START SORT :-) boolean added = false; -// short modifierVal = 0; + // short modifierVal = 0; JModifiers modifiers = jMethod.getModifiers(); - if ( modifiers.isAbstract() ) - { - getModifiers().setAbstract( true ); + if (modifiers.isAbstract()) { + getModifiers().setAbstract(true); } - for ( int i = 0; i < _methods.size(); i++ ) - { - JMethod tmp = (JMethod) _methods.get( i ); - //-- first compare modifiers - if ( tmp.getModifiers().isPrivate() ) - { - if ( !modifiers.isPrivate() ) - { - _methods.add( i, jMethod ); + for (int i = 0; i < _methods.size(); i++) { + JMethod tmp = (JMethod) _methods.get(i); + // -- first compare modifiers + if (tmp.getModifiers().isPrivate()) { + if (!modifiers.isPrivate()) { + _methods.add(i, jMethod); added = true; break; } } - //-- compare names - if ( jMethod.getName().compareTo( tmp.getName() ) < 0 ) - { - _methods.add( i, jMethod ); + // -- compare names + if (jMethod.getName().compareTo(tmp.getName()) < 0) { + _methods.add(i, jMethod); added = true; break; } } - //-- END SORT - if ( !added ) _methods.add( jMethod ); - - } //-- addMethod + // -- END SORT + if (!added) _methods.add(jMethod); + } // -- addMethod /** * Adds the given array of JMethods to this JClass @@ -308,15 +266,11 @@ public void addMethod( JMethod jMethod, boolean importReturnType ) * @exception java.lang.IllegalArgumentException when any of the given * JMethods has the same name of an existing JMethod. **/ - public void addMethods( JMethod[] jMethods ) - throws IllegalArgumentException - { - for ( JMethod jMethod : jMethods ) - { - addMethod( jMethod ); + public void addMethods(JMethod[] jMethods) throws IllegalArgumentException { + for (JMethod jMethod : jMethods) { + addMethod(jMethod); } - } //-- addMethods - + } // -- addMethods /** * Creates a new JConstructor and adds it to this @@ -324,10 +278,9 @@ public void addMethods( JMethod[] jMethods ) * * @return the newly created constructor */ - public JConstructor createConstructor() - { - return createConstructor( null ); - } //-- createConstructor + public JConstructor createConstructor() { + return createConstructor(null); + } // -- createConstructor /** * Creates a new JConstructor and adds it to this @@ -336,19 +289,16 @@ public JConstructor createConstructor() * @param params the parameters * @return the newly created constructor */ - public JConstructor createConstructor( JParameter[] params ) - { - JConstructor cons = new JConstructor( this ); - if ( params != null ) - { - for ( JParameter param : params ) - { - cons.addParameter( param ); + public JConstructor createConstructor(JParameter[] params) { + JConstructor cons = new JConstructor(this); + if (params != null) { + for (JParameter param : params) { + cons.addParameter(param); } } - addConstructor( cons ); + addConstructor(cons); return cons; - } //-- createConstructor + } // -- createConstructor /** * Creates and returns an inner-class for this JClass @@ -356,33 +306,26 @@ public JConstructor createConstructor( JParameter[] params ) * @param localname the name of the class (no package name) * @return the new JClass */ - public JClass createInnerClass( String localname ) - { - if ( localname == null ) - { + public JClass createInnerClass(String localname) { + if (localname == null) { String err = "argument 'localname' must not be null."; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - if ( localname.indexOf( '.' ) >= 0 ) - { + if (localname.indexOf('.') >= 0) { String err = "The name of an inner-class must not contain a package name."; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } String classname = getPackageName(); - if ( classname != null ) - { + if (classname != null) { classname = classname + "." + localname; - } - else - { + } else { classname = localname; } - JClass innerClass = new JInnerClass( classname ); - _innerClasses.add( innerClass ); + JClass innerClass = new JInnerClass(classname); + _innerClasses.add(innerClass); return innerClass; - - } //-- createInnerClass + } // -- createInnerClass /** * Returns the constructor at the specified index. @@ -390,29 +333,25 @@ public JClass createInnerClass( String localname ) * @param index the index of the constructor to return * @return the JConstructor at the specified index. */ - public JConstructor getConstructor( int index ) - { - return (JConstructor) _constructors.get( index ); - } //-- getConstructor + public JConstructor getConstructor(int index) { + return (JConstructor) _constructors.get(index); + } // -- getConstructor /** * Returns the an array of the JConstructors contained within this JClass * * @return an array of JConstructor */ - public JConstructor[] getConstructors() - { + public JConstructor[] getConstructors() { int size = _constructors.size(); JConstructor[] jcArray = new JConstructor[size]; - for ( int i = 0; i < _constructors.size(); i++ ) - { - jcArray[i] = _constructors.get( i ); + for (int i = 0; i < _constructors.size(); i++) { + jcArray[i] = _constructors.get(i); } return jcArray; - } //-- getConstructors - + } // -- getConstructors /** * Returns the member with the given name, or null if no member @@ -421,19 +360,17 @@ public JConstructor[] getConstructors() * @return the member with the given name, or null if no member * was found with the given name **/ - public JField getField( String name ) - { - return (JField) _fields.get( name ); - } //-- getField + public JField getField(String name) { + return (JField) _fields.get(name); + } // -- getField /** * Returns an array of all the JFields of this JClass * @return an array of all the JFields of this JClass **/ - public JField[] getFields() - { - return _fields.values().toArray( new JField[0] ); - } //-- getFields + public JField[] getFields() { + return _fields.values().toArray(new JField[0]); + } // -- getFields /** * Returns an array of JClass (the inner classes) @@ -441,27 +378,24 @@ public JField[] getFields() * * @return an array of JClass contained within this JClass */ - public JClass[] getInnerClasses() - { - return _innerClasses.toArray( new JClass[0] ); - } //-- getInnerClasses; + public JClass[] getInnerClasses() { + return _innerClasses.toArray(new JClass[0]); + } // -- getInnerClasses; /** * Returns an array of all the JMethods of this JClass * * @return an array of all the JMethods of this JClass */ - public JMethod[] getMethods() - { + public JMethod[] getMethods() { int size = _methods.size(); JMethod[] marray = new JMethod[size]; - for ( int i = 0; i < _methods.size(); i++ ) - { - marray[i] = _methods.get( i ); + for (int i = 0; i < _methods.size(); i++) { + marray[i] = _methods.get(i); } return marray; - } //-- getMethods + } // -- getMethods /** * Returns the first occurrence of the method with the @@ -471,15 +405,13 @@ public JMethod[] getMethods() * @param startIndex the starting index to begin the search * @return the method if found, otherwise null. */ - public JMethod getMethod( String name, int startIndex ) - { - for ( int i = startIndex; i < _methods.size(); i++ ) - { - JMethod jMethod = _methods.get( i ); - if ( jMethod.getName().equals( name ) ) return jMethod; + public JMethod getMethod(String name, int startIndex) { + for (int i = startIndex; i < _methods.size(); i++) { + JMethod jMethod = _methods.get(i); + if (jMethod.getName().equals(name)) return jMethod; } return null; - } //-- getMethod + } // -- getMethod /** * Returns the JMethod located at the specified index @@ -487,11 +419,9 @@ public JMethod getMethod( String name, int startIndex ) * @param index the index of the JMethod to return. * @return the JMethod */ - public JMethod getMethod( int index ) - { - return _methods.get( index ); - } //-- getMethod - + public JMethod getMethod(int index) { + return _methods.get(index); + } // -- getMethod /** * Returns the JSourceCode for the static initializer @@ -500,284 +430,247 @@ public JMethod getMethod( int index ) * @return the JSourceCode for the static initializer * of this JClass */ - public JSourceCode getStaticInitializationCode() - { + public JSourceCode getStaticInitializationCode() { return _staticInitializer; - } //-- getStaticInitializationCode + } // -- getStaticInitializationCode /** * Gets the super Class that this class extends * @return superClass the super Class that this Class extends */ - public String getSuperClass() - { + public String getSuperClass() { return _superClass; - } //-- getSuperClass + } // -- getSuperClass /** * Prints the source code for this JClass to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] */ - public void print( JSourceWriter jsw ) - { - print( jsw, false ); - } //-- print + public void print(JSourceWriter jsw) { + print(jsw, false); + } // -- print /** * Prints the source code for this JClass to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] - * @param classOnly whether the header, package and imports should be printed too + * @param classOnly whether the header, package and imports should be printed too */ - public void print( JSourceWriter jsw, boolean classOnly ) - { + public void print(JSourceWriter jsw, boolean classOnly) { - if ( jsw == null ) - { - throw new IllegalArgumentException( "argument 'jsw' should not be null." ); + if (jsw == null) { + throw new IllegalArgumentException("argument 'jsw' should not be null."); } - StringBuilder buffer = new StringBuilder(); + if (!classOnly) { + printHeader(jsw); + printPackageDeclaration(jsw); - if ( !classOnly ) - { - printHeader( jsw ); - printPackageDeclaration( jsw ); - - //-- get imports from inner-classes + // -- get imports from inner-classes List removeImports = null; - if ( _innerClasses.size() > 0 ) - { + if (_innerClasses.size() > 0) { removeImports = new ArrayList(); - for ( JClass iClass : _innerClasses ) - { + for (JClass iClass : _innerClasses) { Enumeration e = iClass.getImports(); - while ( e.hasMoreElements() ) - { + while (e.hasMoreElements()) { String classname = e.nextElement(); - if ( !hasImport( classname ) ) - { - addImport( classname ); - removeImports.add( classname ); + if (!hasImport(classname)) { + addImport(classname); + removeImports.add(classname); } } } } - printImportDeclarations( jsw ); - - //-- remove imports from inner-classes, if necessary - if ( removeImports != null ) - { - for ( int i = 0; i < removeImports.size(); i++ ) - { - removeImport( removeImports.get( i ) ); + printImportDeclarations(jsw); + + // -- remove imports from inner-classes, if necessary + if (removeImports != null) { + for (int i = 0; i < removeImports.size(); i++) { + removeImport(removeImports.get(i)); } } - } - //------------/ - //- Java Doc -/ - //------------/ + // ------------/ + // - Java Doc -/ + // ------------/ - getJDocComment().print( jsw ); + getJDocComment().print(jsw); JAnnotations annotations = getAnnotations(); - if ( annotations != null ) annotations.print( jsw ); + if (annotations != null) annotations.print(jsw); - //-- print class information - //-- we need to add some JavaDoc API adding comments + // -- print class information + // -- we need to add some JavaDoc API adding comments - buffer.setLength( 0 ); + buffer.setLength(0); JModifiers modifiers = getModifiers(); - if ( modifiers.isPrivate() ) - { - buffer.append( "private " ); - } - else if ( modifiers.isPublic() ) - { - buffer.append( "public " ); + if (modifiers.isPrivate()) { + buffer.append("private "); + } else if (modifiers.isPublic()) { + buffer.append("public "); } - if ( modifiers.isAbstract() ) - { - buffer.append( "abstract " ); + if (modifiers.isAbstract()) { + buffer.append("abstract "); } - if ( this instanceof JInnerClass && modifiers.isStatic() ) - { - buffer.append( "static " ); + if (this instanceof JInnerClass && modifiers.isStatic()) { + buffer.append("static "); } - if ( modifiers.isFinal() ) - { - buffer.append( "final " ); + if (modifiers.isFinal()) { + buffer.append("final "); } - buffer.append( "class " ); - buffer.append( getLocalName() ); - jsw.writeln( buffer.toString() ); - buffer.setLength( 0 ); + buffer.append("class "); + buffer.append(getLocalName()); + jsw.writeln(buffer.toString()); + buffer.setLength(0); jsw.indent(); - if ( _superClass != null ) - { - buffer.append( "extends " ); - buffer.append( _superClass ); - jsw.writeln( buffer.toString() ); - buffer.setLength( 0 ); + if (_superClass != null) { + buffer.append("extends "); + buffer.append(_superClass); + jsw.writeln(buffer.toString()); + buffer.setLength(0); } - if ( getInterfaceCount() > 0 ) - { - buffer.append( "implements " ); + if (getInterfaceCount() > 0) { + buffer.append("implements "); Enumeration e = getInterfaces(); - while ( e.hasMoreElements() ) - { - buffer.append( e.nextElement() ); - if ( e.hasMoreElements() ) buffer.append( ", " ); + while (e.hasMoreElements()) { + buffer.append(e.nextElement()); + if (e.hasMoreElements()) buffer.append(", "); } - jsw.writeln( buffer.toString() ); - buffer.setLength( 0 ); + jsw.writeln(buffer.toString()); + buffer.setLength(0); } jsw.unindent(); - jsw.writeln( '{' ); + jsw.writeln('{'); jsw.indent(); - //-- declare members + // -- declare members - if ( _fields.size() > 0 ) - { + if (_fields.size() > 0) { jsw.writeln(); - jsw.writeln( " //--------------------------/" ); - jsw.writeln( " //- Class/Member Variables -/" ); - jsw.writeln( "//--------------------------/" ); + jsw.writeln(" //--------------------------/"); + jsw.writeln(" //- Class/Member Variables -/"); + jsw.writeln("//--------------------------/"); jsw.writeln(); } - for ( JField jField : _fields.values() ) - { - //-- print Java comment + for (JField jField : _fields.values()) { + // -- print Java comment JDocComment comment = jField.getComment(); - if ( comment != null ) comment.print( jsw ); + if (comment != null) comment.print(jsw); JAnnotations fieldAnnotations = jField.getAnnotations(); - if ( fieldAnnotations != null ) fieldAnnotations.print( jsw ); + if (fieldAnnotations != null) fieldAnnotations.print(jsw); // -- print member - jsw.write( jField.getModifiers().toString() ); - jsw.write( ' ' ); + jsw.write(jField.getModifiers().toString()); + jsw.write(' '); JType type = jField.getType(); String typeName = type.toString(); - //-- for esthetics use short name in some cases - if ( typeName.equals( toString() ) ) - { + // -- for esthetics use short name in some cases + if (typeName.equals(toString())) { typeName = type.getLocalName(); } - jsw.write( typeName ); - jsw.write( ' ' ); - jsw.write( jField.getName() ); + jsw.write(typeName); + jsw.write(' '); + jsw.write(jField.getName()); String init = jField.getInitString(); - if ( init != null ) - { - jsw.write( " = " ); - jsw.write( init ); + if (init != null) { + jsw.write(" = "); + jsw.write(init); } - jsw.writeln( ';' ); + jsw.writeln(';'); jsw.writeln(); } - //----------------------/ - //- Static Initializer -/ - //----------------------/ + // ----------------------/ + // - Static Initializer -/ + // ----------------------/ - if ( !_staticInitializer.isEmpty() ) - { + if (!_staticInitializer.isEmpty()) { jsw.writeln(); - jsw.writeln( "static" ); - jsw.writeln( "{" ); - _staticInitializer.print( jsw ); - jsw.writeln( "};" ); + jsw.writeln("static"); + jsw.writeln("{"); + _staticInitializer.print(jsw); + jsw.writeln("};"); jsw.writeln(); } - //-- print constructors - if ( _constructors.size() > 0 ) - { + // -- print constructors + if (_constructors.size() > 0) { jsw.writeln(); - jsw.writeln( " //----------------/" ); - jsw.writeln( " //- Constructors -/" ); - jsw.writeln( "//----------------/" ); + jsw.writeln(" //----------------/"); + jsw.writeln(" //- Constructors -/"); + jsw.writeln("//----------------/"); jsw.writeln(); } - for ( int i = 0; i < _constructors.size(); i++ ) - { - JConstructor jConstructor = _constructors.get( i ); - jConstructor.print( jsw ); + for (int i = 0; i < _constructors.size(); i++) { + JConstructor jConstructor = _constructors.get(i); + jConstructor.print(jsw); jsw.writeln(); } - //-- print methods - if ( _methods.size() > 0 ) - { + // -- print methods + if (_methods.size() > 0) { jsw.writeln(); - jsw.writeln( " //-----------/" ); - jsw.writeln( " //- Methods -/" ); - jsw.writeln( "//-----------/" ); + jsw.writeln(" //-----------/"); + jsw.writeln(" //- Methods -/"); + jsw.writeln("//-----------/"); jsw.writeln(); } - for ( int i = 0; i < _methods.size(); i++ ) - { - JMethod jMethod = _methods.get( i ); - jMethod.print( jsw ); + for (int i = 0; i < _methods.size(); i++) { + JMethod jMethod = _methods.get(i); + jMethod.print(jsw); jsw.writeln(); } - //-- print inner-classes - if ( _innerClasses.size() > 0 ) - { + // -- print inner-classes + if (_innerClasses.size() > 0) { jsw.writeln(); - jsw.writeln( " //-----------------/" ); - jsw.writeln( " //- Inner Classes -/" ); - jsw.writeln( "//-----------------/" ); + jsw.writeln(" //-----------------/"); + jsw.writeln(" //- Inner Classes -/"); + jsw.writeln("//-----------------/"); jsw.writeln(); } - for ( int i = 0; i < _innerClasses.size(); i++ ) - { - JClass jClass = _innerClasses.get( i ); - jClass.print( jsw, true ); + for (int i = 0; i < _innerClasses.size(); i++) { + JClass jClass = _innerClasses.get(i); + jClass.print(jsw, true); jsw.writeln(); } - for ( String sourceCodeEntry : sourceCodeEntries ) - { - jsw.writeln( sourceCodeEntry ); + for (String sourceCodeEntry : sourceCodeEntries) { + jsw.writeln(sourceCodeEntry); } jsw.unindent(); - jsw.writeln( '}' ); + jsw.writeln('}'); jsw.flush(); - } //-- printSource + } // -- printSource private List sourceCodeEntries = new ArrayList(); - public void addSourceCode( String sourceCode ) - { - sourceCodeEntries.add( sourceCode ); + public void addSourceCode(String sourceCode) { + sourceCodeEntries.add(sourceCode); } /** @@ -786,10 +679,9 @@ public void addSourceCode( String sourceCode ) * @param constructor the JConstructor to remove * @return true if the constructor was removed, otherwise false. */ - public boolean removeConstructor( JConstructor constructor ) - { - return _constructors.remove( constructor ); - } //-- removeConstructor + public boolean removeConstructor(JConstructor constructor) { + return _constructors.remove(constructor); + } // -- removeConstructor /** * Removes the field with the given name from this JClass @@ -797,16 +689,15 @@ public boolean removeConstructor( JConstructor constructor ) * @param name the name of the field to remove * @return the removed field **/ - public JField removeField( String name ) - { - if ( name == null ) return null; + public JField removeField(String name) { + if (name == null) return null; - JField field = (JField) _fields.remove( name ); + JField field = (JField) _fields.remove(name); - //-- clean up imports - //-- NOT YET IMPLEMENTED + // -- clean up imports + // -- NOT YET IMPLEMENTED return field; - } //-- removeField + } // -- removeField /** * Removes the given JField from this JClass @@ -814,21 +705,18 @@ public JField removeField( String name ) * @param jField, the JField to remove * @return {{@code true} if and only if the field was successfully removed **/ - public boolean removeField( JField jField ) - { - if ( jField == null ) return false; - - Object field = _fields.get( jField.getName() ); - if ( field == jField ) - { - _fields.remove( jField.getName() ); + public boolean removeField(JField jField) { + if (jField == null) return false; + + Object field = _fields.get(jField.getName()); + if (field == jField) { + _fields.remove(jField.getName()); return true; } - //-- clean up imports - //-- NOT YET IMPLEMENTED + // -- clean up imports + // -- NOT YET IMPLEMENTED return false; - - } //-- removeField + } // -- removeField /** * Removes the given inner-class (JClass) from this JClass. @@ -836,26 +724,21 @@ public boolean removeField( JField jField ) * @param jClass the JClass (inner-class) to remove. * @return true if the JClass was removed, otherwise false. */ - public boolean removeInnerClass( JClass jClass ) - { - return _innerClasses.remove( jClass ); - } //-- removeInnerClass + public boolean removeInnerClass(JClass jClass) { + return _innerClasses.remove(jClass); + } // -- removeInnerClass /** * Sets the super Class that this class extends * @param superClass the super Class that this Class extends */ - public void setSuperClass( String superClass ) - { + public void setSuperClass(String superClass) { _superClass = superClass; - } //-- setSuperClass + } // -- setSuperClass - final class JInnerClass extends JClass - { - JInnerClass( String name ) - { - super( name ); + final class JInnerClass extends JClass { + JInnerClass(String name) { + super(name); } - } //-- JInnerClass - -} //-- JClass + } // -- JInnerClass +} // -- JClass diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCollectionType.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCollectionType.java index 7de02b5f9..4cf602885 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCollectionType.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCollectionType.java @@ -22,9 +22,7 @@ * @version $Revision$ $Date$ * @since 1.0.4 */ -public final class JCollectionType - extends JComponentizedType -{ +public final class JCollectionType extends JComponentizedType { // -------------------------------------------------------------------------- /** Name of the actual collection instance to be used, e.g. java.util.ArrayList. */ @@ -39,9 +37,8 @@ public final class JCollectionType * @param componentType Component type. * @param useJava50 True if Java 5.0 should be used. */ - public JCollectionType( final String typeName, final JType componentType, final boolean useJava50 ) - { - super( typeName, componentType, useJava50 ); + public JCollectionType(final String typeName, final JType componentType, final boolean useJava50) { + super(typeName, componentType, useJava50); } /** @@ -52,10 +49,9 @@ public JCollectionType( final String typeName, final JType componentType, final * @param componentType Component type. * @param useJava50 True if Java 5.0 should be used. */ - public JCollectionType( final String typeName, final String instanceName, final JType componentType, - final boolean useJava50 ) - { - super( typeName, componentType, useJava50 ); + public JCollectionType( + final String typeName, final String instanceName, final JType componentType, final boolean useJava50) { + super(typeName, componentType, useJava50); _instanceName = instanceName; } @@ -66,12 +62,9 @@ public JCollectionType( final String typeName, final String instanceName, final * * @return The instance name of this collection type. */ - public String getInstanceName() - { - if ( _instanceName != null ) - { - if ( isUseJava50() ) - { + public String getInstanceName() { + if (_instanceName != null) { + if (isUseJava50()) { return _instanceName + "<" + getComponentType().toString() + ">"; } @@ -84,10 +77,8 @@ public String getInstanceName() /** * Returns the String representation of this JType. */ - public String toString() - { - if ( isUseJava50() ) - { + public String toString() { + if (isUseJava50()) { return getName() + "<" + getComponentType().toString() + ">"; } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComment.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComment.java index 2e7072d7f..48e1bc5b0 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComment.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComment.java @@ -42,8 +42,6 @@ * * $Id$ */ - - package org.codehaus.modello.plugin.java.javasource; /* @@ -73,9 +71,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JComment -{ - +public class JComment { /** * The auto style, allows this JComment to automatically @@ -104,7 +100,6 @@ public class JComment **/ public static final short JAVADOC_STYLE = 4; - private static final String START_BLOCK = "/*"; private static final String END_BLOCK = " */"; @@ -115,7 +110,6 @@ public class JComment private static final String LINE_COMMENT_PREFIX = "// "; private static final String SPACE_PREFIX = " "; - /** * The style of this comment **/ @@ -131,79 +125,66 @@ public class JComment **/ protected static final int MAX_LENGTH = 65; - /** * Creates a new Java Comment **/ - public JComment() - { + public JComment() { super(); _comment = new StringBuilder(); - } //-- JComment + } // -- JComment /** * Creates a new Java comment with the given style - * + * * @param style the comment style **/ - public JComment( short style ) - { + public JComment(short style) { this(); this.style = style; - } //-- JComment + } // -- JComment /** * Appends the comment String to this JDocComment * @param comment the comment to append **/ - public void appendComment( String comment ) - { - _comment.append( comment ); - } //-- appendComment - + public void appendComment(String comment) { + _comment.append(comment); + } // -- appendComment /** * prints this JComment using the given JSourceWriter * @param jsw the JSourceWriter to print to **/ - public void print( JSourceWriter jsw ) - { + public void print(JSourceWriter jsw) { - - if ( jsw == null ) return; //-- nothing to do + if (jsw == null) return; // -- nothing to do LineFormatter formatter = null; - //-- calculate comment length + // -- calculate comment length short currentIndent = jsw.getIndentSize(); int maxLength = MAX_LENGTH - currentIndent; - //-- a simple to check to make sure we have some room - //-- to print the comment - if ( maxLength <= 17 ) maxLength = MAX_LENGTH / 2; + // -- a simple to check to make sure we have some room + // -- to print the comment + if (maxLength <= 17) maxLength = MAX_LENGTH / 2; short resolvedStyle = style; - if ( style == AUTO_STYLE ) - { - //-- estimation of number of lines + if (style == AUTO_STYLE) { + // -- estimation of number of lines int nbrLines = _comment.length() / maxLength; - if ( nbrLines > 2 ) - resolvedStyle = BLOCK_STYLE; - else - resolvedStyle = LINE_STYLE; + if (nbrLines > 2) resolvedStyle = BLOCK_STYLE; + else resolvedStyle = LINE_STYLE; } - - - //-- start comment + // -- start comment String prefix = null; String start = null; String end = null; - switch ( resolvedStyle ) - { + switch (resolvedStyle) { case BLOCK_STYLE: start = START_BLOCK; end = END_BLOCK; @@ -219,57 +200,51 @@ public void print( JSourceWriter jsw ) end = END_JAVADOC; prefix = ASTERIX_PREFIX; break; - default: //-- LINE + default: // -- LINE prefix = LINE_COMMENT_PREFIX; break; } - if ( start != null ) jsw.writeln( start ); - //-- print main comment - formatter = new LineFormatter( _comment.toString(), maxLength, prefix ); - while ( formatter.hasMoreLines() ) - { - jsw.writeln( formatter.nextLine() ); + if (start != null) jsw.writeln(start); + // -- print main comment + formatter = new LineFormatter(_comment.toString(), maxLength, prefix); + while (formatter.hasMoreLines()) { + jsw.writeln(formatter.nextLine()); } - if ( end != null ) jsw.writeln( end ); + if (end != null) jsw.writeln(end); jsw.flush(); - } //-- print + } // -- print /** * Sets the comment String of this JDocComment * @param comment the comment String of this JDocComment **/ - public void setComment( String comment ) - { - _comment.setLength( 0 ); - _comment.append( comment ); - } //-- setComment + public void setComment(String comment) { + _comment.setLength(0); + _comment.append(comment); + } // -- setComment /** * Sets the style for this JComment * @param style the style to use for this JComment **/ - public void setStyle( short style ) - { + public void setStyle(short style) { this.style = style; - } //-- setStyle + } // -- setStyle /** * Returns the String representation of this Java Doc Comment * @return the String representation of this Java Doc Comment **/ - public String toString() - { + public String toString() { return ""; - } //-- toString - -} //-- JComment + } // -- toString +} // -- JComment /** * Formats a given String for use within a Java comment * @author Keith Visco **/ -class LineFormatter -{ +class LineFormatter { String comment = null; @@ -285,24 +260,20 @@ class LineFormatter * Creates a LineFormatter for the given comment * @param comment the String to format **/ - LineFormatter( String comment ) - { + LineFormatter(String comment) { this.comment = comment; - if ( comment != null ) this.length = comment.length(); + if (comment != null) this.length = comment.length(); sb = new StringBuilder(); - } //-- LineFormatter - + } // -- LineFormatter /** * Creates a new LineFormatter for the given comment * @param comment the String to format * @param maxLength the maximum number of characters per line **/ - LineFormatter( String comment, int maxLength ) - { - this( comment, maxLength, null ); - } //-- LineFormatter - + LineFormatter(String comment, int maxLength) { + this(comment, maxLength, null); + } // -- LineFormatter /** * Creates a new LineFormatter for the given comment @@ -310,89 +281,72 @@ class LineFormatter * @param maxLength the maximum number of characters per line * @param prefix a prefix to append to the beginning of each line **/ - LineFormatter( String comment, int maxLength, String prefix ) - { - this( comment ); + LineFormatter(String comment, int maxLength, String prefix) { + this(comment); this.maxLength = maxLength; this.prefix = prefix; - } //-- LineFormatter + } // -- LineFormatter - boolean hasMoreLines() - { - if ( comment == null ) return false; - return ( offset < length ); - } //-- isFinished + boolean hasMoreLines() { + if (comment == null) return false; + return (offset < length); + } // -- isFinished - String nextLine() - { - if ( comment == null ) return null; - if ( offset >= length ) return null; + String nextLine() { + if (comment == null) return null; + if (offset >= length) return null; - sb.setLength( 0 ); - if ( prefix != null ) sb.append( prefix ); + sb.setLength(0); + if (prefix != null) sb.append(prefix); int max = offset + maxLength; - if ( max > this.length ) max = this.length; - + if (max > this.length) max = this.length; int index = offset; int breakable = offset; - for ( ; index < max; index++ ) - { - char ch = comment.charAt( index ); - if ( isNewLine( ch ) ) - { - sb.append( comment.substring( offset, index ) ); + for (; index < max; index++) { + char ch = comment.charAt(index); + if (isNewLine(ch)) { + sb.append(comment.substring(offset, index)); offset = index + 1; return sb.toString(); } - if ( isWhitespace( ch ) ) breakable = index; + if (isWhitespace(ch)) breakable = index; } - if ( index < length - 1 ) - { - //-- if we could not find a breakable character, we must look - //-- ahead - if ( offset == breakable ) - { - while ( index < length ) - { - if ( isBreakable( comment.charAt( index ) ) ) break; + if (index < length - 1) { + // -- if we could not find a breakable character, we must look + // -- ahead + if (offset == breakable) { + while (index < length) { + if (isBreakable(comment.charAt(index))) break; ++index; } - } - else - index = breakable; + } else index = breakable; } - sb.append( comment.substring( offset, index ) ); + sb.append(comment.substring(offset, index)); offset = index + 1; return sb.toString(); - } //-- getNextLine + } // -- getNextLine /** * Sets the prefix that should be appended to the beginning of * each line * @param prefix the prefix for this LineFormatter **/ - void setPrefix( String prefix ) - { + void setPrefix(String prefix) { this.prefix = prefix; - } //-- setPrefix + } // -- setPrefix - private boolean isBreakable( char ch ) - { - return ( isWhitespace( ch ) || isNewLine( ch ) ); + private boolean isBreakable(char ch) { + return (isWhitespace(ch) || isNewLine(ch)); } - private boolean isWhitespace( char ch ) - { - return ( ( ch == ' ' ) || ( ch == '\t' ) ); - } //-- isWhitespace - - private boolean isNewLine( char ch ) - { - return ( ( ch == '\n' ) || ( ch == '\r' ) ); - } //-- isNewLineChar - -} //-- LineFormatter + private boolean isWhitespace(char ch) { + return ((ch == ' ') || (ch == '\t')); + } // -- isWhitespace + private boolean isNewLine(char ch) { + return ((ch == '\n') || (ch == '\r')); + } // -- isNewLineChar +} // -- LineFormatter diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCompUnit.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCompUnit.java index 149ff859e..e7d2939ef 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCompUnit.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCompUnit.java @@ -50,7 +50,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -93,16 +92,14 @@ * @author Gary Shea * @version $Revision$ $Date$ **/ -public class JCompUnit -{ +public class JCompUnit { /** * The Id for Source control systems * I needed to separate this line to prevent CVS from * expanding it here! ;-) **/ - private static final String DEFAULT_HEADER - = "$" + "Id$"; + private static final String DEFAULT_HEADER = "$" + "Id$"; private JComment header = null; @@ -119,13 +116,13 @@ public class JCompUnit /** * The set of top-level classes that live in this compilation unit. **/ - //private TypeList classes = null; + // private TypeList classes = null; private List classes = null; /** * The set of top-level interfaces that live in this compilation unit. **/ - //private TypeList interfaces = null; + // private TypeList interfaces = null; private List interfaces = null; /** @@ -135,12 +132,11 @@ public class JCompUnit * @param fileName the name of the file in which this JCompUnit * will be stored **/ - public JCompUnit( String packageName, String fileName ) - { + public JCompUnit(String packageName, String fileName) { this.packageName = packageName; this.fileName = fileName; init(); - } //-- JCompUnit + } // -- JCompUnit /** * Creates a new JCompUnit with the given JClass (which must have @@ -149,8 +145,7 @@ public JCompUnit( String packageName, String fileName ) * from jClass. * @param jClass the public class for this JCompUnit. **/ - public JCompUnit( JClass jClass ) - { + public JCompUnit(JClass jClass) { this.packageName = jClass.getPackageName(); // The outer name is the package plus the simple name of the @@ -175,25 +170,22 @@ public JCompUnit( JClass jClass ) this.fileName = filePrefix + ".java"; init(); - classes.add( jClass ); - - } //-- JCompUnit + classes.add(jClass); + } // -- JCompUnit /** * Creates a new JCompUnit with the given JInterface as public interface * Package and file name are taken from jInterface. * @param jInterface the public interface for this JCompUnit. **/ - public JCompUnit( JInterface jInterface ) - { + public JCompUnit(JInterface jInterface) { this.packageName = jInterface.getPackageName(); this.fileName = jInterface.getLocalName() + ".java"; init(); - interfaces.add( jInterface ); - } //-- JCompUnit + interfaces.add(jInterface); + } // -- JCompUnit - private void init() - { + private void init() { classes = new ArrayList(); interfaces = new ArrayList(); } @@ -207,41 +199,32 @@ private void init() * JStructure has the same name of an existing JStructure * or if the class of jStructure is unknown. */ - public void addStructure( JStructure jStructure ) - throws IllegalArgumentException - { - if ( jStructure instanceof JInterface ) - addInterface( (JInterface) jStructure ); - else if ( jStructure instanceof JClass ) - addClass( (JClass) jStructure ); - else - { - String err = "Unknown JStructure subclass '" - + jStructure.getClass().getName() + "'."; - throw new IllegalArgumentException( err ); + public void addStructure(JStructure jStructure) throws IllegalArgumentException { + if (jStructure instanceof JInterface) addInterface((JInterface) jStructure); + else if (jStructure instanceof JClass) addClass((JClass) jStructure); + else { + String err = "Unknown JStructure subclass '" + jStructure.getClass().getName() + "'."; + throw new IllegalArgumentException(err); } - - } //-- addStructure + } // -- addStructure /** * Adds a JClass which should be printed in this file. - * + * * @param jClass the JClass to add **/ - public void addClass( JClass jClass ) - { - classes.add( jClass ); - } //-- addClass + public void addClass(JClass jClass) { + classes.add(jClass); + } // -- addClass /** * Adds a JInterface which should be printed in this file. - * + * * @param jInterface the JInterface to add **/ - public void addInterface( JInterface jInterface ) - { - interfaces.add( jInterface ); - } //-- addInterface + public void addInterface(JInterface jInterface) { + interfaces.add(jInterface); + } // -- addInterface /** * returns a array of String containing all import classes/packages, @@ -249,27 +232,22 @@ public void addInterface( JInterface jInterface ) * @return a array of String containing all import classes/packages, * also imports within the same package of this object. */ - public SortedSet getImports() - { + public SortedSet getImports() { SortedSet allImports = new TreeSet(); // add imports from classes - for ( JClass jClass : classes ) - { + for (JClass jClass : classes) { Enumeration e = jClass.getImports(); - while ( e.hasMoreElements() ) - { - allImports.add( e.nextElement() ); + while (e.hasMoreElements()) { + allImports.add(e.nextElement()); } } - for ( JInterface jInterface : interfaces ) - { + for (JInterface jInterface : interfaces) { Enumeration e = jInterface.getImports(); - while ( e.hasMoreElements() ) - { - allImports.add( e.nextElement() ); + while (e.hasMoreElements()) { + allImports.add(e.nextElement()); } } @@ -284,65 +262,55 @@ public SortedSet getImports() * @return the name of the file that this JCompUnit would be * printed as, given a call to #print. **/ - public String getFilename( String destDir ) - { + public String getFilename(String destDir) { - String filename = new String( fileName ); + String filename = new String(fileName); - //-- Convert Java package to path string + // -- Convert Java package to path string String javaPackagePath = ""; - if ( ( packageName != null ) && ( packageName.length() > 0 ) ) - { - javaPackagePath = packageName.replace( '.', File.separatorChar ); + if ((packageName != null) && (packageName.length() > 0)) { + javaPackagePath = packageName.replace('.', File.separatorChar); } - //-- Create fully qualified path (including 'destDir') to file + // -- Create fully qualified path (including 'destDir') to file File pathFile; - if ( destDir == null ) - pathFile = new File( javaPackagePath ); - else - pathFile = new File( destDir, javaPackagePath ); - if ( !pathFile.exists() ) - { + if (destDir == null) pathFile = new File(javaPackagePath); + else pathFile = new File(destDir, javaPackagePath); + if (!pathFile.exists()) { pathFile.mkdirs(); } - //-- Prefix filename with path - if ( pathFile.toString().length() > 0 ) - filename = pathFile.toString() + File.separator + filename; + // -- Prefix filename with path + if (pathFile.toString().length() > 0) filename = pathFile.toString() + File.separator + filename; return filename; - } //-- getFilename + } // -- getFilename /** * Returns the name of the package that this JCompUnit is a member of * @return the name of the package that this JCompUnit is a member of, * or null if there is no current package name defined **/ - public String getPackageName() - { + public String getPackageName() { return this.packageName; - } //-- getPackageName + } // -- getPackageName - protected static String getPackageFromClassName( String className ) - { + protected static String getPackageFromClassName(String className) { int idx = -1; - if ( ( idx = className.lastIndexOf( '.' ) ) > 0 ) - { - return className.substring( 0, idx ); + if ((idx = className.lastIndexOf('.')) > 0) { + return className.substring(0, idx); } return null; - } //-- getPackageFromClassName + } // -- getPackageFromClassName /** * Prints the source code for this JClass in the current directory * with the default line seperator of the the runtime platform. * @see #print(java.lang.String, java.lang.String) **/ - public void print() - { - print( null, null ); - } //-- print + public void print() { + print(null, null); + } // -- print /** * Prints the source code for this JClass @@ -350,10 +318,9 @@ public void print() * @param destDir the destination directory to generate the file. * @see #print(java.lang.String, java.lang.String) **/ - public void print( String destDir ) - { - print( destDir, null ); - } //-- print + public void print(String destDir) { + print(destDir, null); + } // -- print /** * Prints the source code for this JCompUnit. @@ -362,40 +329,34 @@ public void print( String destDir ) * If null, then the default line separator for the runtime platform will * be used. **/ - public void print( String destDir, String lineSeparator ) - { + public void print(String destDir, String lineSeparator) { - //-- open output file - String filename = getFilename( destDir ); + // -- open output file + String filename = getFilename(destDir); - File file = new File( filename ); + File file = new File(filename); JSourceWriter jsw = null; - try - { - jsw = new JSourceWriter( WriterFactory.newPlatformWriter( file ) ); - } - catch ( java.io.IOException ioe ) - { - System.out.println( "unable to create compilation unit file: " + filename ); + try { + jsw = new JSourceWriter(WriterFactory.newPlatformWriter(file)); + } catch (java.io.IOException ioe) { + System.out.println("unable to create compilation unit file: " + filename); return; } - if ( lineSeparator == null ) - { - lineSeparator = System.getProperty( "line.separator" ); + if (lineSeparator == null) { + lineSeparator = System.getProperty("line.separator"); } - jsw.setLineSeparator( lineSeparator ); - print( jsw ); + jsw.setLineSeparator(lineSeparator); + print(jsw); jsw.flush(); jsw.close(); - } //-- print + } // -- print /** * Prints the source code for this JClass. * @param jsw the JSourceWriter to print to. **/ - public void print( JSourceWriter jsw ) - { + public void print(JSourceWriter jsw) { // Traverse the nested class and interface heirarchy and // update the names to match the compilation unit. @@ -403,47 +364,40 @@ public void print( JSourceWriter jsw ) resolveNames(); StringBuilder buffer = new StringBuilder(); - //-- write file header - if ( header != null ) - header.print( jsw ); - else - { - jsw.writeln( "/*" ); - jsw.writeln( " * " + DEFAULT_HEADER ); - jsw.writeln( "*/" ); + // -- write file header + if (header != null) header.print(jsw); + else { + jsw.writeln("/*"); + jsw.writeln(" * " + DEFAULT_HEADER); + jsw.writeln("*/"); } jsw.writeln(); jsw.flush(); - //-- print package name - if ( ( packageName != null ) && ( packageName.length() > 0 ) ) - { + // -- print package name + if ((packageName != null) && (packageName.length() > 0)) { - buffer.setLength( 0 ); - buffer.append( "package " ); - buffer.append( packageName ); - buffer.append( ';' ); - jsw.writeln( buffer.toString() ); + buffer.setLength(0); + buffer.append("package "); + buffer.append(packageName); + buffer.append(';'); + jsw.writeln(buffer.toString()); jsw.writeln(); } - //-- print imports - jsw.writeln( " //---------------------------------------------/" ); - jsw.writeln( " //- Imported classes, interfaces and packages -/" ); - jsw.writeln( "//---------------------------------------------/" ); + // -- print imports + jsw.writeln(" //---------------------------------------------/"); + jsw.writeln(" //- Imported classes, interfaces and packages -/"); + jsw.writeln("//---------------------------------------------/"); jsw.writeln(); SortedSet allImports = getImports(); String compUnitPackage = getPackageName(); - for ( String importName : allImports ) - { - String importsPackage - = JStructure.getPackageFromClassName( importName ); - if ( importsPackage != null && - !importsPackage.equals( compUnitPackage ) ) - { - jsw.write( "import " ); - jsw.write( importName ); - jsw.writeln( ';' ); + for (String importName : allImports) { + String importsPackage = JStructure.getPackageFromClassName(importName); + if (importsPackage != null && !importsPackage.equals(compUnitPackage)) { + jsw.write("import "); + jsw.write(importName); + jsw.writeln(';'); } } jsw.writeln(); @@ -451,13 +405,13 @@ public void print( JSourceWriter jsw ) // Print the public elements, interfaces first, then classes. // There should only be one public element, but if there are // more we let the compiler catch it. - printStructures( jsw, true ); + printStructures(jsw, true); // Print the remaining non-public elements, interfaces first. - printStructures( jsw, false ); + printStructures(jsw, false); jsw.flush(); - } //-- print + } // -- print /** * Print the source code for the contained JClass objects. @@ -465,64 +419,55 @@ public void print( JSourceWriter jsw ) * @param printPublic if true, print only public classes; if * false, print only non-public classes. **/ - final public void printStructures( JSourceWriter jsw, boolean printPublic ) - { + public final void printStructures(JSourceWriter jsw, boolean printPublic) { - //-- print class information - //-- we need to add some JavaDoc API adding comments + // -- print class information + // -- we need to add some JavaDoc API adding comments boolean isFirst = true; - //SortedSet interfaceList = interfaces.sortedOnFullName(); - for ( JInterface jInterface : interfaces ) - { - if ( jInterface.getModifiers().isPublic() == printPublic ) - { - if ( isFirst ) - { - Header.print( jsw, printPublic ); + // SortedSet interfaceList = interfaces.sortedOnFullName(); + for (JInterface jInterface : interfaces) { + if (jInterface.getModifiers().isPublic() == printPublic) { + if (isFirst) { + Header.print(jsw, printPublic); isFirst = false; } - jInterface.print( jsw, true ); + jInterface.print(jsw, true); jsw.writeln(); } } - //SortedSet classList = classes.sortedOnFullName(); - for ( JClass jClass : classes ) - { - if ( jClass.getModifiers().isPublic() == printPublic ) - { - if ( isFirst ) - { - Header.print( jsw, printPublic ); + // SortedSet classList = classes.sortedOnFullName(); + for (JClass jClass : classes) { + if (jClass.getModifiers().isPublic() == printPublic) { + if (isFirst) { + Header.print(jsw, printPublic); isFirst = false; } - jClass.print( jsw, true ); + jClass.print(jsw, true); jsw.writeln(); } } - } //-- printElements(JSourceWriter, int) + } // -- printElements(JSourceWriter, int) /** * Sets the header comment for this JCompUnit * @param comment the comment to display at the top of the source file * when printed **/ - public void setHeader( JComment comment ) - { + public void setHeader(JComment comment) { this.header = comment; - } //-- setHeader + } // -- setHeader - //-------------------/ - //- Private Methods -/ - //-------------------/ + // -------------------/ + // - Private Methods -/ + // -------------------/ /** * Update the names of nested classes and interfaces. **/ - private void resolveNames() - { + private void resolveNames() { /* Commented out until support for inner-classes is added @@ -537,22 +482,17 @@ private void resolveNames() jInterface.resolveNames(packageName, null); } */ - } //-- resolveNames - - -} //-- JCompUnit + } // -- resolveNames +} // -- JCompUnit /** * Print the headers delineating the public and non-public elements of * the compilation unit. **/ -class Header -{ +class Header { private static String[] publicHeader = { - " //-----------------------------/", - " //- Public Class / Interface -/", - "//-----------------------------/", + " //-----------------------------/", " //- Public Class / Interface -/", "//-----------------------------/", }; private static String[] nonPublicHeader = { " //-------------------------------------/", @@ -566,13 +506,11 @@ class Header * @params boolean if true print the public header, otherwise * print the non-public header. **/ - protected static void print( JSourceWriter jsw, boolean printPublic ) - { + protected static void print(JSourceWriter jsw, boolean printPublic) { String[] header = printPublic ? publicHeader : nonPublicHeader; - for ( String aHeader : header ) - { - jsw.writeln( aHeader ); + for (String aHeader : header) { + jsw.writeln(aHeader); } jsw.writeln(); } -} //-- Header +} // -- Header diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComponentizedType.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComponentizedType.java index d8c174d24..9975487a9 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComponentizedType.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComponentizedType.java @@ -22,9 +22,7 @@ * @version $Revision$ $Date$ * @since 1.0.4 */ -public class JComponentizedType - extends JType -{ +public class JComponentizedType extends JType { // -------------------------------------------------------------------------- /** Indicates the data type contained in this collection. */ @@ -42,9 +40,8 @@ public class JComponentizedType * @param componentType Component type. * @param useJava50 True if Java 5.0 should be used. */ - protected JComponentizedType( final String name, final JType componentType, final boolean useJava50 ) - { - super( name ); + protected JComponentizedType(final String name, final JType componentType, final boolean useJava50) { + super(name); _componentType = componentType; _useJava50 = useJava50; @@ -57,8 +54,7 @@ protected JComponentizedType( final String name, final JType componentType, fina * * @return The component type. */ - public final JType getComponentType() - { + public final JType getComponentType() { return _componentType; } @@ -67,8 +63,7 @@ public final JType getComponentType() * * @return True if Java 5.0 is used. */ - public final boolean isUseJava50() - { + public final boolean isUseJava50() { return _useJava50; } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JConstructor.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JConstructor.java index b58033eea..649ca1c53 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JConstructor.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JConstructor.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; import java.util.Collections; @@ -77,8 +76,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JConstructor -{ +public class JConstructor { /** * The set of modifiers for this JMethod @@ -102,11 +100,10 @@ public class JConstructor /** * Creates a new method with the given name and returnType. * For "void" return types, simply pass in null as the returnType - * + * * @param declaringClass the declaring class for this constructor **/ - public JConstructor( JClass declaringClass ) - { + public JConstructor(JClass declaringClass) { this.declaringClass = declaringClass; this.modifiers = new JModifiers(); this.params = new LinkedHashMap<>(); @@ -120,42 +117,36 @@ public JConstructor( JClass declaringClass ) * @exception java.lang.IllegalArgumentException when a parameter already * exists for this Method with the same name as the new parameter **/ - public void addParameter( JParameter parameter ) - throws IllegalArgumentException - { - if ( parameter == null ) return; - //-- check current params - if ( params.get( parameter.getName() ) != null ) - { + public void addParameter(JParameter parameter) throws IllegalArgumentException { + if (parameter == null) return; + // -- check current params + if (params.get(parameter.getName()) != null) { StringBuilder err = new StringBuilder(); - err.append( "A parameter already exists for the constructor, " ); - err.append( this.declaringClass.getName() ); - err.append( ", with the name: " ); - err.append( parameter.getName() ); - throw new IllegalArgumentException( err.toString() ); + err.append("A parameter already exists for the constructor, "); + err.append(this.declaringClass.getName()); + err.append(", with the name: "); + err.append(parameter.getName()); + throw new IllegalArgumentException(err.toString()); } - params.put( parameter.getName(), parameter ); - } //-- addParameter + params.put(parameter.getName(), parameter); + } // -- addParameter /** * Returns the class in which this JMember has been declared * @return the class in which this JMember has been declared **/ - public JClass getDeclaringClass() - { + public JClass getDeclaringClass() { return this.declaringClass; - } //-- getDeclaringClass + } // -- getDeclaringClass /** * Returns the modifiers for this JConstructor * @return the modifiers for this JConstructor **/ - public JModifiers getModifiers() - { + public JModifiers getModifiers() { return this.modifiers; - } //-- getModifiers - + } // -- getModifiers /** * Returns an array of JParameters consisting of the parameters @@ -163,120 +154,98 @@ public JModifiers getModifiers() * @return a JParameter array consisting of the parameters * of this Method in declared order **/ - public JParameter[] getParameters() - { - return params.values().toArray( new JParameter[0] ); - } //-- getParameters + public JParameter[] getParameters() { + return params.values().toArray(new JParameter[0]); + } // -- getParameters - public JSourceCode getSourceCode() - { + public JSourceCode getSourceCode() { return this.sourceCode; - } //-- getSourceCode + } // -- getSourceCode - public void print( JSourceWriter jsw ) - { + public void print(JSourceWriter jsw) { JAnnotations annotations = getAnnotations(); - if ( annotations != null ) annotations.print( jsw ); - - if ( modifiers.isPrivate() ) - jsw.write( "private" ); - else if ( modifiers.isProtected() ) - jsw.write( "protected" ); - else - jsw.write( "public" ); - jsw.write( ' ' ); - jsw.write( declaringClass.getLocalName() ); - jsw.write( '(' ); - - //-- print parameters - if ( !params.isEmpty() ) - { - Enumeration paramEnum = Collections.enumeration( params.values() ); - jsw.write( paramEnum.nextElement() ); - while( paramEnum.hasMoreElements()) - { - jsw.write( ", " ); - jsw.write( paramEnum.nextElement() ); + if (annotations != null) annotations.print(jsw); + + if (modifiers.isPrivate()) jsw.write("private"); + else if (modifiers.isProtected()) jsw.write("protected"); + else jsw.write("public"); + jsw.write(' '); + jsw.write(declaringClass.getLocalName()); + jsw.write('('); + + // -- print parameters + if (!params.isEmpty()) { + Enumeration paramEnum = Collections.enumeration(params.values()); + jsw.write(paramEnum.nextElement()); + while (paramEnum.hasMoreElements()) { + jsw.write(", "); + jsw.write(paramEnum.nextElement()); } } - - - for ( int i = 0; i < params.size(); i++ ) - { - } - jsw.writeln( ')' ); - jsw.writeln( '{' ); - //jsw.indent(); - sourceCode.print( jsw ); - //jsw.unindent(); - if ( !jsw.isNewline() ) jsw.writeln(); - jsw.write( "} //-- " ); - jsw.writeln( toString() ); - } //-- print - public void setModifiers( JModifiers modifiers ) - { + for (int i = 0; i < params.size(); i++) {} + jsw.writeln(')'); + jsw.writeln('{'); + // jsw.indent(); + sourceCode.print(jsw); + // jsw.unindent(); + if (!jsw.isNewline()) jsw.writeln(); + jsw.write("} //-- "); + jsw.writeln(toString()); + } // -- print + + public void setModifiers(JModifiers modifiers) { this.modifiers = modifiers.copy(); - this.modifiers.setFinal( false ); - } //-- setModifiers + this.modifiers.setFinal(false); + } // -- setModifiers - public void setSourceCode( String sourceCode ) - { - this.sourceCode = new JSourceCode( sourceCode ); - } //-- setSourceCode + public void setSourceCode(String sourceCode) { + this.sourceCode = new JSourceCode(sourceCode); + } // -- setSourceCode - public void setSourceCode( JSourceCode sourceCode ) - { + public void setSourceCode(JSourceCode sourceCode) { this.sourceCode = sourceCode; - } //-- setSourceCode + } // -- setSourceCode - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( declaringClass.getName() ); - sb.append( '(' ); - - //-- print parameters - if ( !params.isEmpty() ) - { - Enumeration paramEnum = Collections.enumeration( params.values() ); - sb.append( paramEnum.nextElement().getType().getName() ); - while( paramEnum.hasMoreElements()) - { - sb.append( ", " ); - sb.append( paramEnum.nextElement().getType().getName() ); + sb.append(declaringClass.getName()); + sb.append('('); + + // -- print parameters + if (!params.isEmpty()) { + Enumeration paramEnum = Collections.enumeration(params.values()); + sb.append(paramEnum.nextElement().getType().getName()); + while (paramEnum.hasMoreElements()) { + sb.append(", "); + sb.append(paramEnum.nextElement().getType().getName()); } } - sb.append( ')' ); + sb.append(')'); return sb.toString(); - } //-- toString + } // -- toString /** * @return the annotations */ - public JAnnotations getAnnotations() - { + public JAnnotations getAnnotations() { return annotations; } /** * @param annotation the annotation to append */ - public void appendAnnotation( String annotation ) - { - if ( annotations == null ) - { + public void appendAnnotation(String annotation) { + if (annotations == null) { annotations = new JAnnotations(); } - annotations.appendAnnotation( annotation ); + annotations.appendAnnotation(annotation); } /** * @param annotations the annotations to set */ - public void setAnnotations( JAnnotations annotations ) - { + public void setAnnotations(JAnnotations annotations) { this.annotations = annotations; } - -} //-- JConstructor +} // -- JConstructor diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocComment.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocComment.java index 52d9dd072..ee65bdb04 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocComment.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocComment.java @@ -42,13 +42,8 @@ * * $Id$ */ - - package org.codehaus.modello.plugin.java.javasource; -import java.util.ArrayList; -import java.util.Collections; - /* * Copyright (c) 2004, Codehaus.org * @@ -71,6 +66,8 @@ * SOFTWARE. */ +import java.util.ArrayList; +import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -80,9 +77,7 @@ * @author Keith Visco * @version $Revision$ $Date$ */ -public class JDocComment -{ - +public class JDocComment { /** * An ordered list of descriptors @@ -97,94 +92,83 @@ public class JDocComment /** * Creates a new JavaDoc Comment */ - public JDocComment() - { + public JDocComment() { super(); _descriptors = new ArrayList(); _comment = new StringBuilder(); - } //-- JDocComment + } // -- JDocComment /** * Adds the given JDocDescriptor to this JDocComment * * @param jdesc the JDocDescriptor to add */ - public void addDescriptor( JDocDescriptor jdesc ) - { + public void addDescriptor(JDocDescriptor jdesc) { - if ( jdesc == null ) return; - //-- on the fly sorting of descriptors - if ( _descriptors.size() == 0 ) - { - _descriptors.add( jdesc ); + if (jdesc == null) return; + // -- on the fly sorting of descriptors + if (_descriptors.size() == 0) { + _descriptors.add(jdesc); return; } - for ( int i = 0; i < _descriptors.size(); i++ ) - { - JDocDescriptor jdd - = _descriptors.get( i ); + for (int i = 0; i < _descriptors.size(); i++) { + JDocDescriptor jdd = _descriptors.get(i); - short compare = jdesc.compareTo( jdd ); + short compare = jdesc.compareTo(jdd); - switch ( compare ) - { + switch (compare) { case 0: // equal - _descriptors.add( i + 1, jdesc ); + _descriptors.add(i + 1, jdesc); return; - case -1: //-- less than - _descriptors.add( i, jdesc ); + case -1: // -- less than + _descriptors.add(i, jdesc); return; case 1: - //-- keep looking + // -- keep looking break; } } - //-- if we make it here we need to add - _descriptors.add( jdesc ); - - } //-- addException + // -- if we make it here we need to add + _descriptors.add(jdesc); + } // -- addException /** * Appends the comment String to this JDocComment * * @param comment the comment to append */ - public void appendComment( String comment ) - { - _comment.append( comment ); - } //-- appendComment + public void appendComment(String comment) { + _comment.append(comment); + } // -- appendComment /** * Returns the String value of this JDocComment. * * @return the String value of the JDocComment. */ - public String getComment() - { + public String getComment() { return _comment.toString(); - } //-- getComment + } // -- getComment /** * Returns an enumeration of the parameters of this JDocComment * * @return an enumeration of the parameters of this JDocComment */ - public Enumeration getDescriptors() - { - return Collections.enumeration( _descriptors ); - } //-- getDescriptors + public Enumeration getDescriptors() { + return Collections.enumeration(_descriptors); + } // -- getDescriptors /** * Returns the length of the comment * * @return the length of the comment */ - public int getLength() - { + public int getLength() { return _comment.length(); - } //-- getLength + } // -- getLength /** * Returns the Parameter Descriptor associated with the @@ -194,76 +178,63 @@ public int getLength() * @return the Parameter Descriptor associated with the * given name */ - public JDocDescriptor getParamDescriptor( String name ) - { - if ( name == null ) return null; + public JDocDescriptor getParamDescriptor(String name) { + if (name == null) return null; - for ( JDocDescriptor jdd : _descriptors ) - { - if ( jdd.getType() == JDocDescriptor.PARAM ) - { - if ( name.equals( jdd.getName() ) ) - return jdd; + for (JDocDescriptor jdd : _descriptors) { + if (jdd.getType() == JDocDescriptor.PARAM) { + if (name.equals(jdd.getName())) return jdd; } } return null; - - } //-- getParamDescriptor - + } // -- getParamDescriptor /** * prints this JavaDoc comment using the given JSourceWriter * * @param jsw the JSourceWriter to print to */ - public void print( JSourceWriter jsw ) - { + public void print(JSourceWriter jsw) { - //-- I reuse JComment for printing - JComment jComment = new JComment( JComment.JAVADOC_STYLE ); + // -- I reuse JComment for printing + JComment jComment = new JComment(JComment.JAVADOC_STYLE); - jComment.setComment( _comment.toString() ); + jComment.setComment(_comment.toString()); - //-- force a separating "*" for readability - if ( _descriptors.size() > 0 ) - { - jComment.appendComment( "\n" ); + // -- force a separating "*" for readability + if (_descriptors.size() > 0) { + jComment.appendComment("\n"); } - for ( int i = 0; i < _descriptors.size(); i++ ) - { - jComment.appendComment( "\n" ); - jComment.appendComment( _descriptors.get( i ).toString() ); + for (int i = 0; i < _descriptors.size(); i++) { + jComment.appendComment("\n"); + jComment.appendComment(_descriptors.get(i).toString()); } - jComment.print( jsw ); - } //-- print + jComment.print(jsw); + } // -- print /** * Sets the comment String of this JDocComment * * @param comment the comment String of this JDocComment */ - public void setComment( String comment ) - { - _comment.setLength( 0 ); - _comment.append( comment ); - } //-- setComment + public void setComment(String comment) { + _comment.setLength(0); + _comment.append(comment); + } // -- setComment /** * Returns the String representation of this Java Doc Comment * * @return the String representation of this Java Doc Comment */ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( "/**\n" ); - sb.append( " * " ); + sb.append("/**\n"); + sb.append(" * "); - sb.append( " */\n" ); + sb.append(" */\n"); return sb.toString(); - } //-- toString - -} //-- JDocComment - + } // -- toString +} // -- JDocComment diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocDescriptor.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocDescriptor.java index 161378546..51bc5757a 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocDescriptor.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocDescriptor.java @@ -42,8 +42,6 @@ * * $Id$ */ - - package org.codehaus.modello.plugin.java.javasource; /* @@ -73,20 +71,17 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JDocDescriptor -{ +public class JDocDescriptor { /** * The default version string **/ - //-- separated using "+" so that CVS doesn't expand - public static final String DEFAULT_VERSION = - "$" + "Revision" + "$ $" + "Date" + "$"; - + // -- separated using "+" so that CVS doesn't expand + public static final String DEFAULT_VERSION = "$" + "Revision" + "$ $" + "Date" + "$"; - //-- These are listed in order of how they should - //-- appear in a JavaDoc list, so the numbers - //-- are important...see #compareTo + // -- These are listed in order of how they should + // -- appear in a JavaDoc list, so the numbers + // -- are important...see #compareTo /** * The param descriptor (param) **/ @@ -107,19 +102,16 @@ public class JDocDescriptor **/ public static final short AUTHOR = 3; - /** * the version descriptor (version) **/ public static final short VERSION = 4; - /** * The reference descriptor (see) **/ public static final short REFERENCE = 5; - private String description = null; private String name = null; private short type = -1; @@ -127,22 +119,20 @@ public class JDocDescriptor /** * Creates a new JDocDescriptor **/ - private JDocDescriptor( short type ) - { + private JDocDescriptor(short type) { this.type = type; - } //-- JDocDescriptor + } // -- JDocDescriptor /** * Creates a new JDocDescriptor * @param name the name string for this descriptor * @param desc the description string for this descriptor **/ - private JDocDescriptor( short type, String name, String desc ) - { + private JDocDescriptor(short type, String name, String desc) { this.type = type; this.name = name; this.description = desc; - } //-- JDocDescriptor + } // -- JDocDescriptor /** * Compares the type of this JDocDescriptor with the given descriptor. @@ -152,11 +142,10 @@ private JDocDescriptor( short type, String name, String desc ) * this descriptor is greater than the given descriptor, or -1 if the * type of this descriptor is less than the given descriptor **/ - protected short compareTo( JDocDescriptor jdd ) - { + protected short compareTo(JDocDescriptor jdd) { short jddType = jdd.getType(); - if ( jddType == this.type ) return 0; + if (jddType == this.type) return 0; // The ordering is as follows // #param @@ -165,37 +154,33 @@ protected short compareTo( JDocDescriptor jdd ) // #version // #see (reference) // - return (short) ( ( jddType < this.type ) ? 1 : -1 ); - - } //-- compareTo + return (short) ((jddType < this.type) ? 1 : -1); + } // -- compareTo /** * Creates a new author descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createAuthorDesc() - { - return new JDocDescriptor( AUTHOR ); - } //-- createAuthorDesc + public static JDocDescriptor createAuthorDesc() { + return new JDocDescriptor(AUTHOR); + } // -- createAuthorDesc /** * Creates a new author descriptor * @param name the author name string * @return the new JDocDescriptor **/ - public static JDocDescriptor createAuthorDesc( String name ) - { - return new JDocDescriptor( AUTHOR, name, null ); - } //-- createAuthorDesc + public static JDocDescriptor createAuthorDesc(String name) { + return new JDocDescriptor(AUTHOR, name, null); + } // -- createAuthorDesc /** * Creates a new exception descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createExceptionDesc() - { - return new JDocDescriptor( EXCEPTION ); - } //-- createExceptionDesc + public static JDocDescriptor createExceptionDesc() { + return new JDocDescriptor(EXCEPTION); + } // -- createExceptionDesc /** * Creates a new exception descriptor @@ -203,21 +188,17 @@ public static JDocDescriptor createExceptionDesc() * @param desc the description of when the exception is called * @return the new JDocDescriptor **/ - public static JDocDescriptor createExceptionDesc - ( String name, String desc ) - { - return new JDocDescriptor( EXCEPTION, name, desc ); - } //-- createExceptionDesc - + public static JDocDescriptor createExceptionDesc(String name, String desc) { + return new JDocDescriptor(EXCEPTION, name, desc); + } // -- createExceptionDesc /** * Creates a new param descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createParamDesc() - { - return new JDocDescriptor( PARAM ); - } //-- createParamDesc + public static JDocDescriptor createParamDesc() { + return new JDocDescriptor(PARAM); + } // -- createParamDesc /** * Creates a new param descriptor @@ -225,77 +206,68 @@ public static JDocDescriptor createParamDesc() * @param desc the param description string * @return the new JDocDescriptor **/ - public static JDocDescriptor createParamDesc( String name, String desc ) - { - return new JDocDescriptor( PARAM, name, desc ); - } //-- createParamDesc - + public static JDocDescriptor createParamDesc(String name, String desc) { + return new JDocDescriptor(PARAM, name, desc); + } // -- createParamDesc /** * Creates a new reference descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createReferenceDesc() - { - return new JDocDescriptor( REFERENCE ); - } //-- createReferenceDesc + public static JDocDescriptor createReferenceDesc() { + return new JDocDescriptor(REFERENCE); + } // -- createReferenceDesc /** * Creates a new reference descriptor * @param name the reference name string * @return the new JDocDescriptor **/ - public static JDocDescriptor createReferenceDesc( String name ) - { - return new JDocDescriptor( REFERENCE, name, null ); - } //-- createReferenceDesc + public static JDocDescriptor createReferenceDesc(String name) { + return new JDocDescriptor(REFERENCE, name, null); + } // -- createReferenceDesc /** * Creates a new return descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createReturnDesc() - { - return new JDocDescriptor( RETURN ); - } //-- createReferenceDesc + public static JDocDescriptor createReturnDesc() { + return new JDocDescriptor(RETURN); + } // -- createReferenceDesc /** * Creates a new return descriptor * @param desc the return description * @return the new JDocDescriptor **/ - public static JDocDescriptor createReturnDesc( String desc ) - { - return new JDocDescriptor( RETURN, null, desc ); - } //-- createReturnDesc + public static JDocDescriptor createReturnDesc(String desc) { + return new JDocDescriptor(RETURN, null, desc); + } // -- createReturnDesc /** * Creates a new version descriptor * @return the new JDocDescriptor **/ - public static JDocDescriptor createVersionDesc() - { - return new JDocDescriptor( VERSION ); - } //-- createVersionDesc + public static JDocDescriptor createVersionDesc() { + return new JDocDescriptor(VERSION); + } // -- createVersionDesc /** * Creates a new version descriptor * @param version the version string * @return the new JDocDescriptor **/ - public static JDocDescriptor createVersionDesc( String version ) - { - return new JDocDescriptor( VERSION, null, version ); - } //-- createVersionDesc + public static JDocDescriptor createVersionDesc(String version) { + return new JDocDescriptor(VERSION, null, version); + } // -- createVersionDesc /** * Returns the description String for this descriptor * @return the description string for this descriptor **/ - public String getDescription() - { + public String getDescription() { return description; - } //-- getDescription + } // -- getDescription /** * Returns the name of the object being described. This @@ -308,29 +280,25 @@ public String getDescription() * * @return the name of the object being described. This **/ - public String getName() - { + public String getName() { return name; - } //-- getName + } // -- getName /** * Returns the type of this JDocDescriptor * @return the type of this JDocDescriptor **/ - public short getType() - { + public short getType() { return this.type; - } //-- getType + } // -- getType /** * Sets the description String for this descriptor * @param desc the description of the object being described **/ - public void setDescription( String desc ) - { + public void setDescription(String desc) { this.description = desc; - } //-- setDescription - + } // -- setDescription /** * Sets the name value of the JavaDoc field. This is @@ -343,57 +311,51 @@ public void setDescription( String desc ) * * @param name the name value of the JavaDoc field **/ - public void setName( String name ) - { + public void setName(String name) { this.name = name; - } //-- setName + } // -- setName /** * Returns the String representation of this JDocDescriptor * @return the String representation of this JDocDescriptor **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); boolean allowName = true; - switch ( type ) - { + switch (type) { case AUTHOR: - sb.append( "@author" ); + sb.append("@author"); break; case EXCEPTION: - sb.append( "@throws" ); + sb.append("@throws"); break; case PARAM: - sb.append( "@param" ); + sb.append("@param"); break; case REFERENCE: - sb.append( "@see" ); + sb.append("@see"); break; case RETURN: - sb.append( "@return" ); + sb.append("@return"); break; case VERSION: allowName = false; - sb.append( "@version" ); + sb.append("@version"); break; default: break; } - if ( ( name != null ) && allowName ) - { - sb.append( ' ' ); - sb.append( name ); + if ((name != null) && allowName) { + sb.append(' '); + sb.append(name); } - if ( description != null ) - { - sb.append( ' ' ); - sb.append( description ); + if (description != null) { + sb.append(' '); + sb.append(description); } return sb.toString(); - } //-- toString - -} //-- JDocDescriptor + } // -- toString +} // -- JDocDescriptor diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JField.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JField.java index 0bfe24f9f..cd7288a50 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JField.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JField.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -75,8 +74,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JField implements JMember -{ +public class JField implements JMember { /** * The set of modifiers for this JField @@ -98,108 +96,94 @@ public class JField implements JMember **/ private JClass declaringClass = null; - public JField( JType type, String name ) - { + public JField(JType type, String name) { - setName( name ); + setName(name); this.type = type; this.modifiers = new JModifiers(); this.modifiers.makePrivate(); comment = new JDocComment(); - comment.appendComment( "Field " + name + "." ); + comment.appendComment("Field " + name + "."); annotations = new JAnnotations(); - } //-- JField - + } // -- JField /** * Returns the comment describing this member. * @return the comment describing this member, or * null if no comment has been set. **/ - public JDocComment getComment() - { + public JDocComment getComment() { return this.comment; - } //-- getComment - + } // -- getComment /** * Returns the class in which this JField has been declared * @return the class in which this JField has been declared **/ - public JClass getDeclaringClass() - { + public JClass getDeclaringClass() { return this.declaringClass; - } //-- getDeclaringClass + } // -- getDeclaringClass /** * Returns the initialization String for this JField * @return the initialization String for this JField, * or null if no initialization String was specified. **/ - public String getInitString() - { + public String getInitString() { return initString; - } //-- getInitString - + } // -- getInitString /** * Returns the modifiers for this JField * @return the modifiers for this JField **/ - public JModifiers getModifiers() - { + public JModifiers getModifiers() { return this.modifiers; - } //-- getModifiers + } // -- getModifiers /** * Returns the name of this JField * @return the name of this JField **/ - public String getName() - { + public String getName() { return this.name; - } //-- getName + } // -- getName /** * Returns the JType represting the type of this JField * @return the JClass represting the type of this JField **/ - public JType getType() - { + public JType getType() { return this.type; - } //-- getType + } // -- getType /** * Sets the comment describing this member. * @param comment the JDocComment for this member **/ - public void setComment( JDocComment comment ) - { + public void setComment(JDocComment comment) { this.comment = comment; - } //-- setComment + } // -- setComment /** * Sets the comment describing this member. * @param comment the JDocComment for this member **/ - public void setComment( String comment ) - { - if ( this.comment == null ) - { + public void setComment(String comment) { + if (this.comment == null) { this.comment = new JDocComment(); } - this.comment.setComment( comment ); - } //-- setComment + this.comment.setComment(comment); + } // -- setComment /** * Sets the initialization string for this JField; * Allows some flexibility in declaring default values. * @param init the initialization string for this member. **/ - public void setInitString( String init ) - { + public void setInitString(String init) { this.initString = init; - } //-- setInitString + } // -- setInitString /** * Sets the name of this JField @@ -208,70 +192,55 @@ public void setInitString( String init ) * name is not a valid Java member name, or if a member * with the given name already exists in the declaring class **/ - public void setName( String name ) throws - IllegalArgumentException - { - if ( !JNaming.isValidJavaIdentifier( name ) ) - { + public void setName(String name) throws IllegalArgumentException { + if (!JNaming.isValidJavaIdentifier(name)) { String err = "'" + name + "' is "; - if ( JNaming.isKeyword( name ) ) - err += "a reserved word and may not be used as " - + " a field name."; - else - err += "not a valid Java identifier."; - throw new IllegalArgumentException( err ); + if (JNaming.isKeyword(name)) err += "a reserved word and may not be used as " + " a field name."; + else err += "not a valid Java identifier."; + throw new IllegalArgumentException(err); } this.name = name; - } //-- setName + } // -- setName - public void setModifiers( JModifiers modifiers ) - { + public void setModifiers(JModifiers modifiers) { this.modifiers = modifiers; - } //-- setModifiers + } // -- setModifiers - protected void setDeclaringClass( JClass declaringClass ) - { + protected void setDeclaringClass(JClass declaringClass) { this.declaringClass = declaringClass; - } //-- setDeclaringClass + } // -- setDeclaringClass - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( modifiers.toString() ); - sb.append( ' ' ); - sb.append( type ); - sb.append( ' ' ); - sb.append( name ); + sb.append(modifiers.toString()); + sb.append(' '); + sb.append(type); + sb.append(' '); + sb.append(name); return sb.toString(); - } //-- toString + } // -- toString /** * @return the annotations */ - public JAnnotations getAnnotations() - { + public JAnnotations getAnnotations() { return annotations; } /** * @param annotation the annotation to append */ - public void appendAnnotation( String annotation ) - { - if ( annotations == null ) - { + public void appendAnnotation(String annotation) { + if (annotations == null) { annotations = new JAnnotations(); } - annotations.appendAnnotation( annotation ); + annotations.appendAnnotation(annotation); } /** * @param annotations the annotations to set */ - public void setAnnotations( JAnnotations annotations ) - { + public void setAnnotations(JAnnotations annotations) { this.annotations = annotations; } - -} //-- JField - +} // -- JField diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JInterface.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JInterface.java index 28b70693d..6c2511681 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JInterface.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JInterface.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -83,9 +82,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public final class JInterface extends JStructure -{ - +public final class JInterface extends JStructure { /** * The fields for this JInterface @@ -97,7 +94,6 @@ public final class JInterface extends JStructure */ private List methods = null; - /** * Creates a new JInterface with the given name. * @@ -105,16 +101,13 @@ public final class JInterface extends JStructure * @throws java.lang.IllegalArgumentException when the given name * is not a valid Class name. **/ - public JInterface( String name ) - throws IllegalArgumentException - { - super( name ); + public JInterface(String name) throws IllegalArgumentException { + super(name); methods = new ArrayList(); - //-- initialize default Java doc - getJDocComment().appendComment( "Interface " + getLocalName() + "." ); - - } //-- JInterface + // -- initialize default Java doc + getJDocComment().appendComment("Interface " + getLocalName() + "."); + } // -- JInterface /** * Adds the given JField to this JStructure. @@ -129,42 +122,35 @@ public JInterface( String name ) * @exception java.lang.IllegalArgumentException when the given * JField has a name of an existing JField */ - public void addField( JField jField ) - throws IllegalArgumentException - { - if ( jField == null ) - { - throw new IllegalArgumentException( "argument 'jField' cannot be null" ); + public void addField(JField jField) throws IllegalArgumentException { + if (jField == null) { + throw new IllegalArgumentException("argument 'jField' cannot be null"); } String name = jField.getName(); - //-- check for duplicate field name - if ( ( fields != null ) && ( fields.get( name ) != null ) ) - { + // -- check for duplicate field name + if ((fields != null) && (fields.get(name) != null)) { String err = "duplicate name found: " + name; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - //-- check for proper modifiers + // -- check for proper modifiers JModifiers modifiers = jField.getModifiers(); - if ( !modifiers.isStatic() ) - { - throw new IllegalArgumentException( "Fields added to a JInterface must be static." ); + if (!modifiers.isStatic()) { + throw new IllegalArgumentException("Fields added to a JInterface must be static."); } - if ( modifiers.isPrivate() ) - { - throw new IllegalArgumentException( "Fields added to a JInterface must not be private." ); + if (modifiers.isPrivate()) { + throw new IllegalArgumentException("Fields added to a JInterface must not be private."); } - //-- only initialize fields if we need it, many interfaces - //-- don't contain any fields, no need to waste space - if ( fields == null ) - { - fields = new LinkedHashMap<>( 3 ); + // -- only initialize fields if we need it, many interfaces + // -- don't contain any fields, no need to waste space + if (fields == null) { + fields = new LinkedHashMap<>(3); } - fields.put( name, jField ); + fields.put(name, jField); } /** @@ -180,25 +166,16 @@ public void addField( JField jField ) * JMember has the same name of an existing JField * or JMethod respectively. */ - public void addMember( JMember jMember ) - throws IllegalArgumentException - { - if ( jMember == null ) - { - throw new IllegalArgumentException( "argument 'jMember' may not be null." ); - } - if ( jMember instanceof JField ) - { - addField( (JField) jMember ); + public void addMember(JMember jMember) throws IllegalArgumentException { + if (jMember == null) { + throw new IllegalArgumentException("argument 'jMember' may not be null."); } - else - { - throw new IllegalArgumentException( "invalid member for JInterface: " + - jMember.toString() ); + if (jMember instanceof JField) { + addField((JField) jMember); + } else { + throw new IllegalArgumentException("invalid member for JInterface: " + jMember.toString()); } - - } //-- addMember - + } // -- addMember /** * Adds the given JMethodSignature to this JClass @@ -208,64 +185,53 @@ public void addMember( JMember jMember ) * JMethodSignature conflicts with an existing * method signature. */ - public void addMethod( JMethodSignature jMethodSig ) - throws IllegalArgumentException - { - if ( jMethodSig == null ) - { + public void addMethod(JMethodSignature jMethodSig) throws IllegalArgumentException { + if (jMethodSig == null) { String err = "The JMethodSignature cannot be null."; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - //-- check method name and signatures *add later* + // -- check method name and signatures *add later* - //-- keep method list sorted for esthetics when printing - //-- START SORT :-) + // -- keep method list sorted for esthetics when printing + // -- START SORT :-) boolean added = false; -// short modifierVal = 0; + // short modifierVal = 0; JModifiers modifiers = jMethodSig.getModifiers(); - for ( int i = 0; i < methods.size(); i++ ) - { - JMethodSignature tmp = methods.get( i ); - //-- first compare modifiers - if ( tmp.getModifiers().isProtected() ) - { - if ( !modifiers.isProtected() ) - { - methods.add( i, jMethodSig ); + for (int i = 0; i < methods.size(); i++) { + JMethodSignature tmp = methods.get(i); + // -- first compare modifiers + if (tmp.getModifiers().isProtected()) { + if (!modifiers.isProtected()) { + methods.add(i, jMethodSig); added = true; break; } } - //-- compare names - if ( jMethodSig.getName().compareTo( tmp.getName() ) < 0 ) - { - methods.add( i, jMethodSig ); + // -- compare names + if (jMethodSig.getName().compareTo(tmp.getName()) < 0) { + methods.add(i, jMethodSig); added = true; break; } } - //-- END SORT - if ( !added ) methods.add( jMethodSig ); + // -- END SORT + if (!added) methods.add(jMethodSig); - //-- check return type to make sure it's included in the - //-- import list + // -- check return type to make sure it's included in the + // -- import list JType jType = jMethodSig.getReturnType(); - if ( jType != null ) - { - while ( jType.isArray() ) - jType = jType.getComponentType(); + if (jType != null) { + while (jType.isArray()) jType = jType.getComponentType(); - if ( !jType.isPrimitive() ) - addImport( jType.getName() ); + if (!jType.isPrimitive()) addImport(jType.getName()); } - //-- check exceptions + // -- check exceptions JClass[] exceptions = jMethodSig.getExceptions(); - for ( JClass exception : exceptions ) - { - addImport( exception.getName() ); + for (JClass exception : exceptions) { + addImport(exception.getName()); } - } //-- addMethod + } // -- addMethod /** * Returns the field with the given name, or null if no field @@ -275,36 +241,31 @@ public void addMethod( JMethodSignature jMethodSig ) * @return the field with the given name, or null if no field * was found with the given name. */ - public JField getField( String name ) - { - if ( fields == null ) return null; - return (JField) fields.get( name ); - } //-- getField + public JField getField(String name) { + if (fields == null) return null; + return (JField) fields.get(name); + } // -- getField /** * Returns an array of all the JFields of this JStructure * * @return an array of all the JFields of this JStructure */ - public JField[] getFields() - { - if ( fields == null ) - { + public JField[] getFields() { + if (fields == null) { return new JField[0]; } - return fields.values().toArray( new JField[0] ); - } //-- getFields - + return fields.values().toArray(new JField[0]); + } // -- getFields /** * Returns an array of all the JMethodSignatures of this JInterface. * * @return an array of all the JMethodSignatures of this JInterface. **/ - public JMethodSignature[] getMethods() - { - return methods.toArray( new JMethodSignature[0] ); - } //-- getMethods + public JMethodSignature[] getMethods() { + return methods.toArray(new JMethodSignature[0]); + } // -- getMethods /** * Returns the JMethodSignature with the given name, @@ -315,14 +276,12 @@ public JMethodSignature[] getMethods() * from. * @return the JMethodSignature, or null if not found. **/ - public JMethodSignature getMethod( String name, int startIndex ) - { - for ( JMethodSignature jMethod : methods ) - { - if ( jMethod.getName().equals( name ) ) return jMethod; + public JMethodSignature getMethod(String name, int startIndex) { + for (JMethodSignature jMethod : methods) { + if (jMethod.getName().equals(name)) return jMethod; } return null; - } //-- getMethod + } // -- getMethod /** * Returns the JMethodSignature at the given index. @@ -330,180 +289,157 @@ public JMethodSignature getMethod( String name, int startIndex ) * @param index the index of the JMethodSignature to return. * @return the JMethodSignature at the given index. **/ - public JMethodSignature getMethod( int index ) - { - return methods.get( index ); - } //-- getMethod - + public JMethodSignature getMethod(int index) { + return methods.get(index); + } // -- getMethod /** * Prints the source code for this JInterface to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] */ - public void print( JSourceWriter jsw ) - { - print( jsw, false ); + public void print(JSourceWriter jsw) { + print(jsw, false); } /** * Prints the source code for this JInterface to the given JSourceWriter * * @param jsw the JSourceWriter to print to. [May not be null] - * @param classOnly whether the header, package and imports should be printed too + * @param classOnly whether the header, package and imports should be printed too */ - public void print( JSourceWriter jsw, boolean classOnly ) - { + public void print(JSourceWriter jsw, boolean classOnly) { - if ( jsw == null ) - { - throw new IllegalArgumentException( "argument 'jsw' should not be null." ); + if (jsw == null) { + throw new IllegalArgumentException("argument 'jsw' should not be null."); } StringBuilder buffer = new StringBuilder(); - if ( !classOnly ) - { - printHeader( jsw ); - printPackageDeclaration( jsw ); - printImportDeclarations( jsw ); + if (!classOnly) { + printHeader(jsw); + printPackageDeclaration(jsw); + printImportDeclarations(jsw); } - //------------/ - //- Java Doc -/ - //------------/ + // ------------/ + // - Java Doc -/ + // ------------/ - getJDocComment().print( jsw ); + getJDocComment().print(jsw); JAnnotations annotations = getAnnotations(); - if ( annotations != null ) annotations.print( jsw ); + if (annotations != null) annotations.print(jsw); - //-- print class information - //-- we need to add some JavaDoc API adding comments + // -- print class information + // -- we need to add some JavaDoc API adding comments - buffer.setLength( 0 ); + buffer.setLength(0); JModifiers modifiers = getModifiers(); - if ( modifiers.isPrivate() ) - { - buffer.append( "private " ); - } - else if ( modifiers.isPublic() ) - { - buffer.append( "public " ); + if (modifiers.isPrivate()) { + buffer.append("private "); + } else if (modifiers.isPublic()) { + buffer.append("public "); } - if ( modifiers.isAbstract() ) - { - buffer.append( "abstract " ); + if (modifiers.isAbstract()) { + buffer.append("abstract "); } - buffer.append( "interface " ); - buffer.append( getLocalName() ); - jsw.writeln( buffer.toString() ); - buffer.setLength( 0 ); + buffer.append("interface "); + buffer.append(getLocalName()); + jsw.writeln(buffer.toString()); + buffer.setLength(0); jsw.indent(); - if ( getInterfaceCount() > 0 ) - { + if (getInterfaceCount() > 0) { Enumeration e = getInterfaces(); - buffer.append( "extends " ); - while ( e.hasMoreElements() ) - { - buffer.append( e.nextElement() ); - if ( e.hasMoreElements() ) buffer.append( ", " ); + buffer.append("extends "); + while (e.hasMoreElements()) { + buffer.append(e.nextElement()); + if (e.hasMoreElements()) buffer.append(", "); } - jsw.writeln( buffer.toString() ); - buffer.setLength( 0 ); + jsw.writeln(buffer.toString()); + buffer.setLength(0); } jsw.unindent(); - jsw.writeln( '{' ); + jsw.writeln('{'); jsw.indent(); - //-- declare static members + // -- declare static members - if ( fields != null ) - { - if ( fields.size() > 0 ) - { + if (fields != null) { + if (fields.size() > 0) { jsw.writeln(); - jsw.writeln( " //--------------------------/" ); - jsw.writeln( " //- Class/Member Variables -/" ); - jsw.writeln( "//--------------------------/" ); + jsw.writeln(" //--------------------------/"); + jsw.writeln(" //- Class/Member Variables -/"); + jsw.writeln("//--------------------------/"); jsw.writeln(); } - - for ( JField jField : fields.values() ) - { - //-- print Java comment + for (JField jField : fields.values()) { + // -- print Java comment JDocComment comment = jField.getComment(); - if ( comment != null ) comment.print( jsw ); + if (comment != null) comment.print(jsw); // -- print member - jsw.write( jField.getModifiers().toString() ); - jsw.write( ' ' ); + jsw.write(jField.getModifiers().toString()); + jsw.write(' '); JType type = jField.getType(); String typeName = type.toString(); - //-- for esthetics use short name in some cases - if ( typeName.equals( toString() ) ) - { + // -- for esthetics use short name in some cases + if (typeName.equals(toString())) { typeName = type.getLocalName(); } - jsw.write( typeName ); - jsw.write( ' ' ); - jsw.write( jField.getName() ); + jsw.write(typeName); + jsw.write(' '); + jsw.write(jField.getName()); String init = jField.getInitString(); - if ( init != null ) - { - jsw.write( " = " ); - jsw.write( init ); + if (init != null) { + jsw.write(" = "); + jsw.write(init); } - jsw.writeln( ';' ); + jsw.writeln(';'); jsw.writeln(); } } - //-- print method signatures + // -- print method signatures - if ( methods.size() > 0 ) - { + if (methods.size() > 0) { jsw.writeln(); - jsw.writeln( " //-----------/" ); - jsw.writeln( " //- Methods -/" ); - jsw.writeln( "//-----------/" ); + jsw.writeln(" //-----------/"); + jsw.writeln(" //- Methods -/"); + jsw.writeln("//-----------/"); jsw.writeln(); } - for ( JMethodSignature signature : methods ) - { - signature.print( jsw ); - jsw.writeln( ';' ); + for (JMethodSignature signature : methods) { + signature.print(jsw); + jsw.writeln(';'); } - for ( String sourceCodeEntry : sourceCodeEntries ) - { - jsw.writeln( sourceCodeEntry ); + for (String sourceCodeEntry : sourceCodeEntries) { + jsw.writeln(sourceCodeEntry); } jsw.unindent(); - jsw.writeln( '}' ); + jsw.writeln('}'); jsw.flush(); jsw.close(); - } //-- printSource + } // -- printSource private List sourceCodeEntries = new ArrayList(); - public void addSourceCode( String sourceCode ) - { - sourceCodeEntries.add( sourceCode ); + public void addSourceCode(String sourceCode) { + sourceCodeEntries.add(sourceCode); } - -} //-- JInterface +} // -- JInterface diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMapType.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMapType.java index db2169948..000d35d1c 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMapType.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMapType.java @@ -30,9 +30,7 @@ * @author Simone Tripodi * @since 1.8 */ -public final class JMapType - extends JComponentizedType -{ +public final class JMapType extends JComponentizedType { // -------------------------------------------------------------------------- /** Name of the actual map instance to be used, e.g. java.util.ArrayList. */ @@ -47,9 +45,8 @@ public final class JMapType * @param componentType Component type. * @param useJava50 True if Java 5.0 should be used. */ - public JMapType( final String typeName, final JType componentType, final boolean useJava50 ) - { - super( typeName, componentType, useJava50 ); + public JMapType(final String typeName, final JType componentType, final boolean useJava50) { + super(typeName, componentType, useJava50); } /** @@ -60,10 +57,9 @@ public JMapType( final String typeName, final JType componentType, final boolean * @param componentType Component type. * @param useJava50 True if Java 5.0 should be used. */ - public JMapType( final String typeName, final String instanceName, final JType componentType, - final boolean useJava50 ) - { - super( typeName, componentType, useJava50 ); + public JMapType( + final String typeName, final String instanceName, final JType componentType, final boolean useJava50) { + super(typeName, componentType, useJava50); _instanceName = instanceName; } @@ -74,29 +70,22 @@ public JMapType( final String typeName, final String instanceName, final JType c * * @return The instance name of this map type. */ - public String getInstanceName() - { - if ( ModelDefault.PROPERTIES.equals( getName() ) ) - { + public String getInstanceName() { + if (ModelDefault.PROPERTIES.equals(getName())) { return _instanceName; } - if ( _instanceName != null ) - { + if (_instanceName != null) { String instance; - int separator = _instanceName.indexOf( "()" ); - if ( separator != -1 ) - { - instance = _instanceName.substring( 0, separator ); - } - else - { + int separator = _instanceName.indexOf("()"); + if (separator != -1) { + instance = _instanceName.substring(0, separator); + } else { instance = _instanceName; } - if ( isUseJava50() ) - { + if (isUseJava50()) { return instance + "()"; } @@ -109,15 +98,12 @@ public String getInstanceName() /** * @return the String representation of this JType. */ - public String toString() - { - if ( ModelDefault.PROPERTIES.equals( getName() ) ) - { + public String toString() { + if (ModelDefault.PROPERTIES.equals(getName())) { return getName(); } - if ( isUseJava50() ) - { + if (isUseJava50()) { return getName() + ""; } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMember.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMember.java index e53075a9a..a4702c462 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMember.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMember.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -75,14 +74,13 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -interface JMember -{ +interface JMember { /** * Returns the class in which this JMember has been declared * @return the class in which this JMember has been declared **/ - //public JClass getDeclaringClass(); + // public JClass getDeclaringClass(); /** * Returns the modifiers for this JMember @@ -97,6 +95,4 @@ interface JMember public String getName(); public JAnnotations getAnnotations(); - -} //-- JMember - +} // -- JMember diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethod.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethod.java index e1ac27142..d7d37399f 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethod.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethod.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -79,9 +78,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JMethod implements JMember -{ - +public class JMethod implements JMember { /** * The set of classes that contain this JMethod. @@ -115,10 +112,9 @@ public class JMethod implements JMember * * @param name, the method name. Must not be null. **/ - public JMethod( String name ) - { - this( name, null, null ); - } //-- JMethod + public JMethod(String name) { + this(name, null, null); + } // -- JMethod /** * Creates a new JMethod with the given name and returnType. @@ -128,10 +124,9 @@ public JMethod( String name ) * @param returnType the return type of the method. May be null. * @deprecated removed in future version of javasource **/ - public JMethod( JType returnType, String name ) - { - this( name, returnType, null ); - } //-- JMethod + public JMethod(JType returnType, String name) { + this(name, returnType, null); + } // -- JMethod /** * Creates a new JMethod with the given name and returnType. @@ -143,30 +138,24 @@ public JMethod( JType returnType, String name ) * null, a default (and mostly useless) javadoc comment will be * generated. **/ - public JMethod( final String name, final JType returnType, final String returnDoc ) - { - if ( ( name == null ) || ( name.length() == 0 ) ) - { + public JMethod(final String name, final JType returnType, final String returnDoc) { + if ((name == null) || (name.length() == 0)) { String err = "The method name must not be null or zero-length"; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - _classes = new ArrayList( 1 ); + _classes = new ArrayList(1); this.source = new JSourceCode(); - _signature = new JMethodSignature( name, returnType ); + _signature = new JMethodSignature(name, returnType); this.jdc = _signature.getJDocComment(); - jdc.appendComment( "Method " + name + "." ); - - //-- create comment - if ( returnType != null ) - { - if ( returnDoc != null && returnDoc.length() > 0 ) - { - jdc.addDescriptor( JDocDescriptor.createReturnDesc( returnDoc ) ); - } - else - { - jdc.addDescriptor( JDocDescriptor.createReturnDesc( returnType.getLocalName() ) ); + jdc.appendComment("Method " + name + "."); + + // -- create comment + if (returnType != null) { + if (returnDoc != null && returnDoc.length() > 0) { + jdc.addDescriptor(JDocDescriptor.createReturnDesc(returnDoc)); + } else { + jdc.addDescriptor(JDocDescriptor.createReturnDesc(returnType.getLocalName())); } } } @@ -176,11 +165,9 @@ public JMethod( final String name, final JType returnType, final String returnDo * * @param exp the JClass representing the Exception **/ - public void addException( JClass exp ) - { - _signature.addException( exp ); - } //-- addException - + public void addException(JClass exp) { + _signature.addException(exp); + } // -- addException /** * Adds the given parameter to this JMethod's list of parameters. @@ -190,28 +177,25 @@ public void addException( JClass exp ) * @throws java.lang.IllegalArgumentException when a parameter already * exists for this Method with the same name as the new parameter **/ - public void addParameter( JParameter parameter ) - throws IllegalArgumentException - { - _signature.addParameter( parameter ); - } //-- addParameter + public void addParameter(JParameter parameter) throws IllegalArgumentException { + _signature.addParameter(parameter); + } // -- addParameter /** * Returns the JDocComment describing this member. * @return the JDocComment describing this member. **/ - public JDocComment getJDocComment() - { + public JDocComment getJDocComment() { return this.jdc; - } //-- getJDocComment + } // -- getJDocComment /** * Returns the class in which this JMember has been declared * @return the class in which this JMember has been declared ** - public JClass getDeclaringClass() { - return _declaringClass; - } //-- getDeclaringClass + * public JClass getDeclaringClass() { + * return _declaringClass; + * } //-- getDeclaringClass */ /** @@ -219,31 +203,27 @@ public JClass getDeclaringClass() { * * @return the exceptions that this JMember throws. **/ - public JClass[] getExceptions() - { + public JClass[] getExceptions() { return _signature.getExceptions(); - } //-- getExceptions - + } // -- getExceptions /** * Returns the modifiers for this JMember. * * @return the modifiers for this JMember. **/ - public JModifiers getModifiers() - { + public JModifiers getModifiers() { return _signature.getModifiers(); - } //-- getModifiers + } // -- getModifiers /** * Returns the name of this JMember. * * @return the name of this JMember. **/ - public String getName() - { + public String getName() { return _signature.getName(); - } //-- getName + } // -- getName /** * Returns the JParameter at the given index. @@ -251,10 +231,9 @@ public String getName() * @param index the index of the JParameter to return. * @return the JParameter at the given index. **/ - public JParameter getParameter( int index ) - { - return _signature.getParameter( index ); - } //-- getParameter + public JParameter getParameter(int index) { + return _signature.getParameter(index); + } // -- getParameter /** * Returns the set of JParameters for this JMethod. @@ -264,40 +243,36 @@ public JParameter getParameter( int index ) * * @return the set of JParameters for this JMethod **/ - public JParameter[] getParameters() - { + public JParameter[] getParameters() { return _signature.getParameters(); - } //-- getParameters + } // -- getParameters /** * Returns the JType that represents the return type of the method. * * @return the JType that represents the return type of the method. **/ - public JType getReturnType() - { + public JType getReturnType() { return _signature.getReturnType(); - } //-- getReturnType + } // -- getReturnType /** * Returns the JMethodSignature for this JMethod. * * @return the JMethodSignature for this JMethod. **/ - public JMethodSignature getSignature() - { + public JMethodSignature getSignature() { return _signature; - } //-- getSignature + } // -- getSignature /** * Returns the JSourceCode for the method body. * * @return the JSourceCode for the method body. **/ - public JSourceCode getSourceCode() - { + public JSourceCode getSourceCode() { return this.source; - } //-- getSourceCode + } // -- getSourceCode /** * Sets the comment describing this member. The comment @@ -307,10 +282,9 @@ public JSourceCode getSourceCode() * @param comment the comment for this member * @see #getJDocComment **/ - public void setComment( String comment ) - { - jdc.setComment( comment ); - } //-- setComment + public void setComment(String comment) { + jdc.setComment(comment); + } // -- setComment /** * Sets the JModifiers for this JMethod. This @@ -322,10 +296,9 @@ public void setComment( String comment ) * * @param modifiers the JModifiers to set. **/ - public void setModifiers( JModifiers modifiers ) - { - _signature.setModifiers( modifiers ); - } //-- setModifiers + public void setModifiers(JModifiers modifiers) { + _signature.setModifiers(modifiers); + } // -- setModifiers /** * Sets the given string as the source code (method body) @@ -333,10 +306,9 @@ public void setModifiers( JModifiers modifiers ) * * @param source the String that represents the method body. **/ - public void setSourceCode( String source ) - { - this.source = new JSourceCode( source ); - } //-- setSource + public void setSourceCode(String source) { + this.source = new JSourceCode(source); + } // -- setSource /** * Sets the given JSourceCode as the source code (method body) @@ -344,52 +316,46 @@ public void setSourceCode( String source ) * * @param source the JSourceCode that represents the method body. **/ - public void setSourceCode( JSourceCode source ) - { + public void setSourceCode(JSourceCode source) { this.source = source; - } //-- setSource; + } // -- setSource; /** * Prints this JMethod to the given JSourceWriter. * * @param jsw the JSourceWriter to print to. **/ - public void print( JSourceWriter jsw ) - { + public void print(JSourceWriter jsw) { - //------------/ - //- Java Doc -/ - //------------/ + // ------------/ + // - Java Doc -/ + // ------------/ - jdc.print( jsw ); + jdc.print(jsw); - //--------------------/ + // --------------------/ // - Annotations -/ - //--------------------/ + // --------------------/ JAnnotations annotations = getAnnotations(); - if ( annotations != null ) annotations.print( jsw ); + if (annotations != null) annotations.print(jsw); - //--------------------/ - //- Method Signature -/ - //--------------------/ + // --------------------/ + // - Method Signature -/ + // --------------------/ - _signature.print( jsw, false ); + _signature.print(jsw, false); - if ( _signature.getModifiers().isAbstract() ) - { - jsw.writeln( ";" ); - } - else - { + if (_signature.getModifiers().isAbstract()) { + jsw.writeln(";"); + } else { jsw.writeln(); - jsw.writeln( "{" ); - source.print( jsw ); - jsw.write( "} //-- " ); - jsw.writeln( toString() ); + jsw.writeln("{"); + source.print(jsw); + jsw.write("} //-- "); + jsw.writeln(toString()); } - } //-- print - + } // -- print /** * Returns the String representation of this JMethod, @@ -397,14 +363,13 @@ public void print( JSourceWriter jsw ) * @return the String representation of this JMethod, which * is simply the method prototype **/ - public String toString() - { + public String toString() { return _signature.toString(); - } //-- toString + } // -- toString - //---------------------/ - //- PROTECTED METHODS -/ - //---------------------/ + // ---------------------/ + // - PROTECTED METHODS -/ + // ---------------------/ /** * Adds the given JClass to the set of classes that @@ -413,10 +378,9 @@ public String toString() * @param jClass the JClass to add as one of * the JClasses that contain this method. **/ - protected void addDeclaringClass( JClass jClass ) - { - _classes.add( jClass ); - } //-- addDeclaringClass + protected void addDeclaringClass(JClass jClass) { + _classes.add(jClass); + } // -- addDeclaringClass /** * Removes the given JClass from the set of classes that @@ -425,42 +389,35 @@ protected void addDeclaringClass( JClass jClass ) * @param jClass the JClass to add as one of * the JClasses that contain this method. **/ - protected void removeDeclaringClass( JClass jClass ) - { - _classes.remove( jClass ); - } //-- removeDeclaringClass + protected void removeDeclaringClass(JClass jClass) { + _classes.remove(jClass); + } // -- removeDeclaringClass - protected String[] getParameterClassNames() - { + protected String[] getParameterClassNames() { return _signature.getParameterClassNames(); - } //-- getParameterClassNames + } // -- getParameterClassNames /** * @return the annotations */ - public JAnnotations getAnnotations() - { + public JAnnotations getAnnotations() { return annotations; } /** * @param annotation the annotation to append */ - public void appendAnnotation( String annotation ) - { - if ( annotations == null ) - { + public void appendAnnotation(String annotation) { + if (annotations == null) { annotations = new JAnnotations(); } - annotations.appendAnnotation( annotation ); + annotations.appendAnnotation(annotation); } /** * @param annotations the annotations to set */ - public void setAnnotations( JAnnotations annotations ) - { + public void setAnnotations(JAnnotations annotations) { this.annotations = annotations; } - -} //-- JMember +} // -- JMember diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethodSignature.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethodSignature.java index 853d7a306..5248e0550 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethodSignature.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethodSignature.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -84,8 +83,7 @@ * * @author Keith Visco **/ -public final class JMethodSignature -{ +public final class JMethodSignature { /** * The set of modifiers for this JMethod @@ -102,7 +100,6 @@ public final class JMethodSignature **/ private String name = null; - /** * The list of parameters of this JMethodSignature in declared * order @@ -126,45 +123,41 @@ public final class JMethodSignature * @param name, the method name. Must not be null. * @param returnType the return type of the method. May be null. **/ - public JMethodSignature( String name, JType returnType ) - { + public JMethodSignature(String name, JType returnType) { - if ( ( name == null ) || ( name.length() == 0 ) ) - { + if ((name == null) || (name.length() == 0)) { String err = "The method name must not be null or zero-length"; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } this.jdc = new JDocComment(); this.returnType = returnType; this.name = name; this.modifiers = new JModifiers(); - this.params = new LinkedHashMap<>( 3 ); - this.exceptions = new ArrayList( 1 ); - } //-- JMethodSignature + this.params = new LinkedHashMap<>(3); + this.exceptions = new ArrayList(1); + } // -- JMethodSignature /** * Adds the given Exception to this JMethodSignature's throws clause. * * @param exp the JClass representing the Exception **/ - public void addException( JClass exp ) - { + public void addException(JClass exp) { - if ( exp == null ) return; + if (exp == null) return; - //-- make sure exception is not already added + // -- make sure exception is not already added String expClassName = exp.getName(); - for ( JClass jClass : exceptions ) - { - if ( expClassName.equals( jClass.getName() ) ) return; + for (JClass jClass : exceptions) { + if (expClassName.equals(jClass.getName())) return; } - //-- add exception - exceptions.add( exp ); + // -- add exception + exceptions.add(exp); - //-- create comment - jdc.addDescriptor( JDocDescriptor.createExceptionDesc( expClassName, expClassName + " if any.") ); - } //-- addException + // -- create comment + jdc.addDescriptor(JDocDescriptor.createExceptionDesc(expClassName, expClassName + " if any.")); + } // -- addException /** * Adds the given parameter to this JMethodSignature's list of @@ -176,31 +169,26 @@ public void addException( JClass exp ) * exists for this Method with the same name as the new * parameter. **/ - public void addParameter( JParameter parameter ) - throws IllegalArgumentException - { + public void addParameter(JParameter parameter) throws IllegalArgumentException { - if ( parameter == null ) return; + if (parameter == null) return; String pName = parameter.getName(); - //-- check current params - if ( params.get( pName ) != null ) - { + // -- check current params + if (params.get(pName) != null) { StringBuilder err = new StringBuilder(); - err.append( "A parameter already exists for this method, " ); - err.append( name ); - err.append( ", with the name: " ); - err.append( pName ); - throw new IllegalArgumentException( err.toString() ); + err.append("A parameter already exists for this method, "); + err.append(name); + err.append(", with the name: "); + err.append(pName); + throw new IllegalArgumentException(err.toString()); } + params.put(pName, parameter); - params.put( pName, parameter ); - - //-- create comment - jdc.addDescriptor( JDocDescriptor.createParamDesc( pName, "a " + pName + " object.") ); - - } //-- addParameter + // -- create comment + jdc.addDescriptor(JDocDescriptor.createParamDesc(pName, "a " + pName + " object.")); + } // -- addParameter /** * Returns the exceptions that this JMethodSignature lists @@ -209,40 +197,36 @@ public void addParameter( JParameter parameter ) * @return the exceptions that this JMethodSignature lists * in it's throws clause. **/ - public JClass[] getExceptions() - { - return exceptions.toArray( new JClass[0] ); - } //-- getExceptions + public JClass[] getExceptions() { + return exceptions.toArray(new JClass[0]); + } // -- getExceptions /** * Returns the JDocComment describing this JMethodSignature * * @return the JDocComment describing this JMethodSignature **/ - public JDocComment getJDocComment() - { + public JDocComment getJDocComment() { return this.jdc; - } //-- getJDocComment + } // -- getJDocComment /** * Returns the modifiers for this JMethodSignature. * * @return the modifiers for this JMethodSignature. **/ - public JModifiers getModifiers() - { + public JModifiers getModifiers() { return this.modifiers; - } //-- getModifiers + } // -- getModifiers /** * Returns the name of the method. * * @return the name of the method. **/ - public String getName() - { + public String getName() { return this.name; - } //-- getName + } // -- getName /** * Returns the JParameter at the given index. @@ -250,16 +234,14 @@ public String getName() * @param index the index of the JParameter to return. * @return the JParameter at the given index. **/ - public JParameter getParameter( int index ) - { + public JParameter getParameter(int index) { Iterator> paramIter = params.entrySet().iterator(); Map.Entry selected = null; - for( int i = 0; i <= index; i++) - { + for (int i = 0; i <= index; i++) { selected = paramIter.next(); } return selected.getValue(); - } //-- getParameter + } // -- getParameter /** * Returns the set of JParameters for this JMethodSignature @@ -268,10 +250,9 @@ public JParameter getParameter( int index ) * are the actual references. * @return the set of JParameters for this JMethod **/ - public synchronized JParameter[] getParameters() - { - return params.values().toArray( new JParameter[0] ); - } //-- getParameters + public synchronized JParameter[] getParameters() { + return params.values().toArray(new JParameter[0]); + } // -- getParameters /** * Returns the JType that represents the return type for the @@ -280,11 +261,9 @@ public synchronized JParameter[] getParameters() * @return the JType that represents the return type for the * method signature. **/ - public JType getReturnType() - { + public JType getReturnType() { return returnType; - } //-- getReturnType - + } // -- getReturnType /** * Sets the comment describing this JMethodSignature. @@ -292,22 +271,19 @@ public JType getReturnType() * @param comment the comment for this member * @see #getJDocComment **/ - public void setComment( String comment ) - { - jdc.setComment( comment ); - } //-- setComment - + public void setComment(String comment) { + jdc.setComment(comment); + } // -- setComment /** * Sets the JModifiers for this method signature. * * @param modifiers the JModifiers for this method signature. **/ - public void setModifiers( JModifiers modifiers ) - { + public void setModifiers(JModifiers modifiers) { this.modifiers = modifiers.copy(); - this.modifiers.setFinal( false ); - } //-- setModifiers + this.modifiers.setFinal(false); + } // -- setModifiers /** * Prints the method signature. A semi-colon (end-of-statement @@ -315,10 +291,9 @@ public void setModifiers( JModifiers modifiers ) * * @param jsw the JSourceWriter to print to. **/ - public void print( JSourceWriter jsw ) - { - print( jsw, true ); - } //-- print + public void print(JSourceWriter jsw) { + print(jsw, true); + } // -- print /** * Prints the method signature. A semi-colon (end-of-statement @@ -328,65 +303,55 @@ public void print( JSourceWriter jsw ) * @param printJavaDoc a boolean that when true prints the JDocComment * associated with this method signature. **/ - public void print( JSourceWriter jsw, boolean printJavaDoc ) - { + public void print(JSourceWriter jsw, boolean printJavaDoc) { - //------------/ - //- Java Doc -/ - //------------/ + // ------------/ + // - Java Doc -/ + // ------------/ - if ( printJavaDoc ) jdc.print( jsw ); + if (printJavaDoc) jdc.print(jsw); - //-----------------/ - //- Method Source -/ - //-----------------/ + // -----------------/ + // - Method Source -/ + // -----------------/ - jsw.write( modifiers.toString() ); - if ( modifiers.toString().length() > 0 ) - { - jsw.write( ' ' ); + jsw.write(modifiers.toString()); + if (modifiers.toString().length() > 0) { + jsw.write(' '); } - if ( returnType != null ) - { - jsw.write( returnType ); - } - else - jsw.write( "void" ); - jsw.write( ' ' ); - jsw.write( name ); - jsw.write( '(' ); - - //-- print parameters - if ( params.size() > 0 ) - { - jsw.write( ' ' ); - - Enumeration paramEnum = Collections.enumeration( params.values() ); - jsw.write( paramEnum.nextElement() ); - while( paramEnum.hasMoreElements() ) - { - jsw.write( ", " ); - jsw.write( paramEnum.nextElement() ); + if (returnType != null) { + jsw.write(returnType); + } else jsw.write("void"); + jsw.write(' '); + jsw.write(name); + jsw.write('('); + + // -- print parameters + if (params.size() > 0) { + jsw.write(' '); + + Enumeration paramEnum = Collections.enumeration(params.values()); + jsw.write(paramEnum.nextElement()); + while (paramEnum.hasMoreElements()) { + jsw.write(", "); + jsw.write(paramEnum.nextElement()); } - - jsw.write( ' ' ); + + jsw.write(' '); } - jsw.write( ')' ); + jsw.write(')'); - if ( exceptions.size() > 0 ) - { + if (exceptions.size() > 0) { jsw.writeln(); - jsw.write( " throws " ); - for ( int i = 0; i < exceptions.size(); i++ ) - { - if ( i > 0 ) jsw.write( ", " ); - JClass jClass = exceptions.get( i ); - jsw.write( jClass.getName() ); + jsw.write(" throws "); + for (int i = 0; i < exceptions.size(); i++) { + if (i > 0) jsw.write(", "); + JClass jClass = exceptions.get(i); + jsw.write(jClass.getName()); } } - } //-- print - + } // -- print /** * Returns the String representation of this JMethod, @@ -394,57 +359,47 @@ public void print( JSourceWriter jsw, boolean printJavaDoc ) * @return the String representation of this JMethod, which * is simply the method prototype **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - if ( returnType != null ) - { - sb.append( returnType ); - } - else - sb.append( "void" ); - sb.append( ' ' ); - sb.append( name ); - sb.append( '(' ); - - //-- print parameters - if ( params.size() > 0 ) - { - sb.append( ' ' ); - - Enumeration paramEnum = Collections.enumeration( params.values() ); - sb.append( paramEnum.nextElement().getType().getName() ); - while( paramEnum.hasMoreElements() ) - { - sb.append( ", " ); - sb.append( paramEnum.nextElement().getType().getName() ); + if (returnType != null) { + sb.append(returnType); + } else sb.append("void"); + sb.append(' '); + sb.append(name); + sb.append('('); + + // -- print parameters + if (params.size() > 0) { + sb.append(' '); + + Enumeration paramEnum = Collections.enumeration(params.values()); + sb.append(paramEnum.nextElement().getType().getName()); + while (paramEnum.hasMoreElements()) { + sb.append(", "); + sb.append(paramEnum.nextElement().getType().getName()); } - - sb.append( ' ' ); + + sb.append(' '); } - sb.append( ')' ); + sb.append(')'); return sb.toString(); - } //-- toString + } // -- toString - protected String[] getParameterClassNames() - { - List names = new ArrayList( params.size() ); + protected String[] getParameterClassNames() { + List names = new ArrayList(params.size()); - for ( JParameter param : params.values() ) - { + for (JParameter param : params.values()) { JType jType = param.getType(); - while ( jType.isArray() ) jType = jType.getComponentType(); - if ( !jType.isPrimitive() ) - { + while (jType.isArray()) jType = jType.getComponentType(); + if (!jType.isPrimitive()) { JClass jclass = (JClass) jType; - names.add( jclass.getName() ); + names.add(jclass.getName()); } } - return names.toArray( new String[0] ); - } //-- getParameterClassNames - -} //-- JMethodSignature \ No newline at end of file + return names.toArray(new String[0]); + } // -- getParameterClassNames +} // -- JMethodSignature diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JModifiers.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JModifiers.java index 1f036ea8f..e99716657 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JModifiers.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JModifiers.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -72,9 +71,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JModifiers -{ - +public class JModifiers { /* static members */ @@ -92,7 +89,6 @@ public class JModifiers private static final short vPublic = 3; private static final short vPackage = 4; - /* local members */ /** @@ -128,10 +124,9 @@ public class JModifiers * Creates a new JModifiers class, by default the * modifiers presented are public. **/ - public JModifiers() - { + public JModifiers() { super(); - } //-- JModifiers + } // -- JModifiers /** * Creates a new JModifiers @@ -141,130 +136,116 @@ public JModifiers() * @param isFinal a boolean indicating the final qualifier. A value * of true indicates that the final qualifier is present. **/ - private JModifiers( short visibility, boolean isStatic, boolean isFinal ) - { + private JModifiers(short visibility, boolean isStatic, boolean isFinal) { this.visibility = visibility; this.isStatic = isStatic; this.isFinal = isFinal; - } //-- JModifiers + } // -- JModifiers /** * Creates a copy of this JModifiers * @return the copy of this JModifiers **/ - public JModifiers copy() - { - JModifiers mods = new JModifiers( visibility, isStatic, isFinal ); - mods.setAbstract( isAbstract ); - mods.setTransient( isTransient ); + public JModifiers copy() { + JModifiers mods = new JModifiers(visibility, isStatic, isFinal); + mods.setAbstract(isAbstract); + mods.setTransient(isTransient); return mods; - } //-- copy + } // -- copy /** * Changes the visibility qualifier to "private" **/ - public void makePrivate() - { + public void makePrivate() { this.visibility = vPrivate; - } //-- makePrivate + } // -- makePrivate /** * Changes the visibility qualifier to "protected" **/ - public void makeProtected() - { + public void makeProtected() { this.visibility = vProtected; - } //-- makeProtected + } // -- makeProtected /** * Changes the visibility qualifier to "public" **/ - public void makePublic() - { + public void makePublic() { this.visibility = vPublic; - } //-- makePublic + } // -- makePublic /** * Changes the visibility qualifier to package (= without qualifier). **/ - public void makePackage() - { + public void makePackage() { this.visibility = vPackage; - } //-- makePackage + } // -- makePackage /** * Returns true if the abstract qualifier is present. *
This is only applicable to methods and classes. * @return true if the abstract qualifier is present **/ - public boolean isAbstract() - { + public boolean isAbstract() { return isAbstract; - } //-- isAbstract + } // -- isAbstract /** * Returns true if the final qualifier is present. *
This is only applicable to methods and classes. * @return true if the final qualifier is present **/ - public boolean isFinal() - { + public boolean isFinal() { return isFinal; - } //-- isFinal + } // -- isFinal /** * Returns true if the modifier represented is private. * @return true if the modifier represented is private. **/ - public boolean isPrivate() - { - return ( visibility == vPrivate ); - } //-- isPrivate + public boolean isPrivate() { + return (visibility == vPrivate); + } // -- isPrivate /** * Returns true if the modifier represented is protected. * @return true if the modifier represented is protected. **/ - public boolean isProtected() - { - return ( visibility == vProtected ); - } //-- isProtected + public boolean isProtected() { + return (visibility == vProtected); + } // -- isProtected /** * Returns true if the modifier represented is public. * @return true if the modifier represented is public. **/ - public boolean isPublic() - { - return ( visibility == vPublic ); - } //-- isPublic + public boolean isPublic() { + return (visibility == vPublic); + } // -- isPublic /** * Returns true if the modifier represented is package (= without qualifier). * @return true if the modifier represented is package (= without qualifier). **/ - public boolean isPackage() - { - return ( visibility == vPackage ); - } //-- isPackage + public boolean isPackage() { + return (visibility == vPackage); + } // -- isPackage /** * Returns true if the modifier represented is static. * @return true if the modifier represented is static. **/ - public boolean isStatic() - { + public boolean isStatic() { return this.isStatic; - } //-- isPublic + } // -- isPublic /** * Returns true if the modifier represented is transient. * @return true if the modifier represented is transient. **/ - public boolean isTransient() - { + public boolean isTransient() { return this.isTransient; - } //-- isTransient + } // -- isTransient /** * Sets whether or not the "abstract" qualifier is present @@ -272,109 +253,92 @@ public boolean isTransient() * @param isAbstract is a boolean which when true will indicate * that the abstract qualifier should be present **/ - public void setAbstract( boolean isAbstract ) - { + public void setAbstract(boolean isAbstract) { this.isAbstract = isAbstract; - } //-- setAbstract + } // -- setAbstract /** * Sets whether or not the "final" qualifier is present * @param isFinal is a boolean which when true will indicate * the final qualifiter is present **/ - public void setFinal( boolean isFinal ) - { + public void setFinal(boolean isFinal) { this.isFinal = isFinal; - } //-- setFinal + } // -- setFinal /** * Sets whether or not the "static" qualifier is present * @param isStatic is a boolean which when true will indicate * the "static" qualifiter is present **/ - public void setStatic( boolean isStatic ) - { + public void setStatic(boolean isStatic) { this.isStatic = isStatic; - } //-- setStatic + } // -- setStatic /** * Sets whether or not the "transient" qualifier is present * @param isTransient is a boolean which when true will indicate * the "transient" qualifiter is present **/ - public void setTransient( boolean isTransient ) - { + public void setTransient(boolean isTransient) { this.isTransient = isTransient; - } //-- setTransient + } // -- setTransient /** * Returns the String represetation of this JModifiers * @return the String represetation of this JModifiers **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - //-- visibility - switch ( visibility ) - { + // -- visibility + switch (visibility) { case vPrivate: - sb.append( sPrivate ); + sb.append(sPrivate); break; case vProtected: - sb.append( sProtected ); + sb.append(sProtected); break; case vPackage: - sb.append( sPackage ); + sb.append(sPackage); break; default: - sb.append( sPublic ); + sb.append(sPublic); break; } - //-- static - if ( isStatic ) - { - if ( sb.length() > 0 ) - { - sb.append( ' ' ); + // -- static + if (isStatic) { + if (sb.length() > 0) { + sb.append(' '); } - sb.append( sStatic ); + sb.append(sStatic); } - //-- final - if ( isFinal ) - { - if ( sb.length() > 0 ) - { - sb.append( ' ' ); + // -- final + if (isFinal) { + if (sb.length() > 0) { + sb.append(' '); } - sb.append( sFinal ); + sb.append(sFinal); } - //-- abstract - if ( isAbstract ) - { - if ( sb.length() > 0 ) - { - sb.append( ' ' ); + // -- abstract + if (isAbstract) { + if (sb.length() > 0) { + sb.append(' '); } - sb.append( sAbstract ); + sb.append(sAbstract); } - //-- transient - if ( isTransient ) - { - if ( sb.length() > 0 ) - { - sb.append( ' ' ); + // -- transient + if (isTransient) { + if (sb.length() > 0) { + sb.append(' '); } - sb.append( sTransient ); + sb.append(sTransient); } - return sb.toString(); - } //-- toString - -} //-- JModifiers - + } // -- toString +} // -- JModifiers diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNaming.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNaming.java index a42d4c51a..475c88ba8 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNaming.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNaming.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -73,8 +72,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -class JNaming -{ +class JNaming { private static final String[] keywords = { "abstract", @@ -127,11 +125,9 @@ class JNaming "void", "volatile", "while" - }; //-- keywords - + }; // -- keywords - private JNaming() - { + private JNaming() { super(); } @@ -139,18 +135,15 @@ private JNaming() * Returns true if the given String is a Java keyword which * will cause a problem when used as a variable name **/ - public static boolean isKeyword( String name ) - { - if ( name == null ) return false; - for ( String keyword : keywords ) - { - if ( keyword.equals( name ) ) - { + public static boolean isKeyword(String name) { + if (name == null) return false; + for (String keyword : keywords) { + if (keyword.equals(name)) { return true; } } return false; - } //-- isKeyword + } // -- isKeyword /** * Returns true if the given String matches the @@ -160,25 +153,19 @@ public static boolean isKeyword( String name ) * @return true if the given String matches the * production of a valid Java name, otherwise false **/ - public static boolean isValidJavaIdentifier( String string ) - { + public static boolean isValidJavaIdentifier(String string) { - if ( ( string == null ) || ( string.length() == 0 ) ) - return false; + if ((string == null) || (string.length() == 0)) return false; char[] chars = string.toCharArray(); - //-- make sure starting character is valid - if ( !Character.isJavaIdentifierStart( chars[0] ) ) - return false; + // -- make sure starting character is valid + if (!Character.isJavaIdentifierStart(chars[0])) return false; - for ( int i = 1; i < chars.length; i++ ) - { - if ( !Character.isJavaIdentifierPart( chars[i] ) ) - return false; + for (int i = 1; i < chars.length; i++) { + if (!Character.isJavaIdentifierPart(chars[i])) return false; } - if ( isKeyword( string ) ) return false; + if (isKeyword(string)) return false; return true; - } //-- isValidJavaIdentifier - -} //-- JNaming \ No newline at end of file + } // -- isValidJavaIdentifier +} // -- JNaming diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JParameter.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JParameter.java index b2f2aa20c..8515cd921 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JParameter.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JParameter.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -72,8 +71,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JParameter -{ +public class JParameter { /** * The type associated with this JParameter @@ -92,55 +90,47 @@ public class JParameter * @param type the type to associate with this JParameter * @param name the name of the JParameter **/ - public JParameter( JType type, String name ) - throws IllegalArgumentException - { + public JParameter(JType type, String name) throws IllegalArgumentException { super(); - setType( type ); - setName( name ); - } //-- JParameter + setType(type); + setName(name); + } // -- JParameter /** * Returns the name of the parameter * @return the name of the parameter **/ - public String getName() - { + public String getName() { return this.name; - } //-- getName + } // -- getName /** * Returns the parameter type * @return the parameter type **/ - public JType getType() - { + public JType getType() { return this.type; - } //-- getType + } // -- getType /** * Sets the name of this parameter * @param name the new name of the parameter **/ - public void setName( String name ) - { + public void setName(String name) { this.name = name; - } //-- setName + } // -- setName /** * Sets the type of this parameter * @param type the new type of this parameter **/ - public void setType( JType type ) - throws IllegalArgumentException - { - if ( type == null ) - { + public void setType(JType type) throws IllegalArgumentException { + if (type == null) { String err = "A Parameter cannot have a null type."; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } this.type = type; - } //-- setType + } // -- setType /** * Returns the String representation of this JParameter. The @@ -148,46 +138,39 @@ public void setType( JType type ) * of the parameter type, followed by the name of the parameter * @return the String representation of this JParameter **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - if ( annotations != null ) - { - sb.append( annotations.toString() ); - sb.append( ' ' ); + if (annotations != null) { + sb.append(annotations.toString()); + sb.append(' '); } - sb.append( this.type.toString() ); - sb.append( ' ' ); - sb.append( this.name ); + sb.append(this.type.toString()); + sb.append(' '); + sb.append(this.name); return sb.toString(); - } //-- toString + } // -- toString /** * @return the annotations */ - public JAnnotations getAnnotations() - { + public JAnnotations getAnnotations() { return annotations; } /** * @param annotation the annotation to append */ - public void appendAnnotation( String annotation ) - { - if ( annotations == null ) - { + public void appendAnnotation(String annotation) { + if (annotations == null) { annotations = new JAnnotations(); } - annotations.appendAnnotation( annotation ); + annotations.appendAnnotation(annotation); } /** * @param annotations the annotations to set */ - public void setAnnotations( JAnnotations annotations ) - { + public void setAnnotations(JAnnotations annotations) { this.annotations = annotations; } - -} //-- JParamater \ No newline at end of file +} // -- JParamater diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceCode.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceCode.java index d96d59d9f..43c8bc279 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceCode.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceCode.java @@ -42,11 +42,8 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; -import java.util.ArrayList; - /* * Copyright (c) 2004, Codehaus.org * @@ -69,7 +66,9 @@ * SOFTWARE. */ +import java.util.ArrayList; import java.util.List; + import org.codehaus.modello.ModelloRuntimeException; /** @@ -78,9 +77,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JSourceCode -{ - +public class JSourceCode { /** * A list of JCodeStatements @@ -100,33 +97,30 @@ public class JSourceCode /** * Creates an empty JSourceCode **/ - public JSourceCode() - { + public JSourceCode() { super(); source = new ArrayList(); - } //-- JSourceCode + } // -- JSourceCode /** * Creates a JSourceCode and adds the given String * to it's contents * @param sourceCode the source to add **/ - public JSourceCode( String sourceCode ) - { + public JSourceCode(String sourceCode) { this(); - this.source.add( new JCodeStatement( sourceCode, currentIndent ) ); - } //-- JSourceCode + this.source.add(new JCodeStatement(sourceCode, currentIndent)); + } // -- JSourceCode /** * Adds the given statement to this JSourceCode. The statement * will be added on a new line. * @param statement the statement to add **/ - public void add( String statement ) - { - JCodeStatement jcs = new JCodeStatement( statement, currentIndent ); - source.add( jcs ); - } //-- add + public void add(String statement) { + JCodeStatement jcs = new JCodeStatement(statement, currentIndent); + source.add(jcs); + } // -- add /** * Adds the given statement to this JSourceCode. The statement @@ -137,11 +131,10 @@ public void add( String statement ) * @see #print * @deprecated this method is not here any mode in castor codegen 1.3rc1 **/ - public void add( String statement, short indentSize ) - { - JCodeStatement jcs = new JCodeStatement( statement, indentSize ); - source.add( jcs ); - } //-- add + public void add(String statement, short indentSize) { + JCodeStatement jcs = new JCodeStatement(statement, indentSize); + source.add(jcs); + } // -- add /** * Adds the given statement to this JSourceCode. The statement @@ -154,174 +147,146 @@ public void add( String statement, short indentSize ) * * @param statement the statement to add **/ - public void addIndented( String statement ) - { + public void addIndented(String statement) { indent(); - JCodeStatement jcs = new JCodeStatement( statement, currentIndent ); - source.add( jcs ); + JCodeStatement jcs = new JCodeStatement(statement, currentIndent); + source.add(jcs); unindent(); - } //-- add + } // -- add /** * Appends the given String to the last line in this * JSourceCode * @param segment the String to append **/ - public void append( String segment ) - { - - if ( source.isEmpty() ) - add( segment ); - else - { - JCodeStatement jcs = (JCodeStatement) source.get( source.size() - 1 ); - jcs.append( segment ); + public void append(String segment) { + + if (source.isEmpty()) add(segment); + else { + JCodeStatement jcs = (JCodeStatement) source.get(source.size() - 1); + jcs.append(segment); } - } //-- append(String) + } // -- append(String) /** * Clears all the code statements from this JSourceCode **/ - public void clear() - { + public void clear() { source.clear(); - } //-- clear(); + } // -- clear(); /** * Copies the contents of this JSourceCode into the given JSourceCode * @param jsc the JSourceCode to copy this JSourceCode into **/ - public void copyInto( JSourceCode jsc ) - { - for ( int i = 0; i < source.size(); i++ ) - { - jsc.addCodeStatement( source.get( i ) ); + public void copyInto(JSourceCode jsc) { + for (int i = 0; i < source.size(); i++) { + jsc.addCodeStatement(source.get(i)); } - } //-- copyInto + } // -- copyInto /** * Increases the current indent level by 1 **/ - public void indent() - { + public void indent() { currentIndent += indentSize; - } //-- indent(); + } // -- indent(); /** * Returns true if this JSourceCode is empty (ie. no source). * @return true if this JSourceCode is empty. **/ - public boolean isEmpty() - { + public boolean isEmpty() { return source.isEmpty(); - } //-- isEmpty + } // -- isEmpty /** * Prints this JSourceCode to the given JSourceWriter * @param jsw the JSourceWriter to print to **/ - public void print( JSourceWriter jsw ) - { - for ( int i = 0; i < source.size(); i++ ) - jsw.writeln( source.get( i ).toString() ); - } //-- print + public void print(JSourceWriter jsw) { + for (int i = 0; i < source.size(); i++) jsw.writeln(source.get(i).toString()); + } // -- print /** * Decreases the indent level by 1 **/ - public void unindent() - { - if ( currentIndent == 0 ) - { - throw new ModelloRuntimeException( "Cannot unindent: current indent is 0." ); + public void unindent() { + if (currentIndent == 0) { + throw new ModelloRuntimeException("Cannot unindent: current indent is 0."); } currentIndent -= indentSize; - } //-- unindent - + } // -- unindent /** * Returns the String representation of this JSourceCode * @return the String representation of this JSourceCode **/ - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - String lineSeparator = System.getProperty( "line.separator" ); - for ( int i = 0; i < source.size(); i++ ) - { - sb.append( source.get( i ).toString() ); - sb.append( lineSeparator ); + String lineSeparator = System.getProperty("line.separator"); + for (int i = 0; i < source.size(); i++) { + sb.append(source.get(i).toString()); + sb.append(lineSeparator); } return sb.toString(); - } //-- toString + } // -- toString /** * Adds the given JCodeStatement to this JSourceCode * @param jcs the JCodeStatement to add **/ - private void addCodeStatement( JCodeStatement jcs ) - { - short indent = (short) ( jcs.getIndent() + currentIndent - JCodeStatement.DEFAULT_INDENTSIZE ); - source.add( new JCodeStatement( jcs.getStatement(), indent ) ); - } //-- addCodeStatement(JCodeStatement) - -} //-- JSourceCode + private void addCodeStatement(JCodeStatement jcs) { + short indent = (short) (jcs.getIndent() + currentIndent - JCodeStatement.DEFAULT_INDENTSIZE); + source.add(new JCodeStatement(jcs.getStatement(), indent)); + } // -- addCodeStatement(JCodeStatement) +} // -- JSourceCode /** * Represents a line of code, used by JSourceCode class * @author Keith Visco **/ -class JCodeStatement -{ +class JCodeStatement { private StringBuilder value = null; - static public short DEFAULT_INDENTSIZE = 4; + public static short DEFAULT_INDENTSIZE = 4; private short indentSize = DEFAULT_INDENTSIZE; - JCodeStatement() - { + JCodeStatement() { super(); value = new StringBuilder(); - } //-- JCodeStatement + } // -- JCodeStatement - JCodeStatement( String statement ) - { + JCodeStatement(String statement) { this(); - this.value.append( statement ); - } //-- JCodeStatement + this.value.append(statement); + } // -- JCodeStatement - JCodeStatement( String statement, short indentSize ) - { - this( statement ); + JCodeStatement(String statement, short indentSize) { + this(statement); this.indentSize = indentSize; - } //-- JCodeStatement - + } // -- JCodeStatement - void append( String segment ) - { - value.append( segment ); + void append(String segment) { + value.append(segment); } - short getIndent() - { + short getIndent() { return indentSize; - } //-- getIndent + } // -- getIndent - String getStatement() - { + String getStatement() { return value.toString(); - } //-- getStatement + } // -- getStatement - public String toString() - { - if ( value.length() == 0 ) - { + public String toString() { + if (value.length() == 0) { return ""; } - StringBuilder sb = new StringBuilder( indentSize + value.length() ); - for ( int i = 0; i < indentSize; i++ ) sb.append( ' ' ); - sb.append( value.toString() ); + StringBuilder sb = new StringBuilder(indentSize + value.length()); + for (int i = 0; i < indentSize; i++) sb.append(' '); + sb.append(value.toString()); return sb.toString(); } -} //-- JCodeStatement +} // -- JCodeStatement diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceWriter.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceWriter.java index f16c59c26..871109130 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceWriter.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceWriter.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -74,8 +73,7 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JSourceWriter extends Writer -{ +public class JSourceWriter extends Writer { /** * The default character to use for indentation @@ -90,7 +88,7 @@ public class JSourceWriter extends Writer /** * The line separator to use for the writeln methods **/ - private String lineSeparator = System.getProperty( "line.separator" ); + private String lineSeparator = System.getProperty("line.separator"); /** * Flag for indicating whether we need to add @@ -130,15 +128,13 @@ public class JSourceWriter extends Writer **/ private Writer out = null; - /** * Creates a new JSourceWriter * @param out the Writer to write the actual output to **/ - public JSourceWriter( Writer out ) - { - this( out, DEFAULT_SIZE, DEFAULT_CHAR, false ); - } //-- JSourceWriter + public JSourceWriter(Writer out) { + this(out, DEFAULT_SIZE, DEFAULT_CHAR, false); + } // -- JSourceWriter /** * Creates a new JSourceWriter @@ -146,10 +142,9 @@ public JSourceWriter( Writer out ) * @param autoflush a boolean indicating whether or not to * perform automatic flush at the end of a line **/ - public JSourceWriter( Writer out, boolean autoflush ) - { - this( out, DEFAULT_SIZE, DEFAULT_CHAR, autoflush ); - } //-- JSourceWriter + public JSourceWriter(Writer out, boolean autoflush) { + this(out, DEFAULT_SIZE, DEFAULT_CHAR, autoflush); + } // -- JSourceWriter /** * Creates a new JSourceWriter @@ -158,11 +153,9 @@ public JSourceWriter( Writer out, boolean autoflush ) * @param autoflush a boolean indicating whether or not to * perform automatic flush at the end of a line **/ - public JSourceWriter - ( Writer out, short tabSize, boolean autoflush ) - { - this( out, tabSize, DEFAULT_CHAR, autoflush ); - } //-- JSourceWriter + public JSourceWriter(Writer out, short tabSize, boolean autoflush) { + this(out, tabSize, DEFAULT_CHAR, autoflush); + } // -- JSourceWriter /** * Creates a new JSourceWriter @@ -172,43 +165,37 @@ public JSourceWriter( Writer out, boolean autoflush ) * @param autoflush a boolean indicating whether or not to * perform automatic flush at the end of a line **/ - public JSourceWriter - ( Writer out, short tabSize, char tabChar, boolean autoflush ) - { + public JSourceWriter(Writer out, short tabSize, char tabChar, boolean autoflush) { this.out = out; this.autoflush = autoflush; this.tabChar = tabChar; this.tabSize = tabSize; createTab(); - } //-- JSourceWriter + } // -- JSourceWriter /** * Returns the line separator being used by this JSourceWriter * @return the line separator being used by this JSourceWriter **/ - public String getLineSeparator() - { + public String getLineSeparator() { return lineSeparator; - } //-- getLineSeparator - + } // -- getLineSeparator /** * Increases the indentation level by 1 **/ - public void indent() - { + public void indent() { ++tabLevel; - } //-- increaseIndent + } // -- increaseIndent /** * Checks to see if the cursor is positioned on a new line * @return true if the cursor is at the start of a new line, otherwise false **/ - public boolean isNewline() - { - //-- if we need to add indentation, we are on a new line + public boolean isNewline() { + // -- if we need to add indentation, we are on a new line return addIndentation; - } //-- isNewline + } // -- isNewline /** * Sets the line separator to use at the end of each line @@ -221,354 +208,256 @@ public boolean isNewline() * "\n" for UNIX
* "\r" for Macintosh **/ - public void setLineSeparator( String lineSeparator ) - { + public void setLineSeparator(String lineSeparator) { this.lineSeparator = lineSeparator; - - } //-- setLineSeparator + } // -- setLineSeparator /** * Decreases the indentation level by 1 **/ - public void unindent() - { - if ( tabLevel > 0 ) --tabLevel; - } //-- decreaseIndent - - - //----------------------------/ - //- Additional write methods -/ - //----------------------------/ - - public void write( float f ) - { - write( String.valueOf( f ) ); - } //-- write(float) - - public void write( long l ) - { - write( String.valueOf( l ) ); - } //-- write(long) - - public void write( double d ) - { - write( String.valueOf( d ) ); - } //-- write(double) - - public void write( Object obj ) - { - write( obj.toString() ); - } //-- write(Object) - - public void write( boolean b ) - { - write( String.valueOf( b ) ); - } //-- write(boolean) - - //- writeln() methods - - public void writeln() - { - synchronized ( lock ) - { + public void unindent() { + if (tabLevel > 0) --tabLevel; + } // -- decreaseIndent + + // ----------------------------/ + // - Additional write methods -/ + // ----------------------------/ + + public void write(float f) { + write(String.valueOf(f)); + } // -- write(float) + + public void write(long l) { + write(String.valueOf(l)); + } // -- write(long) + + public void write(double d) { + write(String.valueOf(d)); + } // -- write(double) + + public void write(Object obj) { + write(obj.toString()); + } // -- write(Object) + + public void write(boolean b) { + write(String.valueOf(b)); + } // -- write(boolean) + + // - writeln() methods + + public void writeln() { + synchronized (lock) { linefeed(); addIndentation = true; } - } //-- writeln + } // -- writeln - public void writeln( float f ) - { - synchronized ( lock ) - { + public void writeln(float f) { + synchronized (lock) { ensureIndent(); - try - { - out.write( String.valueOf( f ) ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(String.valueOf(f)); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(float) + } // -- writeln(float) - public void writeln( long l ) - { - synchronized ( lock ) - { + public void writeln(long l) { + synchronized (lock) { ensureIndent(); - try - { - out.write( String.valueOf( l ) ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(String.valueOf(l)); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(long) + } // -- writeln(long) - public void writeln( int i ) - { - synchronized ( lock ) - { + public void writeln(int i) { + synchronized (lock) { ensureIndent(); - try - { - out.write( String.valueOf( i ) ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(String.valueOf(i)); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(int) + } // -- writeln(int) - public void writeln( double d ) - { - synchronized ( lock ) - { + public void writeln(double d) { + synchronized (lock) { ensureIndent(); - try - { - out.write( String.valueOf( d ) ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(String.valueOf(d)); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(double) + } // -- writeln(double) - - public void writeln( Object obj ) - { - synchronized ( lock ) - { + public void writeln(Object obj) { + synchronized (lock) { ensureIndent(); - try - { - out.write( obj.toString() ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(obj.toString()); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(Object) - - public void writeln( String string ) - { - synchronized ( lock ) - { - if ( string.length() > 0 ) - { + } // -- writeln(Object) + + public void writeln(String string) { + synchronized (lock) { + if (string.length() > 0) { ensureIndent(); - try - { - out.write( string ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(string); + } catch (java.io.IOException ioe) { } } linefeed(); addIndentation = true; } - } //-- writeln(String) + } // -- writeln(String) - public void writeln( char[] chars ) - { - synchronized ( lock ) - { + public void writeln(char[] chars) { + synchronized (lock) { ensureIndent(); - try - { - out.write( chars ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(chars); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(char[]) + } // -- writeln(char[]) - public void writeln( boolean b ) - { - synchronized ( lock ) - { + public void writeln(boolean b) { + synchronized (lock) { ensureIndent(); - try - { - out.write( String.valueOf( b ) ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(String.valueOf(b)); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(boolean) + } // -- writeln(boolean) - public void writeln( char c ) - { - synchronized ( lock ) - { + public void writeln(char c) { + synchronized (lock) { ensureIndent(); - try - { - out.write( c ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(c); + } catch (java.io.IOException ioe) { } ; linefeed(); addIndentation = true; } - } //-- writeln(char) - + } // -- writeln(char) - //-----------------------/ - //- Methods from Writer -/ - //-----------------------/ + // -----------------------/ + // - Methods from Writer -/ + // -----------------------/ - public void close() - { - try - { + public void close() { + try { out.close(); - } - catch ( java.io.IOException ioe ) - { + } catch (java.io.IOException ioe) { } ; - } //-- close - + } // -- close - public void flush() - { - try - { + public void flush() { + try { out.flush(); - } - catch ( java.io.IOException ioe ) - { + } catch (java.io.IOException ioe) { } ; - } //-- flush - + } // -- flush - public void write( String s, int off, int len ) - { - synchronized ( lock ) - { + public void write(String s, int off, int len) { + synchronized (lock) { ensureIndent(); - try - { - out.write( s, off, len ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(s, off, len); + } catch (java.io.IOException ioe) { } ; - if ( autoflush ) flush(); + if (autoflush) flush(); } - } //-- write + } // -- write - - public void write( String s ) - { - synchronized ( lock ) - { + public void write(String s) { + synchronized (lock) { ensureIndent(); - try - { - out.write( s ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(s); + } catch (java.io.IOException ioe) { } ; - if ( autoflush ) flush(); + if (autoflush) flush(); } - } //-- write + } // -- write - public void write( char[] buf ) - { - synchronized ( lock ) - { + public void write(char[] buf) { + synchronized (lock) { ensureIndent(); - try - { - out.write( buf ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(buf); + } catch (java.io.IOException ioe) { } ; - if ( autoflush ) flush(); + if (autoflush) flush(); } - } //-- write - + } // -- write - public void write( int c ) - { - synchronized ( lock ) - { + public void write(int c) { + synchronized (lock) { ensureIndent(); - try - { - out.write( c ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(c); + } catch (java.io.IOException ioe) { } ; - if ( autoflush ) flush(); + if (autoflush) flush(); } - } //-- write + } // -- write - - public void write( char[] buf, int off, int len ) - { - synchronized ( lock ) - { + public void write(char[] buf, int off, int len) { + synchronized (lock) { ensureIndent(); - try - { - out.write( buf, off, len ); - } - catch ( java.io.IOException ioe ) - { + try { + out.write(buf, off, len); + } catch (java.io.IOException ioe) { } ; - if ( autoflush ) flush(); + if (autoflush) flush(); } - } //-- write + } // -- write - //---------------------/ - //- Protected Methods -/ - //---------------------/ + // ---------------------/ + // - Protected Methods -/ + // ---------------------/ - protected short getIndentLevel() - { + protected short getIndentLevel() { return tabLevel; } @@ -576,69 +465,52 @@ protected short getIndentLevel() * Returns the current indent size (getIndentLevel()*tabSize); * @return the current indent size **/ - protected short getIndentSize() - { - return (short) ( tabLevel * tabSize ); - } //-- getIndentSize + protected short getIndentSize() { + return (short) (tabLevel * tabSize); + } // -- getIndentSize - protected char getIndentChar() - { + protected char getIndentChar() { return tabChar; } - protected void writeIndent() - { + protected void writeIndent() { - try - { - for ( int i = 0; i < tabLevel; i++ ) out.write( tab ); - } - catch ( java.io.IOException ioe ) - { + try { + for (int i = 0; i < tabLevel; i++) out.write(tab); + } catch (java.io.IOException ioe) { } ; + } // -- writeIndent - } //-- writeIndent - - //-------------------/ - //- Private Methods -/ - //-------------------/ + // -------------------/ + // - Private Methods -/ + // -------------------/ - private void ensureIndent() - { - if ( addIndentation ) - { + private void ensureIndent() { + if (addIndentation) { writeIndent(); addIndentation = false; } - } //-- ensureIndent - + } // -- ensureIndent /** * writes the line separator character to the writer **/ - private void linefeed() - { - try - { - out.write( lineSeparator ); - } - catch ( java.io.IOException ioe ) - { + private void linefeed() { + try { + out.write(lineSeparator); + } catch (java.io.IOException ioe) { } ; - } //-- linefeed + } // -- linefeed /** * Creates the tab from the tabSize and the tabChar **/ - private void createTab() - { + private void createTab() { tab = new char[tabSize]; - for ( int i = 0; i < tabSize; i++ ) - { + for (int i = 0; i < tabSize; i++) { tab[i] = tabChar; } - } //-- createTab - -} //-- JSourceWriter + } // -- createTab +} // -- JSourceWriter diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JStructure.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JStructure.java index 5230d2b9a..6401158c4 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JStructure.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JStructure.java @@ -42,7 +42,6 @@ * * $Id$ */ - package org.codehaus.modello.plugin.java.javasource; /* @@ -87,16 +86,14 @@ * @author Keith Visco * @version $Revision$ $Date$ */ -public abstract class JStructure extends JType -{ +public abstract class JStructure extends JType { /** * The Id for Source control systems * I needed to separate this line to prevent CVS from * expanding it here! ;-) */ - static final String DEFAULT_HEADER - = "$" + "Id$"; + static final String DEFAULT_HEADER = "$" + "Id$"; /** * The source control version for listed in the JavaDoc @@ -145,33 +142,26 @@ public abstract class JStructure extends JType * @throws java.lang.IllegalArgumentException when the given name * is not a valid Class name. */ - protected JStructure( String name ) - throws IllegalArgumentException - { - super( name ); + protected JStructure(String name) throws IllegalArgumentException { + super(name); - //-- verify name is a valid java class name - if ( !isValidClassName( name ) ) - { + // -- verify name is a valid java class name + if (!isValidClassName(name)) { String lname = getLocalName(); String err = "'" + lname + "' is "; - if ( JNaming.isKeyword( lname ) ) - err += "a reserved word and may not be used as " - + " a class name."; - else - err += "not a valid Java identifier."; + if (JNaming.isKeyword(lname)) err += "a reserved word and may not be used as " + " a class name."; + else err += "not a valid Java identifier."; - throw new IllegalArgumentException( err ); + throw new IllegalArgumentException(err); } - this.packageName = getPackageFromClassName( name ); + this.packageName = getPackageFromClassName(name); imports = new ArrayList(); interfaces = new ArrayList(); jdc = new JDocComment(); modifiers = new JModifiers(); - //-- initialize default Java doc - jdc.addDescriptor( JDocDescriptor.createVersionDesc( version ) ); - - } //-- JStructure + // -- initialize default Java doc + jdc.addDescriptor(JDocDescriptor.createVersionDesc(version)); + } // -- JStructure /** * Adds the given JField to this JStructure. @@ -186,8 +176,7 @@ protected JStructure( String name ) * @exception java.lang.IllegalArgumentException when the given * JField has a name of an existing JField */ - public abstract void addField( JField jField ) - throws IllegalArgumentException; + public abstract void addField(JField jField) throws IllegalArgumentException; /** * Adds the given JMember to this JStructure. @@ -202,48 +191,42 @@ public abstract void addField( JField jField ) * JMember has the same name of an existing JField * or JMethod respectively. */ - public abstract void addMember( JMember jMember ) - throws IllegalArgumentException; - + public abstract void addMember(JMember jMember) throws IllegalArgumentException; /** * Adds the given import to this JStructure * * @param className the className of the class to import. */ - public void addImport( String className ) - { - if ( className == null ) return; - if ( className.length() == 0 ) return; - - //-- getPackageName - String pkgName = getPackageFromClassName( className ); - - if ( pkgName != null ) - { - if ( pkgName.equals( this.packageName ) ) return; - - //-- XXX: Fix needed for this... - //-- This may cause issues if the current package - //-- defines any classes that have the same name - //-- name as the java.lang package. - if ( "java.lang".equals( pkgName ) ) return; - - //-- for readabilty keep import list sorted, and make sure - //-- we do not include more than one of the same import - for ( int i = 0; i < imports.size(); i++ ) - { - String imp = imports.get( i ); - if ( imp.equals( className ) ) return; - if ( imp.compareTo( className ) > 0 ) - { - imports.add( i, className ); + public void addImport(String className) { + if (className == null) return; + if (className.length() == 0) return; + + // -- getPackageName + String pkgName = getPackageFromClassName(className); + + if (pkgName != null) { + if (pkgName.equals(this.packageName)) return; + + // -- XXX: Fix needed for this... + // -- This may cause issues if the current package + // -- defines any classes that have the same name + // -- name as the java.lang package. + if ("java.lang".equals(pkgName)) return; + + // -- for readabilty keep import list sorted, and make sure + // -- we do not include more than one of the same import + for (int i = 0; i < imports.size(); i++) { + String imp = imports.get(i); + if (imp.equals(className)) return; + if (imp.compareTo(className) > 0) { + imports.add(i, className); return; } } - imports.add( className ); + imports.add(className); } - } //-- addImport + } // -- addImport /** * Adds the given interface to the list of interfaces this @@ -253,11 +236,9 @@ public void addImport( String className ) * @param interfaceName the name of the interface to "inherit" * method declarations from. */ - public void addInterface( String interfaceName ) - { - if ( !interfaces.contains( interfaceName ) ) - interfaces.add( interfaceName ); - } //-- addInterface + public void addInterface(String interfaceName) { + if (!interfaces.contains(interfaceName)) interfaces.add(interfaceName); + } // -- addInterface /** * Adds the given interface to the list of interfaces this @@ -266,17 +247,13 @@ public void addInterface( String interfaceName ) * * @param jInterface the JInterface to inherit from. */ - public void addInterface( JInterface jInterface ) - { - if ( jInterface == null ) return; + public void addInterface(JInterface jInterface) { + if (jInterface == null) return; String interfaceName = jInterface.getName(); - if ( !interfaces.contains( interfaceName ) ) - { - interfaces.add( interfaceName ); + if (!interfaces.contains(interfaceName)) { + interfaces.add(interfaceName); } - } //-- addInterface - - + } // -- addInterface /** * Adds the given JMethodSignature to this JClass @@ -287,65 +264,65 @@ public void addInterface( JInterface jInterface ) * method signature. */ /* - public void addMethod(JMethodSignature jMethodSig) - throws IllegalArgumentException - { - if (jMethodSig == null) { - String err = "The JMethodSignature cannot be null."; - throw new IllegalArgumentException(err); - } - - //-- XXXX: check method name and signatures *add later* - - //-- keep method list sorted for esthetics when printing - //-- START SORT :-) - boolean added = false; - short modifierVal = 0; - JModifiers modifiers = jMethodSig.getModifiers(); - for (int i = 0; i < methods.size(); i++) { - JMethodSignature tmp = (JMethodSignature) methods.elementAt(i); - //-- first compare modifiers - if (tmp.getModifiers().isProtected()) { - if (!modifiers.isProtected()) { - methods.insertElementAt(jMethodSig, i); - added = true; - break; - } - } - //-- compare names - if (jMethodSig.getName().compareTo(tmp.getName()) < 0) { - methods.insertElementAt(jMethodSig, i); - added = true; - break; - } - } - //-- END SORT - if (!added) methods.addElement(jMethodSig); - - //-- check parameter packages to make sure we have them - //-- in our import list - - String[] pkgNames = jMethodSig.getParameterClassNames(); - for (int i = 0; i < pkgNames.length; i++) { - addImport(pkgNames[i]); - } - //-- check return type to make sure it's included in the - //-- import list - JType jType = jMethodSig.getReturnType(); - if (jType != null) { - while (jType.isArray()) - jType = jType.getComponentType(); - - if (!jType.isPrimitive()) - addImport(jType.getName()); - } - //-- check exceptions - JClass[] exceptions = jMethodSig.getExceptions(); - for (int i = 0; i < exceptions.length; i++) { - addImport(exceptions[i].getName()); - } - } //-- addMethod - */ + public void addMethod(JMethodSignature jMethodSig) + throws IllegalArgumentException + { + if (jMethodSig == null) { + String err = "The JMethodSignature cannot be null."; + throw new IllegalArgumentException(err); + } + + //-- XXXX: check method name and signatures *add later* + + //-- keep method list sorted for esthetics when printing + //-- START SORT :-) + boolean added = false; + short modifierVal = 0; + JModifiers modifiers = jMethodSig.getModifiers(); + for (int i = 0; i < methods.size(); i++) { + JMethodSignature tmp = (JMethodSignature) methods.elementAt(i); + //-- first compare modifiers + if (tmp.getModifiers().isProtected()) { + if (!modifiers.isProtected()) { + methods.insertElementAt(jMethodSig, i); + added = true; + break; + } + } + //-- compare names + if (jMethodSig.getName().compareTo(tmp.getName()) < 0) { + methods.insertElementAt(jMethodSig, i); + added = true; + break; + } + } + //-- END SORT + if (!added) methods.addElement(jMethodSig); + + //-- check parameter packages to make sure we have them + //-- in our import list + + String[] pkgNames = jMethodSig.getParameterClassNames(); + for (int i = 0; i < pkgNames.length; i++) { + addImport(pkgNames[i]); + } + //-- check return type to make sure it's included in the + //-- import list + JType jType = jMethodSig.getReturnType(); + if (jType != null) { + while (jType.isArray()) + jType = jType.getComponentType(); + + if (!jType.isPrimitive()) + addImport(jType.getName()); + } + //-- check exceptions + JClass[] exceptions = jMethodSig.getExceptions(); + for (int i = 0; i < exceptions.length; i++) { + addImport(exceptions[i].getName()); + } + } //-- addMethod + */ /** * Returns the field with the given name, or null if no field * was found with the given name. @@ -354,7 +331,7 @@ public void addMethod(JMethodSignature jMethodSig) * @return the field with the given name, or null if no field * was found with the given name. */ - public abstract JField getField( String name ); + public abstract JField getField(String name); /** * Returns an array of all the JFields of this JStructure @@ -371,35 +348,29 @@ public void addMethod(JMethodSignature jMethodSig) * @return the name of the file that this JInterface would be * printed as, given a call to #print. */ - public String getFilename( String destDir ) - { + public String getFilename(String destDir) { String filename = getLocalName() + ".java"; - //-- Convert Java package to path string + // -- Convert Java package to path string String javaPackagePath = ""; - if ( ( packageName != null ) && ( packageName.length() > 0 ) ) - { - javaPackagePath = packageName.replace( '.', File.separatorChar ); + if ((packageName != null) && (packageName.length() > 0)) { + javaPackagePath = packageName.replace('.', File.separatorChar); } - //-- Create fully qualified path (including 'destDir') to file + // -- Create fully qualified path (including 'destDir') to file File pathFile; - if ( destDir == null ) - pathFile = new File( javaPackagePath ); - else - pathFile = new File( destDir, javaPackagePath ); - if ( !pathFile.exists() ) - { + if (destDir == null) pathFile = new File(javaPackagePath); + else pathFile = new File(destDir, javaPackagePath); + if (!pathFile.exists()) { pathFile.mkdirs(); } - //-- Prefix filename with path - if ( pathFile.toString().length() > 0 ) - filename = pathFile.toString() + File.separator + filename; + // -- Prefix filename with path + if (pathFile.toString().length() > 0) filename = pathFile.toString() + File.separator + filename; return filename; - } //-- getFilename + } // -- getFilename /** * Returns the JComment header to display at the top of the source file @@ -407,10 +378,9 @@ public String getFilename( String destDir ) * * @return the JComment header or null if none exists. */ - public JComment getHeader() - { + public JComment getHeader() { return this.header; - } //-- getHeader + } // -- getHeader /** * Returns an Enumeration of imported package and @@ -418,10 +388,9 @@ public JComment getHeader() * * @return the Enumeration of imports. May be empty. */ - public Enumeration getImports() - { - return Collections.enumeration( imports ); - } //-- getImports + public Enumeration getImports() { + return Collections.enumeration(imports); + } // -- getImports /** * Returns an Enumeration of interface names that this @@ -430,33 +399,31 @@ public Enumeration getImports() * @return the Enumeration of interface names for this * JStructure. May be empty. */ - public Enumeration getInterfaces() - { - return Collections.enumeration( interfaces ); - } //-- getInterfaces + public Enumeration getInterfaces() { + return Collections.enumeration(interfaces); + } // -- getInterfaces /** * Returns the Java Doc comment for this JStructure * * @return the JDocComment for this JStructure */ - public JDocComment getJDocComment() - { + public JDocComment getJDocComment() { return jdc; - } //-- getJDocComment + } // -- getJDocComment /** * Returns an array of all the JMethodSignatures of this JInterface. * * @return an array of all the JMethodSignatures of this JInterface. */ -/* - public JMethodSignature[] getMethods() { - JMethodSignature[] marray = new JMethodSignature[methods.size()]; - methods.copyInto(marray); - return marray; - } //-- getMethods -*/ + /* + public JMethodSignature[] getMethods() { + JMethodSignature[] marray = new JMethodSignature[methods.size()]; + methods.copyInto(marray); + return marray; + } //-- getMethods + */ /** * Returns the JMethodSignature with the given name, @@ -467,15 +434,15 @@ public JMethodSignature[] getMethods() { * from. * @return the JMethodSignature, or null if not found. */ -/* - public JMethodSignature getMethod(String name, int startIndex) { - for (int i = startIndex; i < methods.size(); i++) { - JMethodSignature jMethod = (JMethodSignature)methods.elementAt(i); - if (jMethod.getName().equals(name)) return jMethod; - } - return null; - } //-- getMethod -*/ + /* + public JMethodSignature getMethod(String name, int startIndex) { + for (int i = startIndex; i < methods.size(); i++) { + JMethodSignature jMethod = (JMethodSignature)methods.elementAt(i); + if (jMethod.getName().equals(name)) return jMethod; + } + return null; + } //-- getMethod + */ /** * Returns the JMethodSignature at the given index. @@ -494,10 +461,9 @@ public JMethodSignature getMethod(int index) { * * @return the JModifiers for this JStructure. */ - public JModifiers getModifiers() - { + public JModifiers getModifiers() { return modifiers; - } //-- getModifiers + } // -- getModifiers /** * Returns the name of the package that this JStructure is a member @@ -506,11 +472,9 @@ public JModifiers getModifiers() * @return the name of the package that this JStructure is a member * of, or null if there is no current package name defined. */ - public String getPackageName() - { + public String getPackageName() { return this.packageName; - } //-- getPackageName - + } // -- getPackageName /** * Returns the name of the interface. @@ -519,17 +483,14 @@ public String getPackageName() * the local name (no package) should be returned. * @return the name of the class. */ - public String getName( boolean stripPackage ) - { + public String getName(boolean stripPackage) { String name = super.getName(); - if ( stripPackage ) - { - int period = name.lastIndexOf( "." ); - if ( period > 0 ) - name = name.substring( period + 1 ); + if (stripPackage) { + int period = name.lastIndexOf("."); + if (period > 0) name = name.substring(period + 1); } return name; - } //-- getName + } // -- getName /** * Returns true if the given classname exists in the imports @@ -538,49 +499,41 @@ public String getName( boolean stripPackage ) * @param classname the class name to check for * @return true if the given classname exists in the imports list */ - public boolean hasImport( String classname ) - { - return imports.contains( classname ); - } //-- hasImport - + public boolean hasImport(String classname) { + return imports.contains(classname); + } // -- hasImport - public boolean removeImport( String className ) - { + public boolean removeImport(String className) { boolean result = false; - if ( className == null ) return result; - if ( className.length() == 0 ) return result; - - return imports.remove( className ); - } //-- removeImport + if (className == null) return result; + if (className.length() == 0) return result; + return imports.remove(className); + } // -- removeImport - public boolean isAbstract() - { + public boolean isAbstract() { return modifiers.isAbstract(); } - public static boolean isValidClassName( String name ) - { + public static boolean isValidClassName(String name) { - if ( name == null ) return false; + if (name == null) return false; - //-- ignore package information, for now - int period = name.lastIndexOf( "." ); - if ( period > 0 ) - name = name.substring( period + 1 ); + // -- ignore package information, for now + int period = name.lastIndexOf("."); + if (period > 0) name = name.substring(period + 1); - return JNaming.isValidJavaIdentifier( name ); - } //-- isValidClassName + return JNaming.isValidJavaIdentifier(name); + } // -- isValidClassName /** * Prints the source code for this JStructure in the current * working directory. Sub-directories will be created if necessary * for the package. */ - public void print() - { - print( (String) null, (String) null ); - } //-- printSrouce + public void print() { + print((String) null, (String) null); + } // -- printSrouce /** * Prints the source code for this JStructure to the destination @@ -592,34 +545,28 @@ public void print() * If null, then the default line separator for the runtime platform will * be used. */ - public void print( String destDir, String lineSeparator ) - { + public void print(String destDir, String lineSeparator) { -// String name = getLocalName(); + // String name = getLocalName(); - //-- open output file - String filename = getFilename( destDir ); + // -- open output file + String filename = getFilename(destDir); - File file = new File( filename ); + File file = new File(filename); JSourceWriter jsw = null; - try - { - jsw = new JSourceWriter( WriterFactory.newPlatformWriter( file ) ); - } - catch ( java.io.IOException ioe ) - { - System.out.println( "unable to create class file: " + filename ); + try { + jsw = new JSourceWriter(WriterFactory.newPlatformWriter(file)); + } catch (java.io.IOException ioe) { + System.out.println("unable to create class file: " + filename); return; } - if ( lineSeparator == null ) - { - lineSeparator = System.getProperty( "line.separator" ); + if (lineSeparator == null) { + lineSeparator = System.getProperty("line.separator"); } - jsw.setLineSeparator( lineSeparator ); - print( jsw ); + jsw.setLineSeparator(lineSeparator); + print(jsw); jsw.close(); - - } //-- print + } // -- print /** * Prints the source code for this JStructure to the given @@ -627,7 +574,7 @@ public void print( String destDir, String lineSeparator ) * * @param jsw the JSourceWriter to print to. */ - public abstract void print( JSourceWriter jsw ); + public abstract void print(JSourceWriter jsw); /** * A utility method that prints the header to the given @@ -635,27 +582,23 @@ public void print( String destDir, String lineSeparator ) * * @param jsw the JSourceWriter to print to. */ - public void printHeader( JSourceWriter jsw ) - { + public void printHeader(JSourceWriter jsw) { - if ( jsw == null ) - { - throw new IllegalArgumentException( "argument 'jsw' should not be null." ); + if (jsw == null) { + throw new IllegalArgumentException("argument 'jsw' should not be null."); } - //-- write class header + // -- write class header JComment header = getHeader(); - if ( header != null ) - header.print( jsw ); - else - { - jsw.writeln( "/*" ); - jsw.writeln( " * " + DEFAULT_HEADER ); - jsw.writeln( " */" ); + if (header != null) header.print(jsw); + else { + jsw.writeln("/*"); + jsw.writeln(" * " + DEFAULT_HEADER); + jsw.writeln(" */"); } jsw.writeln(); jsw.flush(); - } //-- printHeader + } // -- printHeader /** * A utility method that prints the imports to the given @@ -663,31 +606,27 @@ public void printHeader( JSourceWriter jsw ) * * @param jsw the JSourceWriter to print to. */ - public void printImportDeclarations( JSourceWriter jsw ) - { + public void printImportDeclarations(JSourceWriter jsw) { - if ( jsw == null ) - { - throw new IllegalArgumentException( "argument 'jsw' should not be null." ); + if (jsw == null) { + throw new IllegalArgumentException("argument 'jsw' should not be null."); } - //-- print imports - if ( imports.size() > 0 ) - { - jsw.writeln( " //---------------------------------/" ); - jsw.writeln( " //- Imported classes and packages -/" ); - jsw.writeln( "//---------------------------------/" ); + // -- print imports + if (imports.size() > 0) { + jsw.writeln(" //---------------------------------/"); + jsw.writeln(" //- Imported classes and packages -/"); + jsw.writeln("//---------------------------------/"); jsw.writeln(); - for( String imp : imports ) - { - jsw.write( "import " ); - jsw.write( imp ); - jsw.writeln( ';' ); + for (String imp : imports) { + jsw.write("import "); + jsw.write(imp); + jsw.writeln(';'); } jsw.writeln(); jsw.flush(); } - } //-- printImportDeclarations + } // -- printImportDeclarations /** * A utility method that prints the packageDeclaration to @@ -695,24 +634,21 @@ public void printImportDeclarations( JSourceWriter jsw ) * * @param jsw the JSourceWriter to print to. */ - public void printPackageDeclaration( JSourceWriter jsw ) - { + public void printPackageDeclaration(JSourceWriter jsw) { - if ( jsw == null ) - { - throw new IllegalArgumentException( "argument 'jsw' should not be null." ); + if (jsw == null) { + throw new IllegalArgumentException("argument 'jsw' should not be null."); } - //-- print package name - if ( ( packageName != null ) && ( packageName.length() > 0 ) ) - { - jsw.write( "package " ); - jsw.write( packageName ); - jsw.writeln( ';' ); + // -- print package name + if ((packageName != null) && (packageName.length() > 0)) { + jsw.write("package "); + jsw.write(packageName); + jsw.writeln(';'); jsw.writeln(); } jsw.flush(); - } //-- printPackageDeclaration + } // -- printPackageDeclaration /** * Prints the source code for this JStructure to the given @@ -720,88 +656,88 @@ public void printPackageDeclaration( JSourceWriter jsw ) * * @param jsw the JSourceWriter to print to. * - public abstract void print(JSourceWriter jsw); - - - StringBuilder buffer = new StringBuilder(); - - - printHeader(); - printPackageDeclaration(); - printImportDeclarations(); - - //------------/ - //- Java Doc -/ - //------------/ - - jdc.print(jsw); - - //-- print class information - //-- we need to add some JavaDoc API adding comments - - buffer.setLength(0); - - if (modifiers.isPrivate()) { - buffer.append("private "); - } - else if (modifiers.isPublic()) { - buffer.append("public "); - } - - if (modifiers.isAbstract()) { - buffer.append("abstract "); - } - - buffer.append("interface "); - buffer.append(getLocalName()); - buffer.append(' '); - if (interfaces.size() > 0) { - boolean endl = false; - if (interfaces.size() > 1) { - jsw.writeln(buffer.toString()); - buffer.setLength(0); - endl = true; - } - buffer.append("extends "); - for (int i = 0; i < interfaces.size(); i++) { - if (i > 0) buffer.append(", "); - buffer.append(interfaces.elementAt(i)); - } - if (endl) { - jsw.writeln(buffer.toString()); - buffer.setLength(0); - } - else buffer.append(' '); - } - - buffer.append('{'); - jsw.writeln(buffer.toString()); - buffer.setLength(0); - jsw.writeln(); - - jsw.indent(); - - //-- print method signatures - - if (methods.size() > 0) { - jsw.writeln(); - jsw.writeln(" //-----------/"); - jsw.writeln(" //- Methods -/"); - jsw.writeln("//-----------/"); - jsw.writeln(); - } - - for (int i = 0; i < methods.size(); i++) { - JMethodSignature signature = (JMethodSignature) methods.elementAt(i); - signature.print(jsw); - jsw.writeln(';'); - } - - jsw.unindent(); - jsw.writeln('}'); - jsw.flush(); - jsw.close(); - } //-- printSource + * public abstract void print(JSourceWriter jsw); + * + * + * StringBuilder buffer = new StringBuilder(); + * + * + * printHeader(); + * printPackageDeclaration(); + * printImportDeclarations(); + * + * //------------/ + * //- Java Doc -/ + * //------------/ + * + * jdc.print(jsw); + * + * //-- print class information + * //-- we need to add some JavaDoc API adding comments + * + * buffer.setLength(0); + * + * if (modifiers.isPrivate()) { + * buffer.append("private "); + * } + * else if (modifiers.isPublic()) { + * buffer.append("public "); + * } + * + * if (modifiers.isAbstract()) { + * buffer.append("abstract "); + * } + * + * buffer.append("interface "); + * buffer.append(getLocalName()); + * buffer.append(' '); + * if (interfaces.size() > 0) { + * boolean endl = false; + * if (interfaces.size() > 1) { + * jsw.writeln(buffer.toString()); + * buffer.setLength(0); + * endl = true; + * } + * buffer.append("extends "); + * for (int i = 0; i < interfaces.size(); i++) { + * if (i > 0) buffer.append(", "); + * buffer.append(interfaces.elementAt(i)); + * } + * if (endl) { + * jsw.writeln(buffer.toString()); + * buffer.setLength(0); + * } + * else buffer.append(' '); + * } + * + * buffer.append('{'); + * jsw.writeln(buffer.toString()); + * buffer.setLength(0); + * jsw.writeln(); + * + * jsw.indent(); + * + * //-- print method signatures + * + * if (methods.size() > 0) { + * jsw.writeln(); + * jsw.writeln(" //-----------/"); + * jsw.writeln(" //- Methods -/"); + * jsw.writeln("//-----------/"); + * jsw.writeln(); + * } + * + * for (int i = 0; i < methods.size(); i++) { + * JMethodSignature signature = (JMethodSignature) methods.elementAt(i); + * signature.print(jsw); + * jsw.writeln(';'); + * } + * + * jsw.unindent(); + * jsw.writeln('}'); + * jsw.flush(); + * jsw.close(); + * } //-- printSource */ /** @@ -810,17 +746,15 @@ else if (modifiers.isPublic()) { * @param comment the comment to display at the top of the source file * when printed */ - public void setHeader( JComment comment ) - { + public void setHeader(JComment comment) { this.header = comment; - } //-- setHeader + } // -- setHeader - //---------------------/ - //- Protected Methods -/ - //---------------------/ + // ---------------------/ + // - Protected Methods -/ + // ---------------------/ - protected int getInterfaceCount() - { + protected int getInterfaceCount() { return interfaces.size(); } @@ -832,79 +766,65 @@ protected int getInterfaceCount() * @param source the source code to print * @param jsw the JSourceWriter to print to. */ - protected static void printlnWithPrefix( String prefix, String source, JSourceWriter jsw ) - { - jsw.write( prefix ); - if ( source == null ) return; + protected static void printlnWithPrefix(String prefix, String source, JSourceWriter jsw) { + jsw.write(prefix); + if (source == null) return; char[] chars = source.toCharArray(); int lastIdx = 0; - for ( int i = 0; i < chars.length; i++ ) - { + for (int i = 0; i < chars.length; i++) { char ch = chars[i]; - if ( ch == '\n' ) - { - //-- free buffer - jsw.write( chars, lastIdx, ( i - lastIdx ) + 1 ); + if (ch == '\n') { + // -- free buffer + jsw.write(chars, lastIdx, (i - lastIdx) + 1); lastIdx = i + 1; - if ( i < chars.length ) - { - jsw.write( prefix ); + if (i < chars.length) { + jsw.write(prefix); } } } - //-- free buffer - if ( lastIdx < chars.length ) - { - jsw.write( chars, lastIdx, chars.length - lastIdx ); + // -- free buffer + if (lastIdx < chars.length) { + jsw.write(chars, lastIdx, chars.length - lastIdx); } jsw.writeln(); - - } //-- printlnWithPrefix - + } // -- printlnWithPrefix /** * Returns the package name from the given class name - * + * * @param className the className * @return the package of the class, otherwise {@code null} */ - protected static String getPackageFromClassName( String className ) - { + protected static String getPackageFromClassName(String className) { int idx = -1; - if ( ( idx = className.lastIndexOf( '.' ) ) > 0 ) - { - return className.substring( 0, idx ); + if ((idx = className.lastIndexOf('.')) > 0) { + return className.substring(0, idx); } return null; - } //-- getPackageFromClassName + } // -- getPackageFromClassName /** * @return the annotations */ - public JAnnotations getAnnotations() - { + public JAnnotations getAnnotations() { return annotations; } /** * @param annotation the annotation to append */ - public void appendAnnotation( String annotation ) - { - if ( annotations == null ) - { + public void appendAnnotation(String annotation) { + if (annotations == null) { annotations = new JAnnotations(); } - annotations.appendAnnotation( annotation ); + annotations.appendAnnotation(annotation); } /** * @param annotations the annotations to set */ - public void setAnnotations( JAnnotations annotations ) - { + public void setAnnotations(JAnnotations annotations) { this.annotations = annotations; } - -} //-- JStructure +} // -- JStructure diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JType.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JType.java index 587c6e598..5a6018976 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JType.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JType.java @@ -42,8 +42,6 @@ * * $Id$ */ - - package org.codehaus.modello.plugin.java.javasource; /* @@ -72,17 +70,16 @@ * @author Keith Visco * @version $Revision$ $Date$ **/ -public class JType -{ - - public static final JType BOOLEAN = new JType( "boolean" ); - public static final JType BYTE = new JType( "byte" ); - public static final JType CHAR = new JType( "char" ); - public static final JType DOUBLE = new JType( "double" ); - public static final JType FLOAT = new JType( "float" ); - public static final JType INT = new JType( "int" ); - public static final JType LONG = new JType( "long" ); - public static final JType SHORT = new JType( "short" ); +public class JType { + + public static final JType BOOLEAN = new JType("boolean"); + public static final JType BYTE = new JType("byte"); + public static final JType CHAR = new JType("char"); + public static final JType DOUBLE = new JType("double"); + public static final JType FLOAT = new JType("float"); + public static final JType INT = new JType("int"); + public static final JType LONG = new JType("long"); + public static final JType SHORT = new JType("short"); private String name = null; @@ -97,11 +94,10 @@ public class JType * Creates a new JType with the given name * @param name the name of the type **/ - public JType( String name ) - { + public JType(String name) { super(); this.name = name; - } //-- JType + } // -- JType /** * Creates a JType Object representing an array of the current @@ -109,50 +105,44 @@ public JType( String name ) * @return the new JType which is represents an array. * @deprecated removed in javasource 1.3rc1, replaced by JArrayType **/ - public final JType createArray() - { - JType jType = new JType( getName() ); + public final JType createArray() { + JType jType = new JType(getName()); jType._isArray = true; jType._componentType = this; return jType; - } //-- createArray + } // -- createArray /** * If this JType is an array this method will returns the component type * of the array, otherwise null will be returned. * @return the component JType if this JType is an array, otherwise null. **/ - public JType getComponentType() - { + public JType getComponentType() { return _componentType; - } //-- getComponentType + } // -- getComponentType - public String getLocalName() - { + public String getLocalName() { - //-- use getName method in case it's been overloaded + // -- use getName method in case it's been overloaded String name = getName(); - if ( name == null ) return null; - int idx = name.lastIndexOf( '.' ); - if ( idx >= 0 ) - { - name = name.substring( idx + 1 ); + if (name == null) return null; + int idx = name.lastIndexOf('.'); + if (idx >= 0) { + name = name.substring(idx + 1); } return name; - } //-- getLocalName + } // -- getLocalName - public String getName() - { + public String getName() { return this.name; - } //-- getName + } // -- getName /** * Checks to see if this JType represents an array. * @return true if this JType represents an array, otherwise false **/ - public final boolean isArray() - { + public final boolean isArray() { return _isArray; } @@ -160,36 +150,31 @@ public final boolean isArray() * Checks to see if this JType represents a primitive * @return true if this JType represents a primitive, otherwise false **/ - public boolean isPrimitive() - { - return ( ( this == BOOLEAN ) || - ( this == BYTE ) || - ( this == CHAR ) || - ( this == DOUBLE ) || - ( this == FLOAT ) || - ( this == INT ) || - ( this == LONG ) || - ( this == SHORT ) ); - } //-- isPrimitive + public boolean isPrimitive() { + return ((this == BOOLEAN) + || (this == BYTE) + || (this == CHAR) + || (this == DOUBLE) + || (this == FLOAT) + || (this == INT) + || (this == LONG) + || (this == SHORT)); + } // -- isPrimitive /** * Returns the String representation of this JType, which is * simply the name of this type. * @return the String representation of this JType **/ - public String toString() - { - - if ( _isArray ) - return _componentType.toString() + "[]"; - else - return this.name; + public String toString() { - } //-- toString + if (_isArray) return _componentType.toString() + "[]"; + else return this.name; + } // -- toString - //---------------------/ - //- Protected methods -/ - //---------------------/ + // ---------------------/ + // - Protected methods -/ + // ---------------------/ /** * Allows subtypes, such as JClass to alter the package to which @@ -198,24 +183,17 @@ public String toString() *
* Note: The package name cannot be changed on a primitive type. **/ - protected void changePackage( String newPackage ) - { + protected void changePackage(String newPackage) { - if ( this.name == null ) return; - if ( this.isPrimitive() ) return; + if (this.name == null) return; + if (this.isPrimitive()) return; String localName = null; - int idx = name.lastIndexOf( '.' ); - if ( idx >= 0 ) - localName = this.name.substring( idx + 1 ); - else - localName = this.name; - - if ( ( newPackage == null ) || ( newPackage.length() == 0 ) ) - this.name = localName; - else - this.name = newPackage + "." + localName; - - } //-- changePackage - -} //-- JType + int idx = name.lastIndexOf('.'); + if (idx >= 0) localName = this.name.substring(idx + 1); + else localName = this.name; + + if ((newPackage == null) || (newPackage.length() == 0)) this.name = localName; + else this.name = newPackage + "." + localName; + } // -- changePackage +} // -- JType diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaAssociationMetadata.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaAssociationMetadata.java index 9e081ef60..383b4a12d 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaAssociationMetadata.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaAssociationMetadata.java @@ -22,17 +22,15 @@ * SOFTWARE. */ -import org.codehaus.modello.metadata.AssociationMetadata; - import java.util.ArrayList; import java.util.List; +import org.codehaus.modello.metadata.AssociationMetadata; + /** * @author Emmanuel Venisse */ -public class JavaAssociationMetadata - implements AssociationMetadata -{ +public class JavaAssociationMetadata implements AssociationMetadata { public static final String ID = JavaAssociationMetadata.class.getName(); public static final String LAZY_INIT = "lazy"; @@ -41,12 +39,11 @@ public class JavaAssociationMetadata public static final List INIT_TYPES; - static - { + static { INIT_TYPES = new ArrayList(); - INIT_TYPES.add( LAZY_INIT ); - INIT_TYPES.add( CONSTRUCTOR_INIT ); - INIT_TYPES.add( FIELD_INIT ); + INIT_TYPES.add(LAZY_INIT); + INIT_TYPES.add(CONSTRUCTOR_INIT); + INIT_TYPES.add(FIELD_INIT); } public static final String CLONE_SHALLOW = "shallow"; @@ -54,11 +51,10 @@ public class JavaAssociationMetadata public static final List CLONE_MODES; - static - { + static { CLONE_MODES = new ArrayList(); - CLONE_MODES.add( CLONE_SHALLOW ); - CLONE_MODES.add( CLONE_DEEP ); + CLONE_MODES.add(CLONE_SHALLOW); + CLONE_MODES.add(CLONE_DEEP); } private boolean adder = true; @@ -71,61 +67,47 @@ public class JavaAssociationMetadata private String cloneMode; - public boolean isAdder() - { + public boolean isAdder() { return adder; } - public void setAdder( boolean adder ) - { + public void setAdder(boolean adder) { this.adder = adder; } - public boolean isBidi() - { + public boolean isBidi() { return bidi; } - public void setBidi( boolean bidi ) - { + public void setBidi(boolean bidi) { this.bidi = bidi; } - public String getInterfaceName() - { + public String getInterfaceName() { return interfaceName; } - public void setInterfaceName( String interfaceName ) - { + public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } - public String getInitializationMode() - { + public String getInitializationMode() { return initializationMode; } - public void setInitializationMode( String initializationMode ) - { - if ( initializationMode == null ) - { + public void setInitializationMode(String initializationMode) { + if (initializationMode == null) { this.initializationMode = LAZY_INIT; - } - else - { + } else { this.initializationMode = initializationMode; } } - public String getCloneMode() - { + public String getCloneMode() { return cloneMode; } - public void setCloneMode( String cloneMode ) - { + public void setCloneMode(String cloneMode) { this.cloneMode = cloneMode; } - } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaClassMetadata.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaClassMetadata.java index 63b7c7e2d..5f0d41aab 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaClassMetadata.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaClassMetadata.java @@ -30,9 +30,7 @@ /** * @author Emmanuel Venisse */ -public class JavaClassMetadata - implements ClassMetadata -{ +public class JavaClassMetadata implements ClassMetadata { public static final String ID = JavaClassMetadata.class.getName(); public static final String CLONE_NONE = "none"; @@ -41,12 +39,11 @@ public class JavaClassMetadata public static final List CLONE_MODES; - static - { + static { CLONE_MODES = new ArrayList(); - CLONE_MODES.add( CLONE_NONE ); - CLONE_MODES.add( CLONE_SHALLOW ); - CLONE_MODES.add( CLONE_DEEP ); + CLONE_MODES.add(CLONE_NONE); + CLONE_MODES.add(CLONE_SHALLOW); + CLONE_MODES.add(CLONE_DEEP); } private boolean abstractMode; @@ -72,74 +69,59 @@ public class JavaClassMetadata */ private boolean generateStaticCreators = false; - public void setAbstract( boolean abstractMode ) - { + public void setAbstract(boolean abstractMode) { this.abstractMode = abstractMode; } - public boolean isAbstract() - { + public boolean isAbstract() { return abstractMode; } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public void setEnabled( boolean generate ) - { + public void setEnabled(boolean generate) { this.enabled = generate; } - public String getCloneMode() - { + public String getCloneMode() { return cloneMode; } - public void setCloneMode( String cloneMode ) - { + public void setCloneMode(String cloneMode) { this.cloneMode = cloneMode; } - public String getCloneHook() - { + public String getCloneHook() { return cloneHook; } - public void setCloneHook( String cloneHook ) - { + public void setCloneHook(String cloneHook) { this.cloneHook = cloneHook; } - public boolean isGenerateToString() - { + public boolean isGenerateToString() { return generateToString; } - public void setGenerateToString( boolean generateToString ) - { + public void setGenerateToString(boolean generateToString) { this.generateToString = generateToString; } - public boolean isGenerateBuilder() - { + public boolean isGenerateBuilder() { return generateBuilder; } - public void setGenerateBuilder( boolean generateBuilder ) - { + public void setGenerateBuilder(boolean generateBuilder) { this.generateBuilder = generateBuilder; } - public boolean isGenerateStaticCreators() - { + public boolean isGenerateStaticCreators() { return generateStaticCreators; } - public void setGenerateStaticCreators( boolean generateStaticCreators ) - { + public void setGenerateStaticCreators(boolean generateStaticCreators) { this.generateStaticCreators = generateStaticCreators; } - } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaFieldMetadata.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaFieldMetadata.java index cdba5df46..0a8982314 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaFieldMetadata.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaFieldMetadata.java @@ -27,9 +27,7 @@ /** * @author Emmanuel Venisse */ -public class JavaFieldMetadata - implements FieldMetadata -{ +public class JavaFieldMetadata implements FieldMetadata { public static final String ID = JavaFieldMetadata.class.getName(); private boolean getter = true; @@ -38,33 +36,27 @@ public class JavaFieldMetadata private boolean setter = true; - public boolean isGetter() - { + public boolean isGetter() { return getter; } - public void setGetter( boolean getter ) - { + public void setGetter(boolean getter) { this.getter = getter; } - public boolean isBooleanGetter() - { + public boolean isBooleanGetter() { return booleanGetter; } - public void setBooleanGetter( boolean booleanGetter ) - { + public void setBooleanGetter(boolean booleanGetter) { this.booleanGetter = booleanGetter; } - public boolean isSetter() - { + public boolean isSetter() { return setter; } - public void setSetter( boolean setter ) - { + public void setSetter(boolean setter) { this.setter = setter; } -} \ No newline at end of file +} diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaInterfaceMetadata.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaInterfaceMetadata.java index 945f385f1..8d22d974a 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaInterfaceMetadata.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaInterfaceMetadata.java @@ -27,8 +27,6 @@ /** * @author Emmanuel Venisse */ -public class JavaInterfaceMetadata - implements InterfaceMetadata -{ +public class JavaInterfaceMetadata implements InterfaceMetadata { public static final String ID = JavaInterfaceMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaMetadataPlugin.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaMetadataPlugin.java index 296cfcc6c..0c96a8039 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaMetadataPlugin.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaMetadataPlugin.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.Map; + import org.codehaus.modello.metadata.AbstractMetadataPlugin; import org.codehaus.modello.metadata.AssociationMetadata; import org.codehaus.modello.metadata.ClassMetadata; @@ -36,16 +38,11 @@ import org.codehaus.modello.model.ModelInterface; import org.codehaus.plexus.component.annotations.Component; -import java.util.Map; - /** * @author Emmanuel Venisse */ -@Component( role = MetadataPlugin.class, hint = "java" ) -public class JavaMetadataPlugin - extends AbstractMetadataPlugin - implements MetadataPlugin -{ +@Component(role = MetadataPlugin.class, hint = "java") +public class JavaMetadataPlugin extends AbstractMetadataPlugin implements MetadataPlugin { public static final String JAVA_ABSTRACT = "java.abstract"; public static final String JAVA_ADDER = "java.adder"; @@ -87,68 +84,63 @@ public class JavaMetadataPlugin // Map to Metadata // ---------------------------------------------------------------------- - public ModelMetadata getModelMetadata( Model model, Map data ) - { + public ModelMetadata getModelMetadata(Model model, Map data) { JavaModelMetadata metadata = new JavaModelMetadata(); - metadata.setSuppressAllWarnings( getBoolean( data, JAVA_SUPPRESS_ALL_WARNINGS, true ) ); + metadata.setSuppressAllWarnings(getBoolean(data, JAVA_SUPPRESS_ALL_WARNINGS, true)); return metadata; } - public ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - { + public ClassMetadata getClassMetadata(ModelClass clazz, Map data) { JavaClassMetadata metadata = new JavaClassMetadata(); - metadata.setEnabled( getBoolean( data, JAVA_ENABLED, true ) ); + metadata.setEnabled(getBoolean(data, JAVA_ENABLED, true)); - metadata.setAbstract( getBoolean( data, JAVA_ABSTRACT, false ) ); + metadata.setAbstract(getBoolean(data, JAVA_ABSTRACT, false)); - metadata.setCloneMode( getString( data, JAVA_CLONE ) ); + metadata.setCloneMode(getString(data, JAVA_CLONE)); - metadata.setCloneHook( getString( data, JAVA_CLONE_HOOK ) ); + metadata.setCloneHook(getString(data, JAVA_CLONE_HOOK)); - metadata.setGenerateToString( getBoolean( data, JAVA_GENERATE_TOSTRING, false ) ); + metadata.setGenerateToString(getBoolean(data, JAVA_GENERATE_TOSTRING, false)); - metadata.setGenerateBuilder( getBoolean( data, JAVA_GENERATE_BUILDER, false ) ); + metadata.setGenerateBuilder(getBoolean(data, JAVA_GENERATE_BUILDER, false)); - metadata.setGenerateStaticCreators( getBoolean( data, JAVA_GENERATE_STATIC_CREATORS, false ) ); + metadata.setGenerateStaticCreators(getBoolean(data, JAVA_GENERATE_STATIC_CREATORS, false)); return metadata; } - public InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - { + public InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) { return new JavaInterfaceMetadata(); } - public FieldMetadata getFieldMetadata( ModelField field, Map data ) - { + public FieldMetadata getFieldMetadata(ModelField field, Map data) { JavaFieldMetadata metadata = new JavaFieldMetadata(); - metadata.setGetter( getBoolean( data, JAVA_GETTER, true ) ); + metadata.setGetter(getBoolean(data, JAVA_GETTER, true)); String fieldType = field.getType(); - metadata.setBooleanGetter( ( fieldType != null ) && fieldType.endsWith( "oolean" ) ); + metadata.setBooleanGetter((fieldType != null) && fieldType.endsWith("oolean")); - metadata.setSetter( getBoolean( data, JAVA_SETTER, true ) ); + metadata.setSetter(getBoolean(data, JAVA_SETTER, true)); return metadata; } - public AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - { + public AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) { JavaAssociationMetadata metadata = new JavaAssociationMetadata(); - metadata.setAdder( getBoolean( data, JAVA_ADDER, true ) ); + metadata.setAdder(getBoolean(data, JAVA_ADDER, true)); - metadata.setBidi( getBoolean( data, JAVA_BIDI, true ) ); + metadata.setBidi(getBoolean(data, JAVA_BIDI, true)); - metadata.setInterfaceName( getString( data, JAVA_USE_INTERFACE ) ); + metadata.setInterfaceName(getString(data, JAVA_USE_INTERFACE)); - metadata.setInitializationMode( getString( data, JAVA_INIT ) ); + metadata.setInitializationMode(getString(data, JAVA_INIT)); - metadata.setCloneMode( getString( data, JAVA_CLONE ) ); + metadata.setCloneMode(getString(data, JAVA_CLONE)); return metadata; } diff --git a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaModelMetadata.java b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaModelMetadata.java index 957695ddb..47b214b2f 100644 --- a/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaModelMetadata.java +++ b/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/metadata/JavaModelMetadata.java @@ -27,20 +27,16 @@ /** * @author Emmanuel Venisse */ -public class JavaModelMetadata - implements ModelMetadata -{ +public class JavaModelMetadata implements ModelMetadata { public static final String ID = JavaModelMetadata.class.getName(); private boolean suppressAllWarnings = true; - public void setSuppressAllWarnings( boolean suppressAllWarnings ) - { + public void setSuppressAllWarnings(boolean suppressAllWarnings) { this.suppressAllWarnings = suppressAllWarnings; } - public boolean isSuppressAllWarnings() - { + public boolean isSuppressAllWarnings() { return suppressAllWarnings; } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractAnnotationsVerifier.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractAnnotationsVerifier.java index ecd404427..7c3c8eb79 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractAnnotationsVerifier.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractAnnotationsVerifier.java @@ -22,39 +22,31 @@ * SOFTWARE. */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.lang.annotation.Annotation; import org.codehaus.modello.verifier.Verifier; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + /** * @author Hervé Boutemy */ -public abstract class AbstractAnnotationsVerifier - extends Verifier -{ - protected void assertAnnotations( String message, Annotation[] annotations, Class... classes ) - { - assertEquals( classes.length, annotations.length ); +public abstract class AbstractAnnotationsVerifier extends Verifier { + protected void assertAnnotations(String message, Annotation[] annotations, Class... classes) { + assertEquals(classes.length, annotations.length); - for ( Class expectedClass : classes ) - { + for (Class expectedClass : classes) { boolean found = false; - for ( Annotation annotation : annotations ) - { - if ( expectedClass.equals( annotation.annotationType() ) ) - { + for (Annotation annotation : annotations) { + if (expectedClass.equals(annotation.annotationType())) { found = true; break; } } - if ( !found ) - { - fail( message + " is missing annotation: " + expectedClass ); + if (!found) { + fail(message + " is missing annotation: " + expectedClass); } } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractPrincipal.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractPrincipal.java index ef349625b..8bf54494b 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractPrincipal.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AbstractPrincipal.java @@ -5,17 +5,14 @@ * * @author Joakim Erdfelt */ -public abstract class AbstractPrincipal -{ +public abstract class AbstractPrincipal { private int principal; - public int getPrincipal() - { + public int getPrincipal() { return principal; } - public void setPrincipal( int principal ) - { + public void setPrincipal(int principal) { this.principal = principal; } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJava4GeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJava4GeneratorTest.java index 7d7d24a5d..7ed30ebdf 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJava4GeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJava4GeneratorTest.java @@ -31,25 +31,20 @@ /** * Check that annotations are not added to generated sources when Java 5 features are not enabled. */ -public class AnnotationsJava4GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public AnnotationsJava4GeneratorTest() - { - super( "annotations-java4" ); +public class AnnotationsJava4GeneratorTest extends AbstractModelloJavaGeneratorTest { + public AnnotationsJava4GeneratorTest() { + super("annotations-java4"); } - public void testJava4GeneratorWithAnnotations() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJava4GeneratorWithAnnotations() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/annotations.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/annotations.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); } -} \ No newline at end of file +} diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJavaGeneratorTest.java index ca4912097..9732f816b 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AnnotationsJavaGeneratorTest.java @@ -31,34 +31,28 @@ /** * @version $Id: TmpJavaGeneratorTest.java 1125 2009-01-10 20:29:32Z hboutemy $ */ -public class AnnotationsJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public AnnotationsJavaGeneratorTest() - { - super( "annotations" ); +public class AnnotationsJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public AnnotationsJavaGeneratorTest() { + super("annotations"); } - public void testJavaGeneratorWithAnnotations() - throws Throwable - { - if ( skipJava5FeatureTest() ) - { + public void testJavaGeneratorWithAnnotations() throws Throwable { + if (skipJava5FeatureTest()) { return; } - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/annotations.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/annotations.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); + Properties parameters = getModelloParameters("1.0.0", 5); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); - addDependency( "javax.xml.bind", "jaxb-api" ); - addDependency( "javax.persistence", "persistence-api" ); - compileGeneratedSources( 5 ); + addDependency("javax.xml.bind", "jaxb-api"); + addDependency("javax.persistence", "persistence-api"); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "AnnotationsVerifier" ); + verifyCompiledGeneratedSources("AnnotationsVerifier"); } -} \ No newline at end of file +} diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AssociationGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AssociationGeneratorTest.java index 3e65e6a65..942bc170b 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AssociationGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/AssociationGeneratorTest.java @@ -22,36 +22,31 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Trygve Laugstøl */ -public class AssociationGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public AssociationGeneratorTest() - { - super( "oneToManyAssociation" ); +public class AssociationGeneratorTest extends AbstractModelloJavaGeneratorTest { + public AssociationGeneratorTest() { + super("oneToManyAssociation"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/oneToManyAssociation.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/oneToManyAssociation.mdo")); - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - verifyCompiledGeneratedSources( "OneToManyAssociationVerifier" ); + verifyCompiledGeneratedSources("OneToManyAssociationVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BiDirectionalOverrideJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BiDirectionalOverrideJavaGeneratorTest.java index b4ae7b010..f9c1bb2b7 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BiDirectionalOverrideJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BiDirectionalOverrideJavaGeneratorTest.java @@ -16,38 +16,33 @@ * limitations under the License. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * BiDirectionalOverrideJavaGeneratorTest * * @author Joakim Erdfelt */ -public class BiDirectionalOverrideJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public BiDirectionalOverrideJavaGeneratorTest() - { - super( "bidirectional" ); +public class BiDirectionalOverrideJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public BiDirectionalOverrideJavaGeneratorTest() { + super("bidirectional"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/bidirectional-override.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/bidirectional-override.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - verifyCompiledGeneratedSources( "JavaVerifier" ); + verifyCompiledGeneratedSources("JavaVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BuilderJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BuilderJavaGeneratorTest.java index b2262356f..f667ebca3 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BuilderJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/BuilderJavaGeneratorTest.java @@ -30,45 +30,37 @@ import org.codehaus.modello.model.Model; import org.codehaus.plexus.util.FileUtils; -public class BuilderJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public BuilderJavaGeneratorTest() - { - super( "builder" ); +public class BuilderJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public BuilderJavaGeneratorTest() { + super("builder"); } /** * MODELLO-83 * @throws Exception if any exception occurs */ - public void testJavaGeneratorWithBuilder() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGeneratorWithBuilder() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/builder.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/builder.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - verifyClass( "Bundles" ); - verifyClass( "StartLevel" ); - verifyClass( "Bundle" ); + verifyClass("Bundles"); + verifyClass("StartLevel"); + verifyClass("Bundle"); } - private void verifyClass( String className ) - throws Exception - { - File source = new File( getOutputDirectory(), "org/codehaus/modello/builder/" + className + ".java" ); + private void verifyClass(String className) throws Exception { + File source = new File(getOutputDirectory(), "org/codehaus/modello/builder/" + className + ".java"); - String sourceGenerated = FileUtils.fileRead( source ); + String sourceGenerated = FileUtils.fileRead(source); - assertTrue( sourceGenerated.contains( "public static final class Builder" ) ); - assertTrue( sourceGenerated.contains( "public " + className + " build()" ) ); + assertTrue(sourceGenerated.contains("public static final class Builder")); + assertTrue(sourceGenerated.contains("public " + className + " build()")); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesJava5GeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesJava5GeneratorTest.java index c08939528..c13d149e8 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesJava5GeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesJava5GeneratorTest.java @@ -22,42 +22,35 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Benjamin Bentmann */ -public class FeaturesJava5GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesJava5GeneratorTest() - { - super( "features-java5" ); +public class FeaturesJava5GeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesJava5GeneratorTest() { + super("features-java5"); } - public void testJavaGenerator() - throws Throwable - { - if ( skipJava5FeatureTest() ) - { + public void testJavaGenerator() throws Throwable { + if (skipJava5FeatureTest()) { return; } - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "2.0.0", 5 ); + Properties parameters = getModelloParameters("2.0.0", 5); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); - compileGeneratedSources( "features", 5 ); + compileGeneratedSources("features", 5); - verifyCompiledGeneratedSources( "JavaVerifier" ); + verifyCompiledGeneratedSources("JavaVerifier"); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesVersionJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesVersionJavaGeneratorTest.java index dc017fa3a..6d99b9dc0 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesVersionJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/FeaturesVersionJavaGeneratorTest.java @@ -22,47 +22,41 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesVersionJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesVersionJavaGeneratorTest() - { - super( "features-version" ); +public class FeaturesVersionJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesVersionJavaGeneratorTest() { + super("features-version"); } private static final String ALL_VERSIONS = "1.0.0,1.5.0,2.0.0,3.0.0"; - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); Properties parameters = getModelloParameters(); - parameters.setProperty( ModelloParameterConstants.ALL_VERSIONS, ALL_VERSIONS ); - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); + parameters.setProperty(ModelloParameterConstants.ALL_VERSIONS, ALL_VERSIONS); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); - String[] versions = ALL_VERSIONS.split( "," ); + String[] versions = ALL_VERSIONS.split(","); - for ( String version : versions ) - { - parameters.setProperty( ModelloParameterConstants.VERSION, version ); - modello.generate( model, "java", parameters ); + for (String version : versions) { + parameters.setProperty(ModelloParameterConstants.VERSION, version); + modello.generate(model, "java", parameters); } compileGeneratedSources(); - verifyCompiledGeneratedSources( "JavaVerifier" ); + verifyCompiledGeneratedSources("JavaVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/InterfaceAssociationTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/InterfaceAssociationTest.java index c5bd3a99e..538e8cf36 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/InterfaceAssociationTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/InterfaceAssociationTest.java @@ -6,33 +6,26 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -public class InterfaceAssociationTest - extends AbstractModelloJavaGeneratorTest -{ - public InterfaceAssociationTest() - { - super( "interfaceAssociationTest" ); +public class InterfaceAssociationTest extends AbstractModelloJavaGeneratorTest { + public InterfaceAssociationTest() { + super("interfaceAssociationTest"); } - public void testJavaGenerator() - throws Throwable - { - if ( skipJava5FeatureTest() ) - { + public void testJavaGenerator() throws Throwable { + if (skipJava5FeatureTest()) { return; } - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/interfaceAssociation.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/interfaceAssociation.mdo")); - Properties parameters = getModelloParameters( "4.0.0", 5 ); + Properties parameters = getModelloParameters("4.0.0", 5); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "InterfaceAssociationVerifier" ); + verifyCompiledGeneratedSources("InterfaceAssociationVerifier"); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/JavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/JavaGeneratorTest.java index 865f272c3..8af8da190 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/JavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/JavaGeneratorTest.java @@ -22,36 +22,31 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Trygve Laugstøl */ -public class JavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public JavaGeneratorTest() - { - super( "java" ); +public class JavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public JavaGeneratorTest() { + super("java"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/maven.mdo")); - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - verifyCompiledGeneratedSources( "JavaVerifier" ); + verifyCompiledGeneratedSources("JavaVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/LocationsJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/LocationsJavaGeneratorTest.java index 2243600e9..1a9bf2779 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/LocationsJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/LocationsJavaGeneratorTest.java @@ -22,38 +22,32 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Benjamin Bentmann */ -public class LocationsJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ +public class LocationsJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { - public LocationsJavaGeneratorTest() - { - super( "locations" ); + public LocationsJavaGeneratorTest() { + super("locations"); } - public void testLocations() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testLocations() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/locations.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/locations.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 7 ); + Properties parameters = getModelloParameters("1.0.0", 7); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); - compileGeneratedSources( 7 ); + compileGeneratedSources(7); - verifyCompiledGeneratedSources( "JavaLocationsVerifier" ); + verifyCompiledGeneratedSources("JavaLocationsVerifier"); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/PackageVersionJavaTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/PackageVersionJavaTest.java index 55ecf2ba3..3a84974ca 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/PackageVersionJavaTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/PackageVersionJavaTest.java @@ -22,38 +22,33 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Trygve Laugstøl */ -public class PackageVersionJavaTest - extends AbstractModelloJavaGeneratorTest -{ - public PackageVersionJavaTest() - { - super( "packageversion" ); +public class PackageVersionJavaTest extends AbstractModelloJavaGeneratorTest { + public PackageVersionJavaTest() { + super("packageversion"); } - public void testThatTheCorrectVersionIsInThePackageName() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testThatTheCorrectVersionIsInThePackageName() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/maven.mdo")); - Properties parameters = getModelloParameters( "4.0.0" ); - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); + Properties parameters = getModelloParameters("4.0.0"); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - verifyCompiledGeneratedSources( "PackageVersionVerifier" ); + verifyCompiledGeneratedSources("PackageVersionVerifier"); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Permission.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Permission.java index 934c6b7cd..4585afb81 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Permission.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Permission.java @@ -17,13 +17,12 @@ */ /** - * Test Interface used by to ensure that interface overrides can be used. + * Test Interface used by to ensure that interface overrides can be used. * * @author Joakim Erdfelt */ -public interface Permission -{ +public interface Permission { public String getName(); - public void setName( String name ); + public void setName(String name); } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Role.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Role.java index 8a3da1881..b17c3b3f5 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Role.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/Role.java @@ -23,8 +23,7 @@ * * @author Joakim Erdfelt */ -public interface Role -{ +public interface Role { public String getName(); public void setName(String name); diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/StaticCreatorJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/StaticCreatorJavaGeneratorTest.java index 5299cdee9..2d4aaa6ce 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/StaticCreatorJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/StaticCreatorJavaGeneratorTest.java @@ -30,32 +30,26 @@ import org.codehaus.modello.model.Model; import org.codehaus.plexus.util.FileUtils; -public class StaticCreatorJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public StaticCreatorJavaGeneratorTest() - { - super( "static-creator" ); +public class StaticCreatorJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public StaticCreatorJavaGeneratorTest() { + super("static-creator"); } - public void testJavaGeneratorWithStaticCreator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGeneratorWithStaticCreator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/static-creator.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/static-creator.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); - File source = new File( getOutputDirectory(), "org/codehaus/modello/staticcreator/Bundle.java" ); + File source = new File(getOutputDirectory(), "org/codehaus/modello/staticcreator/Bundle.java"); - String sourceGenerated = FileUtils.fileRead( source ); + String sourceGenerated = FileUtils.fileRead(source); - assertTrue( sourceGenerated.contains( "public static Bundle newBundleInstance(" ) ); + assertTrue(sourceGenerated.contains("public static Bundle newBundleInstance(")); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/TmpJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/TmpJavaGeneratorTest.java index 2aced8f94..790d6e403 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/TmpJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/TmpJavaGeneratorTest.java @@ -22,40 +22,35 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * MODELLO-83: check that tmp can be used as a field name without interference with generated code for * hashCode(). * * @author Vincent Siveton */ -public class TmpJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public TmpJavaGeneratorTest() - { - super( "tmp" ); +public class TmpJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public TmpJavaGeneratorTest() { + super("tmp"); } /** * MODELLO-83 * @throws Exception if any exception occurs */ - public void testJavaGeneratorWithTmp() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGeneratorWithTmp() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/tmp.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/tmp.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/ToStringJavaGeneratorTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/ToStringJavaGeneratorTest.java index 1ab149a2b..561a15e74 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/ToStringJavaGeneratorTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/ToStringJavaGeneratorTest.java @@ -22,47 +22,42 @@ * SOFTWARE. */ +import java.io.File; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; import org.codehaus.plexus.util.FileUtils; -import java.io.File; -import java.util.Properties; - /** * check toString() method is generated. * * @author Olivier Lamy */ -public class ToStringJavaGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public ToStringJavaGeneratorTest() - { - super( "tostring" ); +public class ToStringJavaGeneratorTest extends AbstractModelloJavaGeneratorTest { + public ToStringJavaGeneratorTest() { + super("tostring"); } /** * @throws Exception if any exception occurs */ - public void testJavaGeneratorWithToString() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGeneratorWithToString() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/models/tostring.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/models/tostring.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); + modello.generate(model, "java", parameters); compileGeneratedSources(); File source = new File(getOutputDirectory(), "foo/bar/tostring/MyClass.java"); - String sourceGenerated = FileUtils.fileRead( source ); + String sourceGenerated = FileUtils.fileRead(source); - assertTrue( sourceGenerated.contains( "public java.lang.String toString()" ) ); + assertTrue(sourceGenerated.contains("public java.lang.String toString()")); } } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JMapTypeTestCase.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JMapTypeTestCase.java index 54ab4c6e1..68c449ed6 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JMapTypeTestCase.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JMapTypeTestCase.java @@ -6,50 +6,41 @@ * @author Simone Tripodi * @since 1.8 */ -public final class JMapTypeTestCase - extends TestCase -{ +public final class JMapTypeTestCase extends TestCase { - public void testJava5PropertiesType() - { - JMapType mapType = new JMapType( "java.util.Properties", new JClass( "String" ), true ); + public void testJava5PropertiesType() { + JMapType mapType = new JMapType("java.util.Properties", new JClass("String"), true); - assertEquals( "java.util.Properties", mapType.toString() ); + assertEquals("java.util.Properties", mapType.toString()); } - public void testJava4PropertiesType() - { - JMapType mapType = new JMapType( "java.util.Properties", new JClass( "String" ), false ); + public void testJava4PropertiesType() { + JMapType mapType = new JMapType("java.util.Properties", new JClass("String"), false); - assertEquals( "java.util.Properties", mapType.toString() ); + assertEquals("java.util.Properties", mapType.toString()); } - public void testJava5MapType() - { - JMapType mapType = new JMapType( "java.util.Map", new JClass( "String" ), true ); + public void testJava5MapType() { + JMapType mapType = new JMapType("java.util.Map", new JClass("String"), true); - assertEquals( "java.util.Map", mapType.toString() ); + assertEquals("java.util.Map", mapType.toString()); } - public void testJava5MapInitialization() - { - JMapType mapType = new JMapType( "java.util.Map", "new java.util.HashMap()", new JClass( "String" ), true ); + public void testJava5MapInitialization() { + JMapType mapType = new JMapType("java.util.Map", "new java.util.HashMap()", new JClass("String"), true); - assertEquals( "new java.util.HashMap()", mapType.getInstanceName() ); + assertEquals("new java.util.HashMap()", mapType.getInstanceName()); } - public void testJava4MapType() - { - JMapType mapType = new JMapType( "java.util.Map", new JClass( "String" ), false ); + public void testJava4MapType() { + JMapType mapType = new JMapType("java.util.Map", new JClass("String"), false); - assertEquals( "java.util.Map/**/", mapType.toString() ); + assertEquals("java.util.Map/**/", mapType.toString()); } - public void testJava4MapInitialization() - { - JMapType mapType = new JMapType( "java.util.Map", "new java.util.HashMap()", new JClass( "String" ), false ); + public void testJava4MapInitialization() { + JMapType mapType = new JMapType("java.util.Map", "new java.util.HashMap()", new JClass("String"), false); - assertEquals( "new java.util.HashMap/**/()", mapType.getInstanceName() ); + assertEquals("new java.util.HashMap/**/()", mapType.getInstanceName()); } - } diff --git a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JavaSourceTest.java b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JavaSourceTest.java index b86280ea5..430e486bb 100644 --- a/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JavaSourceTest.java +++ b/modello-plugins/modello-plugin-java/src/test/java/org/codehaus/modello/plugin/java/javasource/JavaSourceTest.java @@ -4,167 +4,160 @@ import org.codehaus.modello.AbstractModelloGeneratorTest; -public class JavaSourceTest - extends AbstractModelloGeneratorTest -{ - public JavaSourceTest() - { - super( "javasource" ); +public class JavaSourceTest extends AbstractModelloGeneratorTest { + public JavaSourceTest() { + super("javasource"); } - public void testJavaSource() - { + public void testJavaSource() { checkJClass(); checkJCompUnit(); checkJInterface(); } - private void checkJClass() - { - JClass testClass = new JClass( "org.acme.JClassTest" ); + private void checkJClass() { + JClass testClass = new JClass("org.acme.JClassTest"); - testClass.addSourceCode( "// source code" ); - testClass.addSourceCode( "// source code 2" ); + testClass.addSourceCode("// source code"); + testClass.addSourceCode("// source code 2"); - testClass.addImport( "java.util.Vector" ); - testClass.appendAnnotation( "@SuppressWarnings( \"all\" )" ); - testClass.appendAnnotation( "@Deprecated" ); - testClass.addMember( new JField( JType.INT, "x" ) ); - JClass jcString = new JClass( "String" ); + testClass.addImport("java.util.Vector"); + testClass.appendAnnotation("@SuppressWarnings( \"all\" )"); + testClass.appendAnnotation("@Deprecated"); + testClass.addMember(new JField(JType.INT, "x")); + JClass jcString = new JClass("String"); JField field = null; - field = new JField( JType.INT, "_z" ); - field.appendAnnotation( "@Deprecated" ); - field.getModifiers().setStatic( true ); - testClass.addField( field ); + field = new JField(JType.INT, "_z"); + field.appendAnnotation("@Deprecated"); + field.getModifiers().setStatic(true); + testClass.addField(field); - testClass.getStaticInitializationCode().add( "_z = 75;" ); + testClass.getStaticInitializationCode().add("_z = 75;"); - field = new JField( jcString, "myString" ); + field = new JField(jcString, "myString"); field.getModifiers().makePrivate(); - testClass.addMember( field ); + testClass.addMember(field); // generics test - JType type = new JCollectionType( "java.util.List", jcString, true ); - field = new JField( type, "generics" ); - testClass.addMember( field ); + JType type = new JCollectionType("java.util.List", jcString, true); + field = new JField(type, "generics"); + testClass.addMember(field); - type = new JCollectionType( "java.util.List", jcString, false ); - field = new JField( type, "noGenerics" ); - testClass.addMember( field ); + type = new JCollectionType("java.util.List", jcString, false); + field = new JField(type, "noGenerics"); + testClass.addMember(field); - //-- create constructor + // -- create constructor JConstructor cons = testClass.createConstructor(); - cons.appendAnnotation( "@Deprecated" ); - cons.getSourceCode().add( "this.x = 6;" ); - - JMethod jMethod = new JMethod( "getX", JType.INT, null ); - jMethod.appendAnnotation( "@Deprecated" ); - jMethod.setSourceCode( "return this.x;" ); - testClass.addMethod( jMethod ); - - jMethod = new JMethod( "setX", null, null ); - JParameter param = new JParameter( JType.INT, "x" ); - jMethod.addParameter( param ); - jMethod.setSourceCode( "this.x = x;" ); - testClass.addMethod( jMethod ); - - jMethod = new JMethod( "checkParameterAnotation", JType.INT, null ); - param = new JParameter( JType.LONG, "param" ); - param.appendAnnotation( "@Test" ); - param.appendAnnotation( "@Test2" ); - jMethod.addParameter( param ); - jMethod.setSourceCode( "return param;" ); - testClass.addMethod( jMethod ); - - //-- create inner-class - JClass innerClass = testClass.createInnerClass( "Foo" ); - innerClass.appendAnnotation( "@Deprecated" ); - innerClass.addImport( "java.util.Hashtable" ); - innerClass.addMember( new JField( JType.INT, "_type" ) ); - - field = new JField( jcString, "_name" ); + cons.appendAnnotation("@Deprecated"); + cons.getSourceCode().add("this.x = 6;"); + + JMethod jMethod = new JMethod("getX", JType.INT, null); + jMethod.appendAnnotation("@Deprecated"); + jMethod.setSourceCode("return this.x;"); + testClass.addMethod(jMethod); + + jMethod = new JMethod("setX", null, null); + JParameter param = new JParameter(JType.INT, "x"); + jMethod.addParameter(param); + jMethod.setSourceCode("this.x = x;"); + testClass.addMethod(jMethod); + + jMethod = new JMethod("checkParameterAnotation", JType.INT, null); + param = new JParameter(JType.LONG, "param"); + param.appendAnnotation("@Test"); + param.appendAnnotation("@Test2"); + jMethod.addParameter(param); + jMethod.setSourceCode("return param;"); + testClass.addMethod(jMethod); + + // -- create inner-class + JClass innerClass = testClass.createInnerClass("Foo"); + innerClass.appendAnnotation("@Deprecated"); + innerClass.addImport("java.util.Hashtable"); + innerClass.addMember(new JField(JType.INT, "_type")); + + field = new JField(jcString, "_name"); field.getModifiers().makePrivate(); - innerClass.addMember( field ); + innerClass.addMember(field); - testClass.createInnerClass( "Bar" ); + testClass.createInnerClass("Bar"); - //-- create constructor + // -- create constructor cons = innerClass.createConstructor(); - cons.getSourceCode().add( "_name = \"foo\";" ); + cons.getSourceCode().add("_name = \"foo\";"); - jMethod = new JMethod( "getName", jcString, null ); - jMethod.setSourceCode( "return _name;" ); - innerClass.addMethod( jMethod ); + jMethod = new JMethod("getName", jcString, null); + jMethod.setSourceCode("return _name;"); + innerClass.addMethod(jMethod); - testClass.print( getOutputDirectory().toString(), null ); + testClass.print(getOutputDirectory().toString(), null); - assertTrue( new File( getOutputDirectory(), "org/acme/JClassTest.java" ).exists() ); + assertTrue(new File(getOutputDirectory(), "org/acme/JClassTest.java").exists()); } - private void checkJCompUnit() - { - JCompUnit unit = new JCompUnit( "com.acme", "JCompUnitTest.java" ); + private void checkJCompUnit() { + JCompUnit unit = new JCompUnit("com.acme", "JCompUnitTest.java"); - JClass testClass = new JClass( "Test" ); + JClass testClass = new JClass("Test"); - testClass.addImport( "java.util.Vector" ); - testClass.addMember( new JField( JType.INT, "x" ) ); + testClass.addImport("java.util.Vector"); + testClass.addMember(new JField(JType.INT, "x")); JField field = null; - field = new JField( JType.INT, "_z" ); - field.getModifiers().setStatic( true ); - testClass.addField( field ); + field = new JField(JType.INT, "_z"); + field.getModifiers().setStatic(true); + testClass.addField(field); - testClass.getStaticInitializationCode().add( "_z = 75;" ); + testClass.getStaticInitializationCode().add("_z = 75;"); - JClass jcString = new JClass( "String" ); - field = new JField( jcString, "myString" ); + JClass jcString = new JClass("String"); + field = new JField(jcString, "myString"); field.getModifiers().makePrivate(); - testClass.addMember( field ); + testClass.addMember(field); // -- create constructor JConstructor cons = testClass.createConstructor(); - testClass.addConstructor( cons ); - cons.getSourceCode().add( "this.x = 6;" ); + testClass.addConstructor(cons); + cons.getSourceCode().add("this.x = 6;"); - JMethod jMethod = new JMethod( "getX", JType.INT, null ); - jMethod.setSourceCode( "return this.x;" ); - testClass.addMethod( jMethod ); + JMethod jMethod = new JMethod("getX", JType.INT, null); + jMethod.setSourceCode("return this.x;"); + testClass.addMethod(jMethod); - unit.addClass( testClass ); + unit.addClass(testClass); - JClass fooClass = new JClass( "Foo" ); - unit.addClass( fooClass ); + JClass fooClass = new JClass("Foo"); + unit.addClass(fooClass); - unit.print( getOutputDirectory().toString(), null ); + unit.print(getOutputDirectory().toString(), null); - assertTrue( new File( getOutputDirectory(), "com/acme/JCompUnitTest.java" ).exists() ); + assertTrue(new File(getOutputDirectory(), "com/acme/JCompUnitTest.java").exists()); } - private void checkJInterface() - { - JInterface jInterface = new JInterface( "InterfaceTest" ); + private void checkJInterface() { + JInterface jInterface = new JInterface("InterfaceTest"); // -- add an import - jInterface.addImport( "java.util.Vector" ); - JClass jString = new JClass( "String" ); + jInterface.addImport("java.util.Vector"); + JClass jString = new JClass("String"); // -- add an interface - jInterface.addInterface( "java.io.Serializable" ); + jInterface.addInterface("java.io.Serializable"); // -- add a static field - JField jField = new JField( new JClass( "java.lang.String" ), "TEST" ); - jField.setInitString( "\"Test\"" ); - jField.getModifiers().setStatic( true ); + JField jField = new JField(new JClass("java.lang.String"), "TEST"); + jField.setInitString("\"Test\""); + jField.getModifiers().setStatic(true); jField.getModifiers().makePublic(); - jInterface.addField( jField ); + jInterface.addField(jField); // -- add a method signature - JMethodSignature jMethodSig = new JMethodSignature( "getName", jString ); - jInterface.addMethod( jMethodSig ); - jInterface.print( getOutputDirectory().toString(), null ); + JMethodSignature jMethodSig = new JMethodSignature("getName", jString); + jInterface.addMethod(jMethodSig); + jInterface.print(getOutputDirectory().toString(), null); - assertTrue( new File( getOutputDirectory(), "InterfaceTest.java" ).exists() ); + assertTrue(new File(getOutputDirectory(), "InterfaceTest.java").exists()); } } diff --git a/modello-plugins/modello-plugin-jdom/pom.xml b/modello-plugins/modello-plugin-jdom/pom.xml index 60047ba03..dd57defc8 100644 --- a/modello-plugins/modello-plugin-jdom/pom.xml +++ b/modello-plugins/modello-plugin-jdom/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-jdom Modello JDOM Plugin - - Modello JDOM Plugin generates XML writers based on JDOM API. - + Modello JDOM Plugin generates XML writers based on JDOM API. diff --git a/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/AbstractJDOMGenerator.java b/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/AbstractJDOMGenerator.java index 6a9d942d1..73ce68b16 100644 --- a/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/AbstractJDOMGenerator.java +++ b/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/AbstractJDOMGenerator.java @@ -27,7 +27,4 @@ /** * @author Trygve Laugstøl */ -public abstract class AbstractJDOMGenerator - extends AbstractXmlJavaGenerator -{ -} +public abstract class AbstractJDOMGenerator extends AbstractXmlJavaGenerator {} diff --git a/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/JDOMWriterGenerator.java b/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/JDOMWriterGenerator.java index cde0db2b2..9b11fafed 100644 --- a/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/JDOMWriterGenerator.java +++ b/modello-plugins/modello-plugin-jdom/src/main/java/org/codehaus/modello/plugin/jdom/JDOMWriterGenerator.java @@ -16,6 +16,11 @@ */ package org.codehaus.modello.plugin.jdom; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -38,723 +43,652 @@ import org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata; import org.codehaus.plexus.component.annotations.Component; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - /** * @author mkleint@codehaus.org */ -@Component( role = ModelloGenerator.class, hint = "jdom-writer" ) -public class JDOMWriterGenerator - extends AbstractJDOMGenerator -{ +@Component(role = ModelloGenerator.class, hint = "jdom-writer") +public class JDOMWriterGenerator extends AbstractJDOMGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateJDOMWriter(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating JDOM Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating JDOM Writer.", ex); } } - private void generateJDOMWriter() - throws ModelloException, IOException - { + private void generateJDOMWriter() throws ModelloException, IOException { Model objectModel = getModel(); String packageName = - objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) + ".io.jdom"; + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.jdom"; - String marshallerName = getFileName( "JDOMWriter" ); + String marshallerName = getFileName("JDOMWriter"); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); // ------------------------------------------------------------- // imports now // ------------------------------------------------------------- - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.OutputStreamWriter" ); - jClass.addImport( "java.io.Writer" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.util.ArrayList" ); - jClass.addImport( "java.util.Arrays" ); - jClass.addImport( "java.util.Collection" ); - jClass.addImport( "java.util.Iterator" ); - jClass.addImport( "java.util.List" ); - jClass.addImport( "java.util.ListIterator" ); - jClass.addImport( "java.util.Locale" ); - jClass.addImport( "java.util.Map" ); - jClass.addImport( "java.util.Properties" ); - jClass.addImport( "org.jdom2.Content" ); - jClass.addImport( "org.jdom2.DefaultJDOMFactory" ); - jClass.addImport( "org.jdom2.Document" ); - jClass.addImport( "org.jdom2.Element" ); - jClass.addImport( "org.jdom2.JDOMFactory" ); - jClass.addImport( "org.jdom2.Namespace" ); - jClass.addImport( "org.jdom2.Parent" ); - jClass.addImport( "org.jdom2.Text" ); - jClass.addImport( "org.jdom2.output.Format" ); - jClass.addImport( "org.jdom2.output.XMLOutputter" ); - - addModelImports( jClass, null ); - - JField factoryField = new JField( new JClass( "JDOMFactory" ), "factory" ); - factoryField.getModifiers().setFinal( true ); - jClass.addField( factoryField ); - - JField lineSeparatorField = new JField( new JClass( "String" ), "lineSeparator" ); - lineSeparatorField.getModifiers().setFinal( true ); - jClass.addField( lineSeparatorField ); - - createCounter( jClass ); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.OutputStreamWriter"); + jClass.addImport("java.io.Writer"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.util.ArrayList"); + jClass.addImport("java.util.Arrays"); + jClass.addImport("java.util.Collection"); + jClass.addImport("java.util.Iterator"); + jClass.addImport("java.util.List"); + jClass.addImport("java.util.ListIterator"); + jClass.addImport("java.util.Locale"); + jClass.addImport("java.util.Map"); + jClass.addImport("java.util.Properties"); + jClass.addImport("org.jdom2.Content"); + jClass.addImport("org.jdom2.DefaultJDOMFactory"); + jClass.addImport("org.jdom2.Document"); + jClass.addImport("org.jdom2.Element"); + jClass.addImport("org.jdom2.JDOMFactory"); + jClass.addImport("org.jdom2.Namespace"); + jClass.addImport("org.jdom2.Parent"); + jClass.addImport("org.jdom2.Text"); + jClass.addImport("org.jdom2.output.Format"); + jClass.addImport("org.jdom2.output.XMLOutputter"); + + addModelImports(jClass, null); + + JField factoryField = new JField(new JClass("JDOMFactory"), "factory"); + factoryField.getModifiers().setFinal(true); + jClass.addField(factoryField); + + JField lineSeparatorField = new JField(new JClass("String"), "lineSeparator"); + lineSeparatorField.getModifiers().setFinal(true); + jClass.addField(lineSeparatorField); + + createCounter(jClass); // constructor -- JConstructor constructor = jClass.createConstructor(); JSourceCode constCode = constructor.getSourceCode(); - constCode.add( "this( new DefaultJDOMFactory() );" ); + constCode.add("this( new DefaultJDOMFactory() );"); constructor = jClass.createConstructor(); - constructor.addParameter( new JParameter( new JClass( "JDOMFactory" ), "factory" ) ); + constructor.addParameter(new JParameter(new JClass("JDOMFactory"), "factory")); constCode = constructor.getSourceCode(); - constCode.add( "this.factory = factory;" ); - constCode.add( "this.lineSeparator = \"\\n\";" ); + constCode.add("this.factory = factory;"); + constCode.add("this.lineSeparator = \"\\n\";"); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - String rootElement = resolveTagName( rootClass ); + String rootElement = resolveTagName(rootClass); // the public global write method.. - jClass.addMethod( generateWriteModel2( root, rootElement ) ); - jClass.addMethod( generateWriteModel3( root, rootElement ) ); + jClass.addMethod(generateWriteModel2(root, rootElement)); + jClass.addMethod(generateWriteModel3(root, rootElement)); // the private utility classes; - jClass.addMethods( generateUtilityMethods() ); + jClass.addMethods(generateUtilityMethods()); - writeAllClasses( objectModel, jClass, rootClass ); + writeAllClasses(objectModel, jClass, rootClass); - if ( requiresDomSupport ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); - jClass.addMethods( generateDomMethods() ); + if (requiresDomSupport) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); + jClass.addMethods(generateDomMethods()); } - - try ( JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ) ) - { - jClass.print( sourceWriter ); + + try (JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName)) { + jClass.print(sourceWriter); } } - private void createCounter( final JClass jClass ) - throws IllegalArgumentException - { + private void createCounter(final JClass jClass) throws IllegalArgumentException { // inner counter class - JClass counter = jClass.createInnerClass( "Counter" ); - counter.getModifiers().setStatic( true ); + JClass counter = jClass.createInnerClass("Counter"); + counter.getModifiers().setStatic(true); - JField fld = new JField( new JType( "int" ), "currentIndex" ); - fld.setInitString( "0" ); - counter.addField( fld ); + JField fld = new JField(new JType("int"), "currentIndex"); + fld.setInitString("0"); + counter.addField(fld); - fld = new JField( new JType( "int" ), "level" ); - counter.addField( fld ); + fld = new JField(new JType("int"), "level"); + counter.addField(fld); JConstructor constr = - counter.createConstructor( new JParameter[] { new JParameter( new JType( "int" ), "depthLevel" ) } ); - constr.getSourceCode().append( "level = depthLevel;" ); + counter.createConstructor(new JParameter[] {new JParameter(new JType("int"), "depthLevel")}); + constr.getSourceCode().append("level = depthLevel;"); - JMethod inc = new JMethod( "increaseCount" ); - inc.getSourceCode().add( "currentIndex = currentIndex + 1;" ); - counter.addMethod( inc ); + JMethod inc = new JMethod("increaseCount"); + inc.getSourceCode().add("currentIndex = currentIndex + 1;"); + counter.addMethod(inc); - JMethod getter = new JMethod( "getCurrentIndex", new JType( "int" ), null ); - getter.getSourceCode().add( "return currentIndex;" ); - counter.addMethod( getter ); + JMethod getter = new JMethod("getCurrentIndex", new JType("int"), null); + getter.getSourceCode().add("return currentIndex;"); + counter.addMethod(getter); - getter = new JMethod( "getDepth", new JType( "int" ), null ); - getter.getSourceCode().add( "return level;" ); - counter.addMethod( getter ); + getter = new JMethod("getDepth", new JType("int"), null); + getter.getSourceCode().add("return level;"); + counter.addMethod(getter); } - private JMethod generateWriteModel2( String root, String rootElement ) - { - String variableName = uncapitalise( root ); + private JMethod generateWriteModel2(String root, String rootElement) { + String variableName = uncapitalise(root); - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( root ), variableName ) ); - marshall.addParameter( new JParameter( new JClass( "OutputStreamWriter" ), "writer" ) ); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addParameter(new JParameter(new JClass(root), variableName)); + marshall.addParameter(new JParameter(new JClass("OutputStreamWriter"), "writer")); + marshall.addException(new JClass("java.io.IOException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "Format format = Format.getRawFormat()" ); - sc.add( " .setEncoding( writer.getEncoding() )" ); - sc.add( " .setLineSeparator( System.getProperty( \"line.separator\" ) );" ); - sc.add( "write( " + variableName + ", writer, format );" ); + sc.add("Format format = Format.getRawFormat()"); + sc.add(" .setEncoding( writer.getEncoding() )"); + sc.add(" .setLineSeparator( System.getProperty( \"line.separator\" ) );"); + sc.add("write( " + variableName + ", writer, format );"); return marshall; - } - private JMethod generateWriteModel3( String root, String rootElement ) - { - String variableName = uncapitalise( root ); + private JMethod generateWriteModel3(String root, String rootElement) { + String variableName = uncapitalise(root); - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( root ), variableName ) ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( "Format" ), "jdomFormat" ) ); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addParameter(new JParameter(new JClass(root), variableName)); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass("Format"), "jdomFormat")); + marshall.addException(new JClass("java.io.IOException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "Document document = factory.document( null );" ); - sc.add( "update" + root + "( " + variableName + ", \"" + rootElement - + "\", new Counter( 0 ), document );" ); - sc.add( "XMLOutputter outputter = new XMLOutputter();" ); - sc.add( "outputter.setFormat( jdomFormat );" ); - sc.add( "outputter.output( document, writer );" ); + sc.add("Document document = factory.document( null );"); + sc.add("update" + root + "( " + variableName + ", \"" + rootElement + "\", new Counter( 0 ), document );"); + sc.add("XMLOutputter outputter = new XMLOutputter();"); + sc.add("outputter.setFormat( jdomFormat );"); + sc.add("outputter.output( document, writer );"); return marshall; - } - private JMethod[] generateUtilityMethods() - { - JMethod findRSElement = new JMethod( "findAndReplaceSimpleElement", new JClass( "Element" ), null ); - findRSElement.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - findRSElement.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - findRSElement.addParameter( new JParameter( new JClass( "String" ), "name" ) ); - findRSElement.addParameter( new JParameter( new JClass( "String" ), "text" ) ); - findRSElement.addParameter( new JParameter( new JClass( "String" ), "defaultValue" ) ); + private JMethod[] generateUtilityMethods() { + JMethod findRSElement = new JMethod("findAndReplaceSimpleElement", new JClass("Element"), null); + findRSElement.addParameter(new JParameter(new JClass("Counter"), "counter")); + findRSElement.addParameter(new JParameter(new JClass("Element"), "parent")); + findRSElement.addParameter(new JParameter(new JClass("String"), "name")); + findRSElement.addParameter(new JParameter(new JClass("String"), "text")); + findRSElement.addParameter(new JParameter(new JClass("String"), "defaultValue")); findRSElement.getModifiers().makeProtected(); JSourceCode sc = findRSElement.getSourceCode(); - sc.add( "if ( ( defaultValue != null ) && ( text != null ) && defaultValue.equals( text ) )" ); - sc.add( "{" ); + sc.add("if ( ( defaultValue != null ) && ( text != null ) && defaultValue.equals( text ) )"); + sc.add("{"); sc.indent(); - sc.add( "Element element = parent.getChild( name, parent.getNamespace() );" ); - sc.add( "// if exist and is default value or if doesn't exist.. just keep the way it is.." ); - sc.add( "if ( ( element != null && defaultValue.equals( element.getText() ) ) || element == null )" ); - sc.add( "{" ); - sc.addIndented( "return element;" ); - sc.add( "}" ); + sc.add("Element element = parent.getChild( name, parent.getNamespace() );"); + sc.add("// if exist and is default value or if doesn't exist.. just keep the way it is.."); + sc.add("if ( ( element != null && defaultValue.equals( element.getText() ) ) || element == null )"); + sc.add("{"); + sc.addIndented("return element;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - - sc.add( "boolean shouldExist = ( text != null ) && ( text.trim().length() > 0 );" ); - sc.add( "Element element = updateElement( counter, parent, name );" ); - sc.add( "if ( shouldExist )" ); - sc.add( "{" ); - sc.addIndented( "element.setText( text );" ); - sc.add( "}" ); - sc.add( "return element;" ); - - JMethod updateElement = new JMethod( "updateElement", new JClass( "Element" ), null ); - updateElement.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - updateElement.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - updateElement.addParameter( new JParameter( new JClass( "String" ), "name" ) ); + sc.add("}"); + + sc.add("boolean shouldExist = ( text != null ) && ( text.trim().length() > 0 );"); + sc.add("Element element = updateElement( counter, parent, name );"); + sc.add("if ( shouldExist )"); + sc.add("{"); + sc.addIndented("element.setText( text );"); + sc.add("}"); + sc.add("return element;"); + + JMethod updateElement = new JMethod("updateElement", new JClass("Element"), null); + updateElement.addParameter(new JParameter(new JClass("Counter"), "counter")); + updateElement.addParameter(new JParameter(new JClass("Element"), "parent")); + updateElement.addParameter(new JParameter(new JClass("String"), "name")); updateElement.getModifiers().makeProtected(); sc = updateElement.getSourceCode(); - sc.add( "Element element = factory.element( name, parent.getNamespace() );" ); - sc.add( "insertAtPreferredLocation( parent, element, counter );" ); - sc.add( "counter.increaseCount();" ); - sc.add( "return element;" ); - - JMethod insAtPref = new JMethod( "insertAtPreferredLocation" ); - insAtPref.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - insAtPref.addParameter( new JParameter( new JClass( "Element" ), "child" ) ); - insAtPref.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); + sc.add("Element element = factory.element( name, parent.getNamespace() );"); + sc.add("insertAtPreferredLocation( parent, element, counter );"); + sc.add("counter.increaseCount();"); + sc.add("return element;"); + + JMethod insAtPref = new JMethod("insertAtPreferredLocation"); + insAtPref.addParameter(new JParameter(new JClass("Element"), "parent")); + insAtPref.addParameter(new JParameter(new JClass("Element"), "child")); + insAtPref.addParameter(new JParameter(new JClass("Counter"), "counter")); insAtPref.getModifiers().makeProtected(); sc = insAtPref.getSourceCode(); - sc.add( "int contentIndex = 0;" ); - sc.add( "int elementCounter = 0;" ); - sc.add( "Iterator it = parent.getContent().iterator();" ); - sc.add( "Text lastText = null;" ); - sc.add( "int offset = 0;" ); - sc.add( "while ( it.hasNext() && elementCounter <= counter.getCurrentIndex() )" ); - sc.add( "{" ); + sc.add("int contentIndex = 0;"); + sc.add("int elementCounter = 0;"); + sc.add("Iterator it = parent.getContent().iterator();"); + sc.add("Text lastText = null;"); + sc.add("int offset = 0;"); + sc.add("while ( it.hasNext() && elementCounter <= counter.getCurrentIndex() )"); + sc.add("{"); sc.indent(); - sc.add( "Object next = it.next();" ); - sc.add( "offset = offset + 1;" ); - sc.add( "if ( next instanceof Element )" ); - sc.add( "{" ); + sc.add("Object next = it.next();"); + sc.add("offset = offset + 1;"); + sc.add("if ( next instanceof Element )"); + sc.add("{"); sc.indent(); - sc.add( "elementCounter = elementCounter + 1;" ); - sc.add( "contentIndex = contentIndex + offset;" ); - sc.add( "offset = 0;" ); + sc.add("elementCounter = elementCounter + 1;"); + sc.add("contentIndex = contentIndex + offset;"); + sc.add("offset = 0;"); sc.unindent(); - sc.add( "}" ); - sc.add( "if ( next instanceof Text && it.hasNext() )" ); - sc.add( "{" ); - sc.addIndented( "lastText = (Text) next;" ); - sc.add( "}" ); + sc.add("}"); + sc.add("if ( next instanceof Text && it.hasNext() )"); + sc.add("{"); + sc.addIndented("lastText = (Text) next;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "if ( lastText != null && lastText.getTextTrim().length() == 0 )" ); - sc.add( "{" ); - sc.addIndented( "lastText = (Text) lastText.clone();" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); + sc.add("}"); + sc.add("if ( lastText != null && lastText.getTextTrim().length() == 0 )"); + sc.add("{"); + sc.addIndented("lastText = (Text) lastText.clone();"); + sc.add("}"); + sc.add("else"); + sc.add("{"); sc.indent(); - sc.add( "String starter = lineSeparator;" ); - sc.add( "for ( int i = 0; i < counter.getDepth(); i++ )" ); - sc.add( "{" ); - sc.addIndented( "starter = starter + \" \"; //TODO make settable?" ); - sc.add( "}" ); - sc.add( "lastText = factory.text( starter );" ); + sc.add("String starter = lineSeparator;"); + sc.add("for ( int i = 0; i < counter.getDepth(); i++ )"); + sc.add("{"); + sc.addIndented("starter = starter + \" \"; //TODO make settable?"); + sc.add("}"); + sc.add("lastText = factory.text( starter );"); sc.unindent(); - sc.add( "}" ); - sc.add( "if ( parent.getContentSize() == 0 )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("if ( parent.getContentSize() == 0 )"); + sc.add("{"); sc.indent(); - sc.add( "Text finalText = (Text) lastText.clone();" ); + sc.add("Text finalText = (Text) lastText.clone();"); sc.add( - "finalText.setText( finalText.getText().substring( 0, finalText.getText().length() - \" \".length() ) );" - ); - sc.add( "parent.addContent( contentIndex, finalText );" ); + "finalText.setText( finalText.getText().substring( 0, finalText.getText().length() - \" \".length() ) );"); + sc.add("parent.addContent( contentIndex, finalText );"); sc.unindent(); - sc.add( "}" ); - sc.add( "parent.addContent( contentIndex, child );" ); - sc.add( "parent.addContent( contentIndex, lastText );" ); - - JMethod findRSLists = new JMethod( "findAndReplaceSimpleLists", new JClass( "Element" ), null ); - findRSLists.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - findRSLists.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - findRSLists.addParameter( new JParameter( new JClass( "java.util.Collection" ), "list" ) ); - findRSLists.addParameter( new JParameter( new JClass( "String" ), "parentName" ) ); - findRSLists.addParameter( new JParameter( new JClass( "String" ), "childName" ) ); + sc.add("}"); + sc.add("parent.addContent( contentIndex, child );"); + sc.add("parent.addContent( contentIndex, lastText );"); + + JMethod findRSLists = new JMethod("findAndReplaceSimpleLists", new JClass("Element"), null); + findRSLists.addParameter(new JParameter(new JClass("Counter"), "counter")); + findRSLists.addParameter(new JParameter(new JClass("Element"), "parent")); + findRSLists.addParameter(new JParameter(new JClass("java.util.Collection"), "list")); + findRSLists.addParameter(new JParameter(new JClass("String"), "parentName")); + findRSLists.addParameter(new JParameter(new JClass("String"), "childName")); findRSLists.getModifiers().makeProtected(); sc = findRSLists.getSourceCode(); - sc.add( "boolean shouldExist = ( list != null ) && ( list.size() > 0 );" ); - sc.add( "Element element = updateElement( counter, parent, parentName );" ); - sc.add( "if ( shouldExist )" ); - sc.add( "{" ); + sc.add("boolean shouldExist = ( list != null ) && ( list.size() > 0 );"); + sc.add("Element element = updateElement( counter, parent, parentName );"); + sc.add("if ( shouldExist )"); + sc.add("{"); sc.indent(); - sc.add( "Iterator it = list.iterator();" ); - sc.add( "Counter innerCount = new Counter( counter.getDepth() + 1 );" ); - sc.add( "while ( it.hasNext() )" ); - sc.add( "{" ); + sc.add("Iterator it = list.iterator();"); + sc.add("Counter innerCount = new Counter( counter.getDepth() + 1 );"); + sc.add("while ( it.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "String value = (String) it.next();" ); - sc.add( "Element el = factory.element( childName, element.getNamespace() );" ); - sc.add( "insertAtPreferredLocation( element, el, innerCount );" ); - sc.add( "el.setText( value );" ); - sc.add( "innerCount.increaseCount();" ); + sc.add("String value = (String) it.next();"); + sc.add("Element el = factory.element( childName, element.getNamespace() );"); + sc.add("insertAtPreferredLocation( element, el, innerCount );"); + sc.add("el.setText( value );"); + sc.add("innerCount.increaseCount();"); sc.unindent(); - sc.add( "}" ); - sc.add( "}" ); - sc.add( "return element;" ); + sc.add("}"); + sc.add("}"); + sc.add("return element;"); - return new JMethod[] { findRSElement, updateElement, insAtPref, findRSLists }; + return new JMethod[] {findRSElement, updateElement, insAtPref, findRSLists}; } - private JMethod[] generateDomMethods() - { - JMethod findRSDom = new JMethod( "findAndReplaceXpp3DOM", new JClass( "Element" ), null ); - findRSDom.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - findRSDom.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - findRSDom.addParameter( new JParameter( new JClass( "String" ), "name" ) ); - findRSDom.addParameter( new JParameter( new JClass( "Xpp3Dom" ), "dom" ) ); + private JMethod[] generateDomMethods() { + JMethod findRSDom = new JMethod("findAndReplaceXpp3DOM", new JClass("Element"), null); + findRSDom.addParameter(new JParameter(new JClass("Counter"), "counter")); + findRSDom.addParameter(new JParameter(new JClass("Element"), "parent")); + findRSDom.addParameter(new JParameter(new JClass("String"), "name")); + findRSDom.addParameter(new JParameter(new JClass("Xpp3Dom"), "dom")); findRSDom.getModifiers().makeProtected(); JSourceCode sc = findRSDom.getSourceCode(); - sc.add( "boolean shouldExist = ( dom != null ) && ( dom.getChildCount() > 0 || dom.getValue() != null );" ); - sc.add( "Element element = updateElement( counter, parent, name );" ); - sc.add( "if ( shouldExist )" ); - sc.add( "{" ); - sc.addIndented( "replaceXpp3DOM( element, dom, new Counter( counter.getDepth() + 1 ) );" ); - sc.add( "}" ); - sc.add( "return element;" ); - - JMethod findRSDom2 = new JMethod( "replaceXpp3DOM" ); - findRSDom2.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - findRSDom2.addParameter( new JParameter( new JClass( "Xpp3Dom" ), "parentDom" ) ); - findRSDom2.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); + sc.add("boolean shouldExist = ( dom != null ) && ( dom.getChildCount() > 0 || dom.getValue() != null );"); + sc.add("Element element = updateElement( counter, parent, name );"); + sc.add("if ( shouldExist )"); + sc.add("{"); + sc.addIndented("replaceXpp3DOM( element, dom, new Counter( counter.getDepth() + 1 ) );"); + sc.add("}"); + sc.add("return element;"); + + JMethod findRSDom2 = new JMethod("replaceXpp3DOM"); + findRSDom2.addParameter(new JParameter(new JClass("Element"), "parent")); + findRSDom2.addParameter(new JParameter(new JClass("Xpp3Dom"), "parentDom")); + findRSDom2.addParameter(new JParameter(new JClass("Counter"), "counter")); findRSDom2.getModifiers().makeProtected(); sc = findRSDom2.getSourceCode(); - - if ( hasJavaSourceSupport( 5 ) ) - { - sc.add( "for( String attributeName : parentDom.getAttributeNames() )" ); - sc.add( "{" ); + + if (hasJavaSourceSupport(5)) { + sc.add("for( String attributeName : parentDom.getAttributeNames() )"); + sc.add("{"); sc.indent(); - } - else - { - sc.add( "for ( Iterator i = Arrays.asList( parentDom.getAttributeNames() ).iterator(); i.hasNext(); )" ); - sc.add( "{" ); + } else { + sc.add("for ( Iterator i = Arrays.asList( parentDom.getAttributeNames() ).iterator(); i.hasNext(); )"); + sc.add("{"); sc.indent(); - sc.add( "String attributeName = (String) i.next();" ); + sc.add("String attributeName = (String) i.next();"); } - sc.add( "String[] attrDetails = attributeName.split( \":\", 2 );" ); - sc.add( "if ( attrDetails.length == 2 )" ); - sc.add( "{" ); - sc.addIndented( "parent.setAttribute( attrDetails[1], parentDom.getAttribute( attributeName ), parent.getNamespace( attrDetails[0] ) );" ); - sc.add( "}" ); - sc.add( "else "); - sc.add( "{" ); - sc.addIndented( "parent.setAttribute( attributeName, parentDom.getAttribute( attributeName ) );" ); - sc.add( "}" ); + sc.add("String[] attrDetails = attributeName.split( \":\", 2 );"); + sc.add("if ( attrDetails.length == 2 )"); + sc.add("{"); + sc.addIndented( + "parent.setAttribute( attrDetails[1], parentDom.getAttribute( attributeName ), parent.getNamespace( attrDetails[0] ) );"); + sc.add("}"); + sc.add("else "); + sc.add("{"); + sc.addIndented("parent.setAttribute( attributeName, parentDom.getAttribute( attributeName ) );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "if ( parentDom.getChildCount() > 0 )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("if ( parentDom.getChildCount() > 0 )"); + sc.add("{"); sc.indent(); - sc.add( "Xpp3Dom[] childs = parentDom.getChildren();" ); - sc.add( "Collection domChilds = new ArrayList();" ); - sc.add( "for ( int i = 0; i < childs.length; i++ )" ); - sc.add( "{" ); - sc.addIndented( "domChilds.add( childs[i] );" ); - sc.add( "}" ); - sc.add( "ListIterator it = parent.getChildren().listIterator();" ); - sc.add( "while ( it.hasNext() )" ); - sc.add( "{" ); + sc.add("Xpp3Dom[] childs = parentDom.getChildren();"); + sc.add("Collection domChilds = new ArrayList();"); + sc.add("for ( int i = 0; i < childs.length; i++ )"); + sc.add("{"); + sc.addIndented("domChilds.add( childs[i] );"); + sc.add("}"); + sc.add("ListIterator it = parent.getChildren().listIterator();"); + sc.add("while ( it.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "Element elem = (Element) it.next();" ); - sc.add( "Iterator it2 = domChilds.iterator();" ); - sc.add( "Xpp3Dom corrDom = null;" ); - sc.add( "while ( it2.hasNext() )" ); - sc.add( "{" ); + sc.add("Element elem = (Element) it.next();"); + sc.add("Iterator it2 = domChilds.iterator();"); + sc.add("Xpp3Dom corrDom = null;"); + sc.add("while ( it2.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "Xpp3Dom dm = (Xpp3Dom) it2.next();" ); - sc.add( "if ( dm.getName().equals( elem.getName() ) )" ); - sc.add( "{" ); + sc.add("Xpp3Dom dm = (Xpp3Dom) it2.next();"); + sc.add("if ( dm.getName().equals( elem.getName() ) )"); + sc.add("{"); sc.indent(); - sc.add( "corrDom = dm;" ); - sc.add( "break;" ); + sc.add("corrDom = dm;"); + sc.add("break;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "if ( corrDom != null )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("if ( corrDom != null )"); + sc.add("{"); sc.indent(); - sc.add( "domChilds.remove( corrDom );" ); - sc.add( "replaceXpp3DOM( elem, corrDom, new Counter( counter.getDepth() + 1 ) );" ); - sc.add( "counter.increaseCount();" ); + sc.add("domChilds.remove( corrDom );"); + sc.add("replaceXpp3DOM( elem, corrDom, new Counter( counter.getDepth() + 1 ) );"); + sc.add("counter.increaseCount();"); sc.unindent(); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "it.remove();" ); - sc.add( "}" ); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("it.remove();"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "Iterator it2 = domChilds.iterator();" ); - sc.add( "while ( it2.hasNext() )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("Iterator it2 = domChilds.iterator();"); + sc.add("while ( it2.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "Xpp3Dom dm = (Xpp3Dom) it2.next();" ); - sc.add( "Element elem = factory.element( dm.getName(), parent.getNamespace() );" ); - sc.add( "insertAtPreferredLocation( parent, elem, counter );" ); - sc.add( "counter.increaseCount();" ); - sc.add( "replaceXpp3DOM( elem, dm, new Counter( counter.getDepth() + 1 ) );" ); + sc.add("Xpp3Dom dm = (Xpp3Dom) it2.next();"); + sc.add("Element elem = factory.element( dm.getName(), parent.getNamespace() );"); + sc.add("insertAtPreferredLocation( parent, elem, counter );"); + sc.add("counter.increaseCount();"); + sc.add("replaceXpp3DOM( elem, dm, new Counter( counter.getDepth() + 1 ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( " else if ( parentDom.getValue() != null )" ); - sc.add( "{" ); - sc.addIndented( "parent.setText( parentDom.getValue() );" ); - sc.add( "}" ); + sc.add("}"); + sc.add(" else if ( parentDom.getValue() != null )"); + sc.add("{"); + sc.addIndented("parent.setText( parentDom.getValue() );"); + sc.add("}"); - return new JMethod[] { findRSDom, findRSDom2 }; + return new JMethod[] {findRSDom, findRSDom2}; } - private void writeAllClasses( Model objectModel, JClass jClass, ModelClass rootClass ) - throws ModelloException - { + private void writeAllClasses(Model objectModel, JClass jClass, ModelClass rootClass) throws ModelloException { List alwaysExistingElements = new ArrayList(); - alwaysExistingElements.add( rootClass ); + alwaysExistingElements.add(rootClass); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - updateClass( clazz, jClass, alwaysExistingElements ); + for (ModelClass clazz : getClasses(objectModel)) { + updateClass(clazz, jClass, alwaysExistingElements); } } - private void updateClass( ModelClass clazz, JClass jClass, List alwaysExisting ) - throws ModelloException - { + private void updateClass(ModelClass clazz, JClass jClass, List alwaysExisting) throws ModelloException { String className = clazz.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); - - ModelClassMetadata classMetadata = (ModelClassMetadata) clazz.getMetadata( ModelClassMetadata.ID ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "update" + capClassName ); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "String" ), "xmlTag" ) ); - marshall.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - if ( classMetadata.isRootElement() ) - { - marshall.addParameter( new JParameter( new JClass( "Document" ), "document" ) ); - } - else - { - marshall.addParameter( new JParameter( new JClass( "Element" ), "element" ) ); + ModelClassMetadata classMetadata = (ModelClassMetadata) clazz.getMetadata(ModelClassMetadata.ID); + + JMethod marshall = new JMethod("update" + capClassName); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("String"), "xmlTag")); + marshall.addParameter(new JParameter(new JClass("Counter"), "counter")); + if (classMetadata.isRootElement()) { + marshall.addParameter(new JParameter(new JClass("Document"), "document")); + } else { + marshall.addParameter(new JParameter(new JClass("Element"), "element")); } marshall.getModifiers().makeProtected(); JSourceCode sc = marshall.getSourceCode(); - sc.add( "if ( " + uncapClassName + " != null )" ); - sc.add( "{" ); + sc.add("if ( " + uncapClassName + " != null )"); + sc.add("{"); sc.indent(); - - if ( classMetadata.isRootElement() ) - { - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) clazz.getModel().getMetadata( XmlModelMetadata.ID ); - String namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() ); - - if ( namespace != null ) - { - sc.add( "Element root = factory.element( xmlTag, \"" + namespace + "\" );" ); - if ( xmlModelMetadata.getSchemaLocation() != null ) - { - String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); - sc.add("Namespace xsins = Namespace.getNamespace( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); - sc.add( "root.setAttribute( \"schemaLocation\", \"" + namespace + " " + url + "\", xsins );" ); + + if (classMetadata.isRootElement()) { + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) clazz.getModel().getMetadata(XmlModelMetadata.ID); + String namespace = xmlModelMetadata.getNamespace(getGeneratedVersion()); + + if (namespace != null) { + sc.add("Element root = factory.element( xmlTag, \"" + namespace + "\" );"); + if (xmlModelMetadata.getSchemaLocation() != null) { + String url = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); + sc.add( + "Namespace xsins = Namespace.getNamespace( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); + sc.add("root.setAttribute( \"schemaLocation\", \"" + namespace + " " + url + "\", xsins );"); } + } else { + sc.add("Element root = factory.element( xmlTag );"); } - else - { - sc.add( "Element root = factory.element( xmlTag );" ); - } - sc.add( "document.setRootElement( root );" ); - } - else - { - sc.add( "Element root = updateElement( counter, element, xmlTag );" ); + sc.add("document.setRootElement( root );"); + } else { + sc.add("Element root = updateElement( counter, element, xmlTag );"); } - - sc.add( "Counter innerCount = new Counter( counter.getDepth() + 1 );" ); + + sc.add("Counter innerCount = new Counter( counter.getDepth() + 1 );"); ModelField contentField = null; String contentValue = null; - - List modelFields = getFieldsForXml( clazz, getGeneratedVersion() ); - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + List modelFields = getFieldsForXml(clazz, getGeneratedVersion()); + + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + '.' + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; - - if ( xmlFieldMetadata.isContent() ) - { + String value = uncapClassName + '.' + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; + + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); - sc.add( "{" ); - sc.addIndented( "root.setAttribute( \"" + fieldTagName + "\", " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "}" ); + + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); + sc.add("{"); + sc.addIndented("root.setAttribute( \"" + fieldTagName + "\", " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("}"); continue; } - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; - + ModelClass toClass = association.getToClass(); - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, field ) ); - sc.add( "{" ); - sc.addIndented( "update" + capitalise( field.getType() ) + "( " + value + ", \"" + fieldTagName - + "\", innerCount, root );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, field)); + sc.add("{"); + sc.addIndented("update" + capitalise(field.getType()) + "( " + value + ", \"" + fieldTagName + + "\", innerCount, root );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); - - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); -// -// type = association.getType(); -// String toType = association.getTo(); -// - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { -// type = association.getType(); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); + + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); + // + // type = association.getType(); + // String toType = association.getTo(); + // + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + // type = association.getType(); String toType = association.getTo(); - if ( toClass != null ) - { - if ( xmlAssociationMetadata.isWrappedItems() ) - { - sc.add( "iterate" + capitalise( toType ) + "( innerCount, root, " + value + ",\"" - + fieldTagName + "\",\"" + valuesTagName + "\" );" ); - createIterateMethod( field.getName(), toClass, singular( fieldTagName ), jClass ); - } - else - { - //assume flat.. - sc.add( "iterate2" + capitalise( toType ) + "( innerCount, root, " + value + ", \"" - + valuesTagName + "\" );" ); - createIterateMethod2( field.getName(), toClass, singular( fieldTagName ), jClass ); + if (toClass != null) { + if (xmlAssociationMetadata.isWrappedItems()) { + sc.add("iterate" + capitalise(toType) + "( innerCount, root, " + value + ",\"" + + fieldTagName + "\",\"" + valuesTagName + "\" );"); + createIterateMethod(field.getName(), toClass, singular(fieldTagName), jClass); + } else { + // assume flat.. + sc.add("iterate2" + capitalise(toType) + "( innerCount, root, " + value + ", \"" + + valuesTagName + "\" );"); + createIterateMethod2(field.getName(), toClass, singular(fieldTagName), jClass); } + } else { + // list of strings? + sc.add("findAndReplaceSimpleLists( innerCount, root, " + value + ", \"" + fieldTagName + + "\", \"" + singular(fieldTagName) + "\" );"); } - else - { - //list of strings? - sc.add( "findAndReplaceSimpleLists( innerCount, root, " + value + ", \"" + fieldTagName - + "\", \"" + singular( fieldTagName ) + "\" );" ); - } - } - else - { - //Map or Properties - sc.add( getValueChecker( type, value, field ) ); - sc.add( "{" ); + } else { + // Map or Properties + sc.add(getValueChecker(type, value, field)); + sc.add("{"); sc.indent(); - sc.add( "Element listElement = updateElement( innerCount, root, \"" + fieldTagName - + "\" );" ); - sc.add( "Iterator it = " + value + ".keySet().iterator();" ); - sc.add( "Counter propertiesCounter = new Counter( innerCount.getDepth() + 1 );" ); - sc.add( "while ( it.hasNext() )" ); - sc.add( "{" ); + sc.add("Element listElement = updateElement( innerCount, root, \"" + fieldTagName + "\" );"); + sc.add("Iterator it = " + value + ".keySet().iterator();"); + sc.add("Counter propertiesCounter = new Counter( innerCount.getDepth() + 1 );"); + sc.add("while ( it.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "String key = (String) it.next();" ); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "Element propTag = updateElement( propertiesCounter, listElement, \"" + singular( fieldTagName ) +"\" );" ); - sc.add( "Counter propertyCounter = new Counter( propertiesCounter.getDepth() + 1 );" ); - sc.add( "findAndReplaceSimpleElement( propertyCounter, propTag, \"key\", key, null );" ); - sc.add( "findAndReplaceSimpleElement( propertyCounter, propTag, \"value\", (String) " - + value + ".get( key ), null );" ); - } - else - { - sc.add( "findAndReplaceSimpleElement( propertiesCounter, listElement, key, (String) " + value + ".get( key ), null );" ); + sc.add("String key = (String) it.next();"); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("Element propTag = updateElement( propertiesCounter, listElement, \"" + + singular(fieldTagName) + "\" );"); + sc.add("Counter propertyCounter = new Counter( propertiesCounter.getDepth() + 1 );"); + sc.add("findAndReplaceSimpleElement( propertyCounter, propTag, \"key\", key, null );"); + sc.add("findAndReplaceSimpleElement( propertyCounter, propTag, \"value\", (String) " + value + + ".get( key ), null );"); + } else { + sc.add("findAndReplaceSimpleElement( propertiesCounter, listElement, key, (String) " + value + + ".get( key ), null );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - if ( "DOM".equals( field.getType() ) ) - { - sc.add( - "findAndReplaceXpp3DOM( innerCount, root, \"" + fieldTagName + "\", (Xpp3Dom) " + value + " );" ); + } else { + if ("DOM".equals(field.getType())) { + sc.add("findAndReplaceXpp3DOM( innerCount, root, \"" + fieldTagName + "\", (Xpp3Dom) " + value + + " );"); requiresDomSupport = true; - } - else - { - sc.add( getValueChecker( type, value, field ) ); - sc.add( "{"); - sc.addIndented( "updateElement( innerCount, root, \"" + fieldTagName + "\" ).setText( " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "}" ); + } else { + sc.add(getValueChecker(type, value, field)); + sc.add("{"); + sc.addIndented("updateElement( innerCount, root, \"" + fieldTagName + "\" ).setText( " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("}"); } } } - - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - sc.add( "root.setText( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + " );" ); + + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + sc.add("root.setText( " + getValue(contentField.getType(), contentValue, xmlFieldMetadata) + " );"); } - + sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void createIterateMethod( String field, ModelClass toClass, String childFieldTagName, JClass jClass ) - { - if ( jClass.getMethod( "iterate" + capitalise( toClass.getName() ), 0 ) != null ) - { + private void createIterateMethod(String field, ModelClass toClass, String childFieldTagName, JClass jClass) { + if (jClass.getMethod("iterate" + capitalise(toClass.getName()), 0) != null) { return; } - JMethod toReturn = new JMethod( "iterate" + capitalise( toClass.getName() ) ); - toReturn.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - toReturn.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - toReturn.addParameter( new JParameter( new JClass( "java.util.Collection" ), "list" ) ); - toReturn.addParameter( new JParameter( new JClass( "java.lang.String" ), "parentTag" ) ); - toReturn.addParameter( new JParameter( new JClass( "java.lang.String" ), "childTag" ) ); + JMethod toReturn = new JMethod("iterate" + capitalise(toClass.getName())); + toReturn.addParameter(new JParameter(new JClass("Counter"), "counter")); + toReturn.addParameter(new JParameter(new JClass("Element"), "parent")); + toReturn.addParameter(new JParameter(new JClass("java.util.Collection"), "list")); + toReturn.addParameter(new JParameter(new JClass("java.lang.String"), "parentTag")); + toReturn.addParameter(new JParameter(new JClass("java.lang.String"), "childTag")); toReturn.getModifiers().makeProtected(); JSourceCode sc = toReturn.getSourceCode(); - sc.add( "boolean shouldExist = ( list != null ) && ( list.size() > 0 );" ); - sc.add( "Element element = updateElement( counter, parent, parentTag );" ); - sc.add( "if ( shouldExist )" ); - sc.add( "{" ); + sc.add("boolean shouldExist = ( list != null ) && ( list.size() > 0 );"); + sc.add("Element element = updateElement( counter, parent, parentTag );"); + sc.add("if ( shouldExist )"); + sc.add("{"); sc.indent(); - sc.add( "Iterator it = list.iterator();" ); - sc.add( "Counter innerCount = new Counter( counter.getDepth() + 1 );" ); - sc.add( "while ( it.hasNext() )" ); - sc.add( "{" ); + sc.add("Iterator it = list.iterator();"); + sc.add("Counter innerCount = new Counter( counter.getDepth() + 1 );"); + sc.add("while ( it.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( toClass.getName() + " value = (" + toClass.getName() + ") it.next();" ); - sc.add( "update" + toClass.getName() + "( value, childTag, innerCount, element );" ); - sc.add( "innerCount.increaseCount();" ); + sc.add(toClass.getName() + " value = (" + toClass.getName() + ") it.next();"); + sc.add("update" + toClass.getName() + "( value, childTag, innerCount, element );"); + sc.add("innerCount.increaseCount();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( toReturn ); + jClass.addMethod(toReturn); } - private void createIterateMethod2( String field, ModelClass toClass, String childFieldTagName, JClass jClass ) - { - if ( jClass.getMethod( "iterate2" + capitalise( toClass.getName() ), 0 ) != null ) - { + private void createIterateMethod2(String field, ModelClass toClass, String childFieldTagName, JClass jClass) { + if (jClass.getMethod("iterate2" + capitalise(toClass.getName()), 0) != null) { return; } - JMethod toReturn = new JMethod( "iterate2" + capitalise( toClass.getName() ) ); - toReturn.addParameter( new JParameter( new JClass( "Counter" ), "counter" ) ); - toReturn.addParameter( new JParameter( new JClass( "Element" ), "parent" ) ); - toReturn.addParameter( new JParameter( new JClass( "java.util.Collection" ), "list" ) ); - toReturn.addParameter( new JParameter( new JClass( "java.lang.String" ), "childTag" ) ); + JMethod toReturn = new JMethod("iterate2" + capitalise(toClass.getName())); + toReturn.addParameter(new JParameter(new JClass("Counter"), "counter")); + toReturn.addParameter(new JParameter(new JClass("Element"), "parent")); + toReturn.addParameter(new JParameter(new JClass("java.util.Collection"), "list")); + toReturn.addParameter(new JParameter(new JClass("java.lang.String"), "childTag")); toReturn.getModifiers().makeProtected(); JSourceCode sc = toReturn.getSourceCode(); - sc.add( "Iterator it = list.iterator();" ); - sc.add( "while ( it.hasNext() )" ); - sc.add( "{" ); + sc.add("Iterator it = list.iterator();"); + sc.add("while ( it.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( toClass.getName() + " value = (" + toClass.getName() + ") it.next();" ); - sc.add( "update" + toClass.getName() + "( value, childTag, counter, parent );" ); + sc.add(toClass.getName() + " value = (" + toClass.getName() + ") it.next();"); + sc.add("update" + toClass.getName() + "( value, childTag, counter, parent );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( toReturn ); + jClass.addMethod(toReturn); } - - } diff --git a/modello-plugins/modello-plugin-jdom/src/test/java/org/codehaus/modello/plugin/jdom/FeaturesJDOMGeneratorTest.java b/modello-plugins/modello-plugin-jdom/src/test/java/org/codehaus/modello/plugin/jdom/FeaturesJDOMGeneratorTest.java index 741fba1bf..d092b20aa 100644 --- a/modello-plugins/modello-plugin-jdom/src/test/java/org/codehaus/modello/plugin/jdom/FeaturesJDOMGeneratorTest.java +++ b/modello-plugins/modello-plugin-jdom/src/test/java/org/codehaus/modello/plugin/jdom/FeaturesJDOMGeneratorTest.java @@ -22,40 +22,35 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesJDOMGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesJDOMGeneratorTest() - { - super( "features" ); +public class FeaturesJDOMGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesJDOMGeneratorTest() { + super("features"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-reader", parameters ); - modello.generate( model, "jdom-writer", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-reader", parameters); + modello.generate(model, "jdom-writer", parameters); - addDependency( "org.jdom", "jdom" ); - addDependency( "org.xmlunit", "xmlunit-core" ); + addDependency("org.jdom", "jdom"); + addDependency("org.xmlunit", "xmlunit-core"); compileGeneratedSources(); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.jdom.JDOMFeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.jdom.JDOMFeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-jsonschema/pom.xml b/modello-plugins/modello-plugin-jsonschema/pom.xml index 7126cfc84..9ee1191bf 100644 --- a/modello-plugins/modello-plugin-jsonschema/pom.xml +++ b/modello-plugins/modello-plugin-jsonschema/pom.xml @@ -1,12 +1,12 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-jsonschema Modello JSON-Schema Plugin Modello JSON-Schema Plugin generates a JSON-Schema from the model to be able to validate JSON content. diff --git a/modello-plugins/modello-plugin-jsonschema/src/main/java/org/codehaus/modello/plugin/jsonschema/JsonSchemaGenerator.java b/modello-plugins/modello-plugin-jsonschema/src/main/java/org/codehaus/modello/plugin/jsonschema/JsonSchemaGenerator.java index c59dad967..c9e07efd7 100644 --- a/modello-plugins/modello-plugin-jsonschema/src/main/java/org/codehaus/modello/plugin/jsonschema/JsonSchemaGenerator.java +++ b/modello-plugins/modello-plugin-jsonschema/src/main/java/org/codehaus/modello/plugin/jsonschema/JsonSchemaGenerator.java @@ -29,6 +29,10 @@ import java.util.List; import java.util.Properties; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonGenerator.Feature; +import com.fasterxml.jackson.core.json.JsonWriteFeature; import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.model.Model; @@ -42,96 +46,72 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; -import com.fasterxml.jackson.core.JsonEncoding; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonGenerator.Feature; -import com.fasterxml.jackson.core.json.JsonWriteFeature; - /** * @author Simone Tripodi * @since 1.8 */ -@Component( role = ModelloGenerator.class, hint = "jsonschema" ) -public final class JsonSchemaGenerator - extends AbstractXmlJavaGenerator -{ - - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); - - try - { - generateJsonSchema( parameters ); - } - catch ( IOException ioe ) - { - throw new ModelloException( "Exception while generating JSON Schema.", ioe ); +@Component(role = ModelloGenerator.class, hint = "jsonschema") +public final class JsonSchemaGenerator extends AbstractXmlJavaGenerator { + + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + try { + generateJsonSchema(parameters); + } catch (IOException ioe) { + throw new ModelloException("Exception while generating JSON Schema.", ioe); } } - private void generateJsonSchema( Properties parameters ) - throws IOException, ModelloException - { + private void generateJsonSchema(Properties parameters) throws IOException, ModelloException { Model objectModel = getModel(); File directory = getOutputDirectory(); - if ( isPackageWithVersion() ) - { - directory = new File( directory, getGeneratedVersion().toString() ); + if (isPackageWithVersion()) { + directory = new File(directory, getGeneratedVersion().toString()); } - if ( !directory.exists() ) - { + if (!directory.exists()) { directory.mkdirs(); } // we assume parameters not null - String schemaFileName = parameters.getProperty( ModelloParameterConstants.OUTPUT_JSONSCHEMA_FILE_NAME ); + String schemaFileName = parameters.getProperty(ModelloParameterConstants.OUTPUT_JSONSCHEMA_FILE_NAME); File schemaFile; - if ( schemaFileName != null ) - { - schemaFile = new File( directory, schemaFileName ); - } - else - { - schemaFile = new File( directory, objectModel.getId() + "-" + getGeneratedVersion() + ".schema.json" ); + if (schemaFileName != null) { + schemaFile = new File(directory, schemaFileName); + } else { + schemaFile = new File(directory, objectModel.getId() + "-" + getGeneratedVersion() + ".schema.json"); } JsonGenerator generator = new JsonFactory() - .enable( Feature.AUTO_CLOSE_JSON_CONTENT ) - .enable( Feature.AUTO_CLOSE_TARGET ) - .enable( Feature.FLUSH_PASSED_TO_STREAM ) - .enable( JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature() ) - .enable( JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature() ) - .enable( JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature() ) - .disable( JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS.mappedFeature() ) - .createGenerator( newWriter( schemaFile.toPath(), StandardCharsets.UTF_8 ) ); + .enable(Feature.AUTO_CLOSE_JSON_CONTENT) + .enable(Feature.AUTO_CLOSE_TARGET) + .enable(Feature.FLUSH_PASSED_TO_STREAM) + .enable(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature()) + .enable(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature()) + .enable(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature()) + .disable(JsonWriteFeature.WRITE_NUMBERS_AS_STRINGS.mappedFeature()) + .createGenerator(newWriter(schemaFile.toPath(), StandardCharsets.UTF_8)); generator.useDefaultPrettyPrinter(); - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), - getGeneratedVersion() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - try - { + try { generator.writeStartObject(); - generator.writeStringField( "$schema", "http://json-schema.org/draft-04/schema#" ); + generator.writeStringField("$schema", "http://json-schema.org/draft-04/schema#"); - writeClassDocumentation( generator, root, true ); + writeClassDocumentation(generator, root, true); - generator.writeObjectFieldStart( "definitions" ); + generator.writeObjectFieldStart("definitions"); - for ( ModelClass current : objectModel.getClasses( getGeneratedVersion() ) ) - { - if ( !root.equals( current ) ) - { - writeClassDocumentation( generator, current, false ); + for (ModelClass current : objectModel.getClasses(getGeneratedVersion())) { + if (!root.equals(current)) { + writeClassDocumentation(generator, current, false); } } @@ -140,104 +120,87 @@ private void generateJsonSchema( Properties parameters ) // end main object generator.writeEndObject(); - } - finally - { + } finally { generator.close(); } } - private void writeClassDocumentation( JsonGenerator generator, ModelClass modelClass, boolean isRoot ) - throws IOException - { - if ( !isRoot ) - { - generator.writeObjectFieldStart( modelClass.getName() ); + private void writeClassDocumentation(JsonGenerator generator, ModelClass modelClass, boolean isRoot) + throws IOException { + if (!isRoot) { + generator.writeObjectFieldStart(modelClass.getName()); } - generator.writeStringField( "id", modelClass.getName() + '#' ); - writeDescriptionField( generator, modelClass.getDescription() ); - writeTypeField( generator, "object" ); + generator.writeStringField("id", modelClass.getName() + '#'); + writeDescriptionField(generator, modelClass.getDescription()); + writeTypeField(generator, "object"); - generator.writeObjectFieldStart( "properties" ); + generator.writeObjectFieldStart("properties"); List required = new LinkedList(); ModelClass reference = modelClass; // traverse the whole modelClass hierarchy to create the nested Builder instance - while ( reference != null ) - { + while (reference != null) { // collect parameters and set them in the instance object - for ( ModelField modelField : reference.getFields( getGeneratedVersion() ) ) - { - if ( modelField.isRequired() ) - { - required.add( modelField.getName() ); + for (ModelField modelField : reference.getFields(getGeneratedVersion())) { + if (modelField.isRequired()) { + required.add(modelField.getName()); } // each field is represented as object - generator.writeObjectFieldStart( modelField.getName() ); + generator.writeObjectFieldStart(modelField.getName()); - writeDescriptionField( generator, modelField.getDescription() ); + writeDescriptionField(generator, modelField.getDescription()); - if ( modelField instanceof ModelAssociation ) - { + if (modelField instanceof ModelAssociation) { ModelAssociation modelAssociation = (ModelAssociation) modelField; - if ( modelAssociation.isOneMultiplicity() ) - { - writeTypeField( generator, modelAssociation.getType() ); - } - else - { + if (modelAssociation.isOneMultiplicity()) { + writeTypeField(generator, modelAssociation.getType()); + } else { // MANY_MULTIPLICITY - writeTypeField( generator, "array" ); + writeTypeField(generator, "array"); - generator.writeObjectFieldStart( "items" ); + generator.writeObjectFieldStart("items"); String type = modelAssociation.getType(); String toType = modelAssociation.getTo(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - writeTypeField( generator, toType ); - } - else - { + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + writeTypeField(generator, toType); + } else { // Map or Properties - writeTypeField( generator, "object" ); + writeTypeField(generator, "object"); - generator.writeObjectFieldStart( "properties" ); + generator.writeObjectFieldStart("properties"); - XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) modelAssociation.getAssociationMetadata( XmlAssociationMetadata.ID ); + XmlAssociationMetadata xmlAssociationMetadata = (XmlAssociationMetadata) + modelAssociation.getAssociationMetadata(XmlAssociationMetadata.ID); - if ( xmlAssociationMetadata.isMapExplode() ) - { + if (xmlAssociationMetadata.isMapExplode()) { // key - generator.writeObjectFieldStart( "key" ); - writeTypeField( generator, "string" ); + generator.writeObjectFieldStart("key"); + writeTypeField(generator, "string"); generator.writeEndObject(); // value - generator.writeObjectFieldStart( "value" ); - writeTypeField( generator, toType ); + generator.writeObjectFieldStart("value"); + writeTypeField(generator, toType); generator.writeEndObject(); // properties generator.writeEndObject(); // required field - generator.writeArrayFieldStart( "required" ); - generator.writeString( "key" ); - generator.writeString( "value" ); + generator.writeArrayFieldStart("required"); + generator.writeString("key"); + generator.writeString("value"); generator.writeEndArray(); - } - else - { - generator.writeObjectFieldStart( "*" ); - writeTypeField( generator, toType ); + } else { + generator.writeObjectFieldStart("*"); + writeTypeField(generator, toType); generator.writeEndObject(); } } @@ -245,21 +208,16 @@ private void writeClassDocumentation( JsonGenerator generator, ModelClass modelC // items generator.writeEndObject(); } - } - else - { - writeTypeField( generator, modelField.getType() ); + } else { + writeTypeField(generator, modelField.getType()); } generator.writeEndObject(); } - if ( reference.hasSuperClass() ) - { - reference = reference.getModel().getClass( reference.getSuperClass(), getGeneratedVersion() ); - } - else - { + if (reference.hasSuperClass()) { + reference = reference.getModel().getClass(reference.getSuperClass(), getGeneratedVersion()); + } else { reference = null; } } @@ -268,68 +226,55 @@ private void writeClassDocumentation( JsonGenerator generator, ModelClass modelC generator.writeEndObject(); // write `required` sequence - if ( !required.isEmpty() ) - { - generator.writeArrayFieldStart( "required" ); + if (!required.isEmpty()) { + generator.writeArrayFieldStart("required"); - for ( String requiredField : required ) - { - generator.writeString( requiredField ); + for (String requiredField : required) { + generator.writeString(requiredField); } generator.writeEndArray(); } // end definition - if ( !isRoot ) - { + if (!isRoot) { generator.writeEndObject(); } } - private static void writeDescriptionField( JsonGenerator generator, String description ) - throws IOException - { - if ( !StringUtils.isEmpty( description ) ) - { - generator.writeStringField( "description", description ); + private static void writeDescriptionField(JsonGenerator generator, String description) throws IOException { + if (!StringUtils.isEmpty(description)) { + generator.writeStringField("description", description); } } - private void writeTypeField( JsonGenerator generator, String type ) - throws IOException - { - if ( isClassInModel( type, getModel() ) ) - { - generator.writeStringField( "$ref", "#/definitions/" + type ); + private void writeTypeField(JsonGenerator generator, String type) throws IOException { + if (isClassInModel(type, getModel())) { + generator.writeStringField("$ref", "#/definitions/" + type); return; } // try to make the input type compliant, as much as possible, to JSON Schema primitive types // see http://json-schema.org/latest/json-schema-core.html#anchor8 - if ( "boolean".equals( type ) || "Boolean".equals( type ) ) - { + if ("boolean".equals(type) || "Boolean".equals(type)) { type = "boolean"; - } - else if ( "int".equals( type ) || "Integer".equals( type ) ) - { + } else if ("int".equals(type) || "Integer".equals(type)) { type = "integer"; - } - else if ( "short".equals( type ) || "Short".equals( type ) - || "long".equals( type ) || "Long".equals( type ) - || "double".equals( type ) || "Double".equals( type ) - || "float".equals( type ) || "Float".equals( type ) ) - { + } else if ("short".equals(type) + || "Short".equals(type) + || "long".equals(type) + || "Long".equals(type) + || "double".equals(type) + || "Double".equals(type) + || "float".equals(type) + || "Float".equals(type)) { type = "number"; - } - else if ( "String".equals( type ) ) - { + } else if ("String".equals(type)) { type = "string"; } // keep as it is otherwise - generator.writeStringField( "type", type ); + generator.writeStringField("type", type); } - } diff --git a/modello-plugins/modello-plugin-sax/pom.xml b/modello-plugins/modello-plugin-sax/pom.xml index 5ef9ebcae..eaf74135b 100644 --- a/modello-plugins/modello-plugin-sax/pom.xml +++ b/modello-plugins/modello-plugin-sax/pom.xml @@ -1,24 +1,16 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-sax Modello SAX Plugin Modello SAX Plugin generates XML readers and writers based on SAX API. - - - - maven-dependency-plugin - - - - org.codehaus.modello @@ -40,4 +32,12 @@ test + + + + + maven-dependency-plugin + + + diff --git a/modello-plugins/modello-plugin-sax/src/main/java/org/codehaus/modello/plugin/sax/SaxWriterGenerator.java b/modello-plugins/modello-plugin-sax/src/main/java/org/codehaus/modello/plugin/sax/SaxWriterGenerator.java index 2df94b7e6..0290d1404 100644 --- a/modello-plugins/modello-plugin-sax/src/main/java/org/codehaus/modello/plugin/sax/SaxWriterGenerator.java +++ b/modello-plugins/modello-plugin-sax/src/main/java/org/codehaus/modello/plugin/sax/SaxWriterGenerator.java @@ -53,630 +53,591 @@ * @since 1.8 * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "sax-writer" ) -public class SaxWriterGenerator - extends AbstractXmlJavaGenerator -{ +@Component(role = ModelloGenerator.class, hint = "sax-writer") +public class SaxWriterGenerator extends AbstractXmlJavaGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateSaxWriter(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating SAX Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating SAX Writer.", ex); } } - private void generateSaxWriter() - throws ModelloException, IOException - { + private void generateSaxWriter() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.sax"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.sax"; - String marshallerName = getFileName( "SaxWriter" ); + String marshallerName = getFileName("SaxWriter"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.OutputStreamWriter" ); - jClass.addImport( "java.io.UnsupportedEncodingException" ); - jClass.addImport( "java.io.Writer" ); - jClass.addImport( "java.util.Iterator" ); - jClass.addImport( "java.util.Properties" ); - jClass.addImport( "javax.xml.transform.OutputKeys" ); - jClass.addImport( "javax.xml.transform.TransformerException" ); - jClass.addImport( "javax.xml.transform.TransformerFactory" ); - jClass.addImport( "javax.xml.transform.sax.SAXTransformerFactory" ); - jClass.addImport( "javax.xml.transform.sax.TransformerHandler" ); - jClass.addImport( "javax.xml.transform.stream.StreamResult" ); - jClass.addImport( "org.xml.sax.ContentHandler" ); - jClass.addImport( "org.xml.sax.SAXException" ); - jClass.addImport( "org.xml.sax.helpers.AttributesImpl" ); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.OutputStreamWriter"); + jClass.addImport("java.io.UnsupportedEncodingException"); + jClass.addImport("java.io.Writer"); + jClass.addImport("java.util.Iterator"); + jClass.addImport("java.util.Properties"); + jClass.addImport("javax.xml.transform.OutputKeys"); + jClass.addImport("javax.xml.transform.TransformerException"); + jClass.addImport("javax.xml.transform.TransformerFactory"); + jClass.addImport("javax.xml.transform.sax.SAXTransformerFactory"); + jClass.addImport("javax.xml.transform.sax.TransformerHandler"); + jClass.addImport("javax.xml.transform.stream.StreamResult"); + jClass.addImport("org.xml.sax.ContentHandler"); + jClass.addImport("org.xml.sax.SAXException"); + jClass.addImport("org.xml.sax.helpers.AttributesImpl"); - JField namespaceField = new JField( new JClass( "String" ), "NAMESPACE" ); - namespaceField.getModifiers().setFinal( true ); - namespaceField.getModifiers().setStatic( true ); - namespaceField.setInitString( "\"\"" ); - jClass.addField( namespaceField ); + JField namespaceField = new JField(new JClass("String"), "NAMESPACE"); + namespaceField.getModifiers().setFinal(true); + namespaceField.getModifiers().setStatic(true); + namespaceField.setInitString("\"\""); + jClass.addField(namespaceField); - JField factoryField = new JField( new JClass( "SAXTransformerFactory" ), "transformerFactory" ); - factoryField.getModifiers().setFinal( true ); - factoryField.setInitString( "(SAXTransformerFactory) TransformerFactory.newInstance()" ); - jClass.addField( factoryField ); + JField factoryField = new JField(new JClass("SAXTransformerFactory"), "transformerFactory"); + factoryField.getModifiers().setFinal(true); + factoryField.setInitString("(SAXTransformerFactory) TransformerFactory.newInstance()"); + jClass.addField(factoryField); - addModelImports( jClass, null ); + addModelImports(jClass, null); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - String rootElement = resolveTagName( rootClass ); + String rootElement = resolveTagName(rootClass); - JConstructor saxWriterConstructor = new JConstructor( jClass ); + JConstructor saxWriterConstructor = new JConstructor(jClass); JSourceCode sc = saxWriterConstructor.getSourceCode(); - if ( hasJavaSourceSupport( 5 ) ) - { - sc.add( "transformerFactory.setAttribute( \"indent-number\", 2 );" ); - } - else - { - sc.add( "transformerFactory.setAttribute( \"indent-number\", new Integer( 2 ) );" ); + if (hasJavaSourceSupport(5)) { + sc.add("transformerFactory.setAttribute( \"indent-number\", 2 );"); + } else { + sc.add("transformerFactory.setAttribute( \"indent-number\", new Integer( 2 ) );"); } - jClass.addConstructor( saxWriterConstructor ); + jClass.addConstructor(saxWriterConstructor); // ---------------------------------------------------------------------- // Write the write( Writer, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - String rootElementParameterName = uncapitalise( root ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + String rootElementParameterName = uncapitalise(root); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "SAXException" ) ); - marshall.addException( new JClass( "TransformerException" ) ); + marshall.addException(new JClass("SAXException")); + marshall.addException(new JClass("TransformerException")); sc = marshall.getSourceCode(); - sc.add( "TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();" ); + sc.add("TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();"); - sc.add( "Properties format = new Properties();" ); - sc.add( "format.put( OutputKeys.ENCODING, " + rootElementParameterName + ".getModelEncoding() );" ); - sc.add( "format.put( OutputKeys.INDENT, \"yes\" );" ); - sc.add( "format.put( OutputKeys.MEDIA_TYPE, \"text/xml\" );" ); - sc.add( "format.put( OutputKeys.METHOD, \"xml\" );" ); + sc.add("Properties format = new Properties();"); + sc.add("format.put( OutputKeys.ENCODING, " + rootElementParameterName + ".getModelEncoding() );"); + sc.add("format.put( OutputKeys.INDENT, \"yes\" );"); + sc.add("format.put( OutputKeys.MEDIA_TYPE, \"text/xml\" );"); + sc.add("format.put( OutputKeys.METHOD, \"xml\" );"); - sc.add( "transformerHandler.getTransformer().setOutputProperties( format );" ); - sc.add( "transformerHandler.setResult( new StreamResult( writer ) );" ); + sc.add("transformerHandler.getTransformer().setOutputProperties( format );"); + sc.add("transformerHandler.setResult( new StreamResult( writer ) );"); - sc.add( "write( transformerHandler, " + rootElementParameterName + " );" ); + sc.add("write( transformerHandler, " + rootElementParameterName + " );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "SAXException" ) ); - marshall.addException( new JClass( "TransformerException" ) ); - marshall.addException( new JClass( "UnsupportedEncodingException" ) ); + marshall.addException(new JClass("SAXException")); + marshall.addException(new JClass("TransformerException")); + marshall.addException(new JClass("UnsupportedEncodingException")); sc = marshall.getSourceCode(); - sc.add( "write( new OutputStreamWriter( stream, " + rootElementParameterName + ".getModelEncoding() ), " + rootElementParameterName + " );" ); + sc.add("write( new OutputStreamWriter( stream, " + rootElementParameterName + ".getModelEncoding() ), " + + rootElementParameterName + " );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( ContentHandler, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "SAXException" ) ); + marshall.addException(new JClass("SAXException")); sc = marshall.getSourceCode(); - sc.add( "write( contentHandler, " + rootElementParameterName + ", true );" ); + sc.add("write( contentHandler, " + rootElementParameterName + ", true );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( ContentHandler, Model, boolean ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); - marshall.addParameter( new JParameter( JType.BOOLEAN, "startDocument" ) ); + marshall.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); + marshall.addParameter(new JParameter(JType.BOOLEAN, "startDocument")); - marshall.addException( new JClass( "SAXException" ) ); + marshall.addException(new JClass("SAXException")); sc = marshall.getSourceCode(); - sc.add( "if ( startDocument )" ); - sc.add( "{" ); - sc.addIndented( "contentHandler.startDocument();" ); - sc.add( "}" ); + sc.add("if ( startDocument )"); + sc.add("{"); + sc.addIndented("contentHandler.startDocument();"); + sc.add("}"); - sc.add( "AttributesImpl attributes = new AttributesImpl();" ); + sc.add("AttributesImpl attributes = new AttributesImpl();"); - sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", contentHandler, attributes );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", \"" + rootElement + + "\", contentHandler, attributes );"); - sc.add( "if ( startDocument )" ); - sc.add( "{" ); - sc.addIndented( "contentHandler.endDocument();" ); - sc.add( "}" ); + sc.add("if ( startDocument )"); + sc.add("{"); + sc.addIndented("contentHandler.endDocument();"); + sc.add("}"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the writeText( String, ContentHandler ) method which will help unmarshalling textual values. // ---------------------------------------------------------------------- - marshall = new JMethod( "writeText" ); + marshall = new JMethod("writeText"); marshall.getModifiers().makePrivate(); - marshall.addParameter( new JParameter( new JClass( "String" ), "text" ) ); - marshall.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); + marshall.addParameter(new JParameter(new JClass("String"), "text")); + marshall.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); - marshall.addException( new JClass( "SAXException" ) ); + marshall.addException(new JClass("SAXException")); sc = marshall.getSourceCode(); - sc.add( "contentHandler.characters( text.toCharArray(), 0, text.length() );" ); + sc.add("contentHandler.characters( text.toCharArray(), 0, text.length() );"); // generate the code - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); - if ( requiresDomSupport ) - { - createWriteDomMethod( jClass ); - createXpp3DomMethod( jClass ); + if (requiresDomSupport) { + createWriteDomMethod(jClass); + createXpp3DomMethod(jClass); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - marshall.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); - marshall.addParameter( new JParameter( new JClass( "AttributesImpl" ), "attributes" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("String"), "tagName")); + marshall.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); + marshall.addParameter(new JParameter(new JClass("AttributesImpl"), "attributes")); - marshall.addException( new JClass( "SAXException" ) ); + marshall.addException(new JClass("SAXException")); marshall.getModifiers().makePrivate(); JSourceCode sc = marshall.getSourceCode(); - ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); String namespace = null; - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID ); + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) modelClass.getModel().getMetadata(XmlModelMetadata.ID); ModelField contentField = null; String contentValue = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); boolean needsToCleanAttributes = false; // XML attributes - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); - sc.addIndented( "attributes.addAttribute( NAMESPACE, \"" - + fieldTagName - + "\", \"" - + fieldTagName - + "\", \"CDATA\", " - + getValue( field.getType(), value, xmlFieldMetadata ) - + " );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("attributes.addAttribute( NAMESPACE, \"" + + fieldTagName + + "\", \"" + + fieldTagName + + "\", \"CDATA\", " + + getValue(field.getType(), value, xmlFieldMetadata) + + " );"); + sc.add("}"); needsToCleanAttributes = true; } - } // add namespace information for root element only - if ( classMetadata.isRootElement() && ( xmlModelMetadata.getNamespace() != null ) ) - { - namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() ); - sc.add( "contentHandler.startPrefixMapping( \"\", \"" + namespace + "\" );" ); + if (classMetadata.isRootElement() && (xmlModelMetadata.getNamespace() != null)) { + namespace = xmlModelMetadata.getNamespace(getGeneratedVersion()); + sc.add("contentHandler.startPrefixMapping( \"\", \"" + namespace + "\" );"); } - if ( ( namespace != null ) && ( xmlModelMetadata.getSchemaLocation() != null ) ) - { - String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); + if ((namespace != null) && (xmlModelMetadata.getSchemaLocation() != null)) { + String url = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); - sc.add( "contentHandler.startPrefixMapping( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); + sc.add("contentHandler.startPrefixMapping( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); - sc.add( "attributes.addAttribute( \"http://www.w3.org/2001/XMLSchema-instance\", \"schemaLocation\", \"xsi:schemaLocation\", \"CDATA\", \"" + namespace + " " + url + "\" );" ); + sc.add( + "attributes.addAttribute( \"http://www.w3.org/2001/XMLSchema-instance\", \"schemaLocation\", \"xsi:schemaLocation\", \"CDATA\", \"" + + namespace + " " + url + "\" );"); } - sc.add( "contentHandler.startElement( NAMESPACE, tagName, tagName, attributes );" ); + sc.add("contentHandler.startElement( NAMESPACE, tagName, tagName, attributes );"); - if ( needsToCleanAttributes ) - { - sc.add( "attributes.clear();" ); + if (needsToCleanAttributes) { + sc.add("attributes.clear();"); } - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - sc.add( "writeText( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + ", contentHandler );" ); + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + sc.add("writeText( " + getValue(contentField.getType(), contentValue, xmlFieldMetadata) + + ", contentHandler );"); } // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // skip field with type Content continue; } - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { continue; } - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); - sc.addIndented( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" - + fieldTagName + "\", contentHandler, attributes );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented("write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" + + fieldTagName + "\", contentHandler, attributes );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); type = association.getType(); String toType = association.getTo(); boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( getValueChecker( type, value, association ) ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\", attributes );" ); + if (wrappedItems) { + sc.add("contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\", attributes );"); } - sc.add( "for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( toType + " o = (" + toType + ") iter.next();" ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add(toType + " o = (" + toType + ") iter.next();"); - sc.add( "write" + toType + "( o, \"" + valuesTagName + "\", contentHandler, attributes );" ); - } - else - { - sc.add( toType + " " + singular( uncapitalise( field.getName() ) ) + " = (" + toType - + ") iter.next();" ); - - sc.add( "contentHandler.startElement( NAMESPACE, \"" + valuesTagName + "\", \"" + valuesTagName + "\", attributes );" ); - sc.add( "writeText( " + singular( uncapitalise( field.getName() ) ) + ", contentHandler );" ); - sc.add( "contentHandler.endElement( NAMESPACE, \"" + valuesTagName + "\", \"" + valuesTagName + "\" );" ); + sc.add("write" + toType + "( o, \"" + valuesTagName + "\", contentHandler, attributes );"); + } else { + sc.add(toType + " " + singular(uncapitalise(field.getName())) + " = (" + toType + + ") iter.next();"); + + sc.add("contentHandler.startElement( NAMESPACE, \"" + valuesTagName + "\", \"" + + valuesTagName + "\", attributes );"); + sc.add("writeText( " + singular(uncapitalise(field.getName())) + ", contentHandler );"); + sc.add("contentHandler.endElement( NAMESPACE, \"" + valuesTagName + "\", \"" + valuesTagName + + "\" );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\" );"); } sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\", attributes );" ); + if (wrappedItems) { + sc.add("contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\", attributes );"); } - sc.add( "for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = (String) iter.next();" ); - - sc.add( association.getTo() + " value = (" + association.getTo() + ") " + value + ".get( key );" ); - - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "contentHandler.startElement( NAMESPACE, \"" + singular( associationName ) + "\", \"" + singular( associationName ) + "\", attributes );" ); - - sc.add( "contentHandler.startElement( NAMESPACE, \"key\", \"key\", attributes );" ); - sc.add( "writeText( key, contentHandler );" ); - sc.add( "contentHandler.endElement( NAMESPACE, \"key\", \"key\" );" ); - - if ( isClassInModel( association.getTo(), association.getModelClass().getModel() ) ) - { - sc.add( "write" + association.getTo() + "( value, \"value\", contentHandler, attributes );" ); - } - else - { - sc.add( "contentHandler.startElement( NAMESPACE, \"value\", \"value\", attributes );" ); - sc.add( "writeText( " + getValue( association.getTo(), "value", xmlFieldMetadata ) + ", contentHandler );" ); - sc.add( "contentHandler.endElement( NAMESPACE, \"value\", \"value\" );" ); + sc.add("String key = (String) iter.next();"); + + sc.add(association.getTo() + " value = (" + association.getTo() + ") " + value + + ".get( key );"); + + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("contentHandler.startElement( NAMESPACE, \"" + singular(associationName) + "\", \"" + + singular(associationName) + "\", attributes );"); + + sc.add("contentHandler.startElement( NAMESPACE, \"key\", \"key\", attributes );"); + sc.add("writeText( key, contentHandler );"); + sc.add("contentHandler.endElement( NAMESPACE, \"key\", \"key\" );"); + + if (isClassInModel( + association.getTo(), + association.getModelClass().getModel())) { + sc.add("write" + association.getTo() + + "( value, \"value\", contentHandler, attributes );"); + } else { + sc.add("contentHandler.startElement( NAMESPACE, \"value\", \"value\", attributes );"); + sc.add("writeText( " + getValue(association.getTo(), "value", xmlFieldMetadata) + + ", contentHandler );"); + sc.add("contentHandler.endElement( NAMESPACE, \"value\", \"value\" );"); } - sc.add( "contentHandler.endElement( NAMESPACE, \"" + singular( associationName ) + "\", \"" + singular( associationName ) + "\" );" ); - } - else - { - if ( isClassInModel( association.getTo(), association.getModelClass().getModel() ) ) - { - sc.add( "write" + association.getTo() + "( value, key, contentHandler, attributes );" ); - } - else - { - sc.add( "contentHandler.startElement( NAMESPACE, key, key, attributes );" ); - sc.add( "writeText( " + getValue( association.getTo(), "value", xmlFieldMetadata ) + ", contentHandler );" ); - sc.add( "contentHandler.endElement( NAMESPACE, key, key );" ); + sc.add("contentHandler.endElement( NAMESPACE, \"" + singular(associationName) + "\", \"" + + singular(associationName) + "\" );"); + } else { + if (isClassInModel( + association.getTo(), + association.getModelClass().getModel())) { + sc.add("write" + association.getTo() + "( value, key, contentHandler, attributes );"); + } else { + sc.add("contentHandler.startElement( NAMESPACE, key, key, attributes );"); + sc.add("writeText( " + getValue(association.getTo(), "value", xmlFieldMetadata) + + ", contentHandler );"); + sc.add("contentHandler.endElement( NAMESPACE, key, key );"); } } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\" );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); - - sc.add( "{" ); - if ( "DOM".equals( field.getType() ) ) - { - if ( domAsXpp3 ) - { - sc.addIndented( "writeDom( (Xpp3Dom) " + value + ", contentHandler, attributes );" ); - } - else - { - sc.addIndented( "writeDom( (Element) " + value + ", contentHandler );" ); + } else { + sc.add(getValueChecker(type, value, field)); + + sc.add("{"); + if ("DOM".equals(field.getType())) { + if (domAsXpp3) { + sc.addIndented("writeDom( (Xpp3Dom) " + value + ", contentHandler, attributes );"); + } else { + sc.addIndented("writeDom( (Element) " + value + ", contentHandler );"); } requiresDomSupport = true; - } - else - { + } else { sc.indent(); - sc.add( "contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\", attributes );" ); - sc.add( "writeText( " + getValue( field.getType(), value, xmlFieldMetadata ) + ", contentHandler );" ); - sc.add( "contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + "\" );" ); + sc.add("contentHandler.startElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\", attributes );"); + sc.add("writeText( " + getValue(field.getType(), value, xmlFieldMetadata) + ", contentHandler );"); + sc.add("contentHandler.endElement( NAMESPACE, \"" + fieldTagName + "\", \"" + fieldTagName + + "\" );"); sc.unindent(); } - sc.add( "}" ); + sc.add("}"); } } - sc.add( "contentHandler.endElement( NAMESPACE, tagName, tagName );" ); + sc.add("contentHandler.endElement( NAMESPACE, tagName, tagName );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void createXpp3DomMethod( JClass jClass ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); + private void createXpp3DomMethod(JClass jClass) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); - JMethod method = new JMethod( "writeDom" ); + JMethod method = new JMethod("writeDom"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "Xpp3Dom" ), "dom" ) ); - method.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); - method.addParameter( new JParameter( new JClass( "AttributesImpl" ), "attributes" ) ); + method.addParameter(new JParameter(new JType("Xpp3Dom"), "dom")); + method.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); + method.addParameter(new JParameter(new JClass("AttributesImpl"), "attributes")); - method.addException( new JClass( "SAXException" ) ); + method.addException(new JClass("SAXException")); JSourceCode sc = method.getSourceCode(); - sc.add( "String[] attributeNames = dom.getAttributeNames();" ); - sc.add( "if ( attributeNames != null && attributeNames.length > 0 )" ); - sc.add( "{" ); + sc.add("String[] attributeNames = dom.getAttributeNames();"); + sc.add("if ( attributeNames != null && attributeNames.length > 0 )"); + sc.add("{"); sc.indent(); - sc.add( "String attributeName;" ); - sc.add( "String attributeValue;" ); - sc.add( "for ( int i = 0; i < attributeNames.length; i++ )" ); - sc.add( "{" ); + sc.add("String attributeName;"); + sc.add("String attributeValue;"); + sc.add("for ( int i = 0; i < attributeNames.length; i++ )"); + sc.add("{"); sc.indent(); - sc.add( "attributeName = attributeNames[i];" ); - sc.add( "attributeValue = dom.getAttribute( attributeName );" ); - sc.add( "attributes.addAttribute( NAMESPACE, attributeName, attributeName, \"CDATA\", attributeValue );" ); + sc.add("attributeName = attributeNames[i];"); + sc.add("attributeValue = dom.getAttribute( attributeName );"); + sc.add("attributes.addAttribute( NAMESPACE, attributeName, attributeName, \"CDATA\", attributeValue );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "contentHandler.startElement( NAMESPACE, dom.getName(), dom.getName(), attributes );" ); + sc.add("contentHandler.startElement( NAMESPACE, dom.getName(), dom.getName(), attributes );"); - sc.add( "if ( attributeNames != null && attributeNames.length > 0 )" ); - sc.add( "{" ); - sc.addIndented( "attributes.clear();" ); - sc.add( "}" ); + sc.add("if ( attributeNames != null && attributeNames.length > 0 )"); + sc.add("{"); + sc.addIndented("attributes.clear();"); + sc.add("}"); - sc.add( "Xpp3Dom[] children = dom.getChildren();" ); - sc.add( "if ( children != null && children.length > 0 )" ); - sc.add( "{" ); + sc.add("Xpp3Dom[] children = dom.getChildren();"); + sc.add("if ( children != null && children.length > 0 )"); + sc.add("{"); sc.indent(); - sc.add( "for ( int i = 0; i < children.length; i++ )" ); - sc.add( "{" ); - sc.addIndented( "writeDom( children[i], contentHandler, attributes );" ); - sc.add( "}" ); + sc.add("for ( int i = 0; i < children.length; i++ )"); + sc.add("{"); + sc.addIndented("writeDom( children[i], contentHandler, attributes );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "String value = dom.getValue();" ); - sc.add( "if ( value != null )" ); - sc.add( "{" ); - sc.addIndented( "writeText( value, contentHandler );" ); - sc.add( "}" ); - sc.add( "contentHandler.endElement( NAMESPACE, dom.getName(), dom.getName() );" ); + sc.add("String value = dom.getValue();"); + sc.add("if ( value != null )"); + sc.add("{"); + sc.addIndented("writeText( value, contentHandler );"); + sc.add("}"); + sc.add("contentHandler.endElement( NAMESPACE, dom.getName(), dom.getName() );"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private void createWriteDomMethod( JClass jClass ) - { - jClass.addImport( "org.w3c.dom.Element" ); - jClass.addImport( "javax.xml.transform.Transformer" ); - jClass.addImport( "javax.xml.transform.dom.DOMSource" ); - jClass.addImport( "javax.xml.transform.sax.SAXResult" ); + private void createWriteDomMethod(JClass jClass) { + jClass.addImport("org.w3c.dom.Element"); + jClass.addImport("javax.xml.transform.Transformer"); + jClass.addImport("javax.xml.transform.dom.DOMSource"); + jClass.addImport("javax.xml.transform.sax.SAXResult"); - JMethod method = new JMethod( "writeDom" ); + JMethod method = new JMethod("writeDom"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "Element" ), "dom" ) ); - method.addParameter( new JParameter( new JClass( "ContentHandler" ), "contentHandler" ) ); + method.addParameter(new JParameter(new JType("Element"), "dom")); + method.addParameter(new JParameter(new JClass("ContentHandler"), "contentHandler")); - method.addException( new JClass( "SAXException" ) ); + method.addException(new JClass("SAXException")); JSourceCode sc = method.getSourceCode(); - sc.add( "try" ); - sc.add( "{" ); + sc.add("try"); + sc.add("{"); sc.indent(); - sc.add( "Transformer transformer = transformerFactory.newTransformer();" ); - sc.add( "DOMSource source = new DOMSource( dom );" ); - sc.add( "SAXResult result = new SAXResult( contentHandler );" ); - sc.add( "transformer.transform( source, result );" ); + sc.add("Transformer transformer = transformerFactory.newTransformer();"); + sc.add("DOMSource source = new DOMSource( dom );"); + sc.add("SAXResult result = new SAXResult( contentHandler );"); + sc.add("transformer.transform( source, result );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "catch ( TransformerException e )" ); - sc.add( "{" ); - sc.addIndented( "throw new SAXException( \"Impossible to convert DOM element, see nested exceptions.\", e );" ); - sc.add( "}" ); + sc.add("catch ( TransformerException e )"); + sc.add("{"); + sc.addIndented("throw new SAXException( \"Impossible to convert DOM element, see nested exceptions.\", e );"); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); } - } diff --git a/modello-plugins/modello-plugin-sax/src/test/java/org/codehaus/modello/plugin/sax/SaxGeneratorTest.java b/modello-plugins/modello-plugin-sax/src/test/java/org/codehaus/modello/plugin/sax/SaxGeneratorTest.java index e0fa8b107..92b66315c 100644 --- a/modello-plugins/modello-plugin-sax/src/test/java/org/codehaus/modello/plugin/sax/SaxGeneratorTest.java +++ b/modello-plugins/modello-plugin-sax/src/test/java/org/codehaus/modello/plugin/sax/SaxGeneratorTest.java @@ -36,64 +36,59 @@ /** * @author Simone Tripodi */ -public class SaxGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public SaxGeneratorTest() - { - super( "sax" ); +public class SaxGeneratorTest extends AbstractModelloJavaGeneratorTest { + public SaxGeneratorTest() { + super("sax"); } - public void testXpp3Generator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXpp3Generator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); // check some elements read from the model - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 28, classesList.size() ); + assertEquals(28, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); // now generate sources and test them - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "sax-writer", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "sax-writer", parameters); - addDependency( "org.xmlunit", "xmlunit-core" ); + addDependency("org.xmlunit", "xmlunit-core"); compileGeneratedSources(); // TODO: see why without this, version system property is set to "2.4.1" value after verify - System.setProperty( "version", getModelloVersion() ); + System.setProperty("version", getModelloVersion()); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.sax.SaxVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.sax.SaxVerifier"); } } diff --git a/modello-plugins/modello-plugin-snakeyaml/pom.xml b/modello-plugins/modello-plugin-snakeyaml/pom.xml index 11576a39c..248a21c8c 100644 --- a/modello-plugins/modello-plugin-snakeyaml/pom.xml +++ b/modello-plugins/modello-plugin-snakeyaml/pom.xml @@ -1,12 +1,12 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-snakeyaml Modello SnakeYaml Plugin Modello SnakeYaml Plugin generates YAML readers and writers based on SnakeYaml Streaming APIs, plus reader delegates to be able to read diff --git a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/AbstractSnakeYamlGenerator.java b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/AbstractSnakeYamlGenerator.java index 2434cd475..541c6439f 100644 --- a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/AbstractSnakeYamlGenerator.java +++ b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/AbstractSnakeYamlGenerator.java @@ -27,7 +27,4 @@ /** * @author Simone Tripodi */ -public abstract class AbstractSnakeYamlGenerator - extends AbstractXmlJavaGenerator -{ -} +public abstract class AbstractSnakeYamlGenerator extends AbstractXmlJavaGenerator {} diff --git a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlExtendedReaderGenerator.java b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlExtendedReaderGenerator.java index c9279bfc3..6dc2a6566 100644 --- a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlExtendedReaderGenerator.java +++ b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlExtendedReaderGenerator.java @@ -31,21 +31,16 @@ * * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "snakeyaml-extended-reader" ) -public class SnakeYamlExtendedReaderGenerator - extends SnakeYamlReaderGenerator -{ +@Component(role = ModelloGenerator.class, hint = "snakeyaml-extended-reader") +public class SnakeYamlExtendedReaderGenerator extends SnakeYamlReaderGenerator { @Override - protected boolean isRelevant( ModelClass modelClass ) - { - return isJavaEnabled( modelClass ); + protected boolean isRelevant(ModelClass modelClass) { + return isJavaEnabled(modelClass); } @Override - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return true; } - } diff --git a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlReaderGenerator.java b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlReaderGenerator.java index 4fa9fd076..9f65c6447 100644 --- a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlReaderGenerator.java +++ b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlReaderGenerator.java @@ -51,10 +51,8 @@ /** * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "snakeyaml-reader" ) -public class SnakeYamlReaderGenerator - extends AbstractSnakeYamlGenerator -{ +@Component(role = ModelloGenerator.class, hint = "snakeyaml-reader") +public class SnakeYamlReaderGenerator extends AbstractSnakeYamlGenerator { private static final String SOURCE_PARAM = "source"; @@ -68,89 +66,73 @@ public class SnakeYamlReaderGenerator private String trackingArgs; - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return false; } - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); locationTracker = sourceTracker = null; trackingArgs = locationField = ""; - if ( isLocationTracking() ) - { - locationTracker = model.getLocationTracker( getGeneratedVersion() ); - if ( locationTracker == null ) - { - throw new ModelloException( "No model class has been marked as location tracker" - + " via the attribute locationTracker=\"locations\"" - + ", cannot generate extended reader." ); + if (isLocationTracking()) { + locationTracker = model.getLocationTracker(getGeneratedVersion()); + if (locationTracker == null) { + throw new ModelloException("No model class has been marked as location tracker" + + " via the attribute locationTracker=\"locations\"" + + ", cannot generate extended reader."); } locationField = - ( (ModelClassMetadata) locationTracker.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); + ((ModelClassMetadata) locationTracker.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); - sourceTracker = model.getSourceTracker( getGeneratedVersion() ); + sourceTracker = model.getSourceTracker(getGeneratedVersion()); - if ( sourceTracker != null ) - { + if (sourceTracker != null) { trackingArgs += ", " + SOURCE_PARAM; } } - try - { + try { generateSnakeYamlReader(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating SnakeYaml Reader.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating SnakeYaml Reader.", ex); } } - private void writeAllClassesReaders( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesReaders(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassReaders( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassReaders(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassReaders(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } - XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata( XmlClassMetadata.ID ); - if ( !rootElement && !xmlClassMetadata.isStandaloneRead() ) - { + XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata(XmlClassMetadata.ID); + if (!rootElement && !xmlClassMetadata.isStandaloneRead()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); String readerMethodName = "read"; - if ( !rootElement ) - { + if (!rootElement) { readerMethodName += capClassName; } @@ -158,327 +140,320 @@ private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean ro // Write the read(Parser) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + JMethod unmarshall = new JMethod(readerMethodName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "Parser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("Parser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); JSourceCode sc = unmarshall.getSourceCode(); - String variableName = uncapitalise( className ); + String variableName = uncapitalise(className); - sc.add( "Event event;" ); + sc.add("Event event;"); - sc.add( "if ( !( event = parser.getEvent() ).is( Event.ID.StreamStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected Stream Start event\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !( event = parser.getEvent() ).is( Event.ID.StreamStart ) )"); + sc.add("{"); + sc.addIndented( + "throw new ParserException( \"Expected Stream Start event\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "if ( !( event = parser.getEvent() ).is( Event.ID.DocumentStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected Document Start event\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !( event = parser.getEvent() ).is( Event.ID.DocumentStart ) )"); + sc.add("{"); + sc.addIndented( + "throw new ParserException( \"Expected Document Start event\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( - className + ' ' + variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );" ); + sc.add(className + ' ' + variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );"); - if ( rootElement ) - { + if (rootElement) { // TODO // sc.add( variableName + ".setModelEncoding( parser.getInputEncoding() );" ); } - sc.add( "" ); + sc.add(""); - sc.add( "if ( !( event = parser.getEvent() ).is( Event.ID.DocumentEnd ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected Document End event\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !( event = parser.getEvent() ).is( Event.ID.DocumentEnd ) )"); + sc.add("{"); + sc.addIndented( + "throw new ParserException( \"Expected Document End event\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "if ( !( event = parser.getEvent() ).is( Event.ID.StreamEnd ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected Stream End event\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !( event = parser.getEvent() ).is( Event.ID.StreamEnd ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected Stream End event\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( "return " + variableName + ';' ); + sc.add("return " + variableName + ';'); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(Reader[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "Parser parser = new ParserImpl( new StreamReader( reader ) );" ); + sc.add("Parser parser = new ParserImpl( new StreamReader( reader ) );"); - sc.add( "return " + readerMethodName + "( parser, strict );" ); + sc.add("return " + readerMethodName + "( parser, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( reader, true );" ); + sc.add("return " + readerMethodName + "( reader, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(InputStream[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( new InputStreamReader( in ), strict" + trackingArgs + " );" ); + sc.add("return " + readerMethodName + "( new InputStreamReader( in ), strict" + trackingArgs + " );"); - jClass.addMethod( unmarshall );unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + jClass.addMethod(unmarshall); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( in, true );" ); + sc.add("return " + readerMethodName + "( in, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // -------------------------------------------------------------------- } - private void generateSnakeYamlReader() - throws ModelloException, IOException - { + private void generateSnakeYamlReader() throws ModelloException, IOException { Model objectModel = getModel(); String packageName = - objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) + ".io.snakeyaml"; - - String unmarshallerName = getFileName( "SnakeYamlReader" + ( isLocationTracking() ? "Ex" : "" ) ); - - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); - - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); - - jClass.addImport( "org.yaml.snakeyaml.events.DocumentEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.DocumentStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.Event" ); - jClass.addImport( "org.yaml.snakeyaml.events.ImplicitTuple" ); - jClass.addImport( "org.yaml.snakeyaml.events.MappingEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.MappingStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.ScalarEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.SequenceEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.SequenceStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.StreamEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.StreamStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.parser.Parser" ); - jClass.addImport( "org.yaml.snakeyaml.parser.ParserException" ); - jClass.addImport( "org.yaml.snakeyaml.parser.ParserImpl" ); - jClass.addImport( "org.yaml.snakeyaml.reader.StreamReader" ); - jClass.addImport( "java.io.InputStream" ); - jClass.addImport( "java.io.InputStreamReader" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.util.Set" ); - jClass.addImport( "java.util.HashSet" ); - - addModelImports( jClass, null ); + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.snakeyaml"; + + String unmarshallerName = getFileName("SnakeYamlReader" + (isLocationTracking() ? "Ex" : "")); + + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); + + JClass jClass = new JClass(packageName + '.' + unmarshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); + + jClass.addImport("org.yaml.snakeyaml.events.DocumentEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.DocumentStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.Event"); + jClass.addImport("org.yaml.snakeyaml.events.ImplicitTuple"); + jClass.addImport("org.yaml.snakeyaml.events.MappingEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.MappingStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.ScalarEvent"); + jClass.addImport("org.yaml.snakeyaml.events.SequenceEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.SequenceStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.StreamEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.StreamStartEvent"); + jClass.addImport("org.yaml.snakeyaml.parser.Parser"); + jClass.addImport("org.yaml.snakeyaml.parser.ParserException"); + jClass.addImport("org.yaml.snakeyaml.parser.ParserImpl"); + jClass.addImport("org.yaml.snakeyaml.reader.StreamReader"); + jClass.addImport("java.io.InputStream"); + jClass.addImport("java.io.InputStreamReader"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.util.Set"); + jClass.addImport("java.util.HashSet"); + + addModelImports(jClass, null); // ---------------------------------------------------------------------- // Write the class parsers // ---------------------------------------------------------------------- - writeAllClassesParser( objectModel, jClass ); + writeAllClassesParser(objectModel, jClass); // ---------------------------------------------------------------------- // Write the class readers // ---------------------------------------------------------------------- - writeAllClassesReaders( objectModel, jClass ); + writeAllClassesReaders(objectModel, jClass); // ---------------------------------------------------------------------- // Write helpers // ---------------------------------------------------------------------- - writeHelpers( jClass ); + writeHelpers(jClass); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClassesParser( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesParser(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassParser(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassParser(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null ); + JMethod unmarshall = new JMethod("parse" + capClassName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "Parser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("Parser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); + unmarshall.addException(new JClass("IOException")); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( "Event event = parser.getEvent();" ); + sc.add("Event event = parser.getEvent();"); - sc.add( "" ); + sc.add(""); - sc.add( "if ( !event.is( Event.ID.MappingStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected '" - + className - + "' data to start with a Mapping\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !event.is( Event.ID.MappingStart ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected '" + + className + + "' data to start with a Mapping\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( className + " " + uncapClassName + " = new " + className + "();" ); + sc.add(className + " " + uncapClassName + " = new " + className + "();"); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + ";" ); - writeNewSetLocation( "\"\"", uncapClassName, null, sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + ";"); + writeNewSetLocation("\"\"", uncapClassName, null, sc); } ModelField contentField = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // read all XML attributes first - contentField = writeClassAttributesParser( modelFields, uncapClassName, rootElement ); + contentField = writeClassAttributesParser(modelFields, uncapClassName, rootElement); // then read content, either content field or elements - if ( contentField != null ) - { - writePrimitiveField( contentField, contentField.getType(), uncapClassName, uncapClassName, "\"\"", - "set" + capitalise( contentField.getName() ), sc, false ); - } - else - { - //Write other fields - - sc.add( "Set parsed = new HashSet();" ); - - sc.add( "" ); - - sc.add( "while ( !( event = parser.getEvent() ).is( Event.ID.MappingEnd ) )" ); - - sc.add( "{" ); + if (contentField != null) { + writePrimitiveField( + contentField, + contentField.getType(), + uncapClassName, + uncapClassName, + "\"\"", + "set" + capitalise(contentField.getName()), + sc, + false); + } else { + // Write other fields + + sc.add("Set parsed = new HashSet();"); + + sc.add(""); + + sc.add("while ( !( event = parser.getEvent() ).is( Event.ID.MappingEnd ) )"); + + sc.add("{"); sc.indent(); boolean addElse = false; - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass ); + processField(field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass); addElse = true; } - if ( addElse ) - { - sc.add( "else" ); + if (addElse) { + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.indent(); } - sc.add( "checkUnknownElement( event, parser, strict );" ); + sc.add("checkUnknownElement( event, parser, strict );"); - if ( addElse ) - { + if (addElse) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "return " + uncapClassName + ";" ); + sc.add("return " + uncapClassName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } - private ModelField writeClassAttributesParser( List modelFields, String objectName, boolean rootElement ) - { + private ModelField writeClassAttributesParser( + List modelFields, String objectName, boolean rootElement) { ModelField contentField = null; - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); // TODO check if we have already one with this type and throws Exception - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; } } @@ -496,751 +471,718 @@ private ModelField writeClassAttributesParser( List modelFields, Str * @param objectName the object name in the source * @param jClass the generated class source file */ - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc, - String objectName, JClass jClass ) - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + boolean addElse, + JSourceCode sc, + String objectName, + JClass jClass) { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String capFieldName = capitalise( field.getName() ); + String capFieldName = capitalise(field.getName()); - String singularName = singular( field.getName() ); + String singularName = singular(field.getName()); String alias; - if ( StringUtils.isEmpty( field.getAlias() ) ) - { + if (StringUtils.isEmpty(field.getAlias())) { alias = "null"; - } - else - { + } else { alias = "\"" + field.getAlias() + "\""; } - String tagComparison = - ( addElse ? "else " : "" ) + "if ( checkFieldWithDuplicate( event, \"" + fieldTagName + "\", " + alias - + ", parsed ) )"; + String tagComparison = (addElse ? "else " : "") + "if ( checkFieldWithDuplicate( event, \"" + fieldTagName + + "\", " + alias + ", parsed ) )"; - if ( !( field instanceof ModelAssociation ) ) - { // model field - sc.add( tagComparison ); + if (!(field instanceof ModelAssociation)) { // model field + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writePrimitiveField( field, field.getType(), objectName, objectName, "\"" + field.getName() + "\"", - "set" + capFieldName, sc, false ); + writePrimitiveField( + field, + field.getType(), + objectName, + objectName, + "\"" + field.getName() + "\"", + "set" + capFieldName, + sc, + false); sc.unindent(); - sc.add( "}" ); - } - else - { // model association + sc.add("}"); + } else { // model association ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( tagComparison ); + if (association.isOneMultiplicity()) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); // sc.add( "// consume current key" ); // sc.add( "parser.getEvent();" ); - sc.add( objectName + sc.add(objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict" + trackingArgs - + " ) );" ); + + " ) );"); sc.unindent(); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); String type = association.getType(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - boolean inModel = isClassInModel( association.getTo(), field.getModelClass().getModel() ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + boolean inModel = isClassInModel( + association.getTo(), field.getModelClass().getModel()); - sc.add( ( addElse ? "else " : "" ) + sc.add((addElse ? "else " : "") + "if ( checkFieldWithDuplicate( event, \"" + fieldTagName + "\", " + alias - + ", parsed ) )" ); + + ", parsed ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( !parser.getEvent().is( Event.ID.SequenceStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected '" - + field.getName() - + "' data to start with a Sequence\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !parser.getEvent().is( Event.ID.SequenceStart ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected '" + + field.getName() + + "' data to start with a Sequence\", event.getStartMark(), \"\", null );"); + sc.add("}"); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) association.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) association.getMetadata(JavaFieldMetadata.ID); String adder; - if ( javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter() ) - { - sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" ); + if (javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter()) { + sc.add(type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();"); - sc.add( "if ( " + associationName + " == null )" ); + sc.add("if ( " + associationName + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( associationName + " = " + association.getDefaultValue() + ";" ); + sc.add(associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } - if ( !inModel && locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" - + capitalise( singular( locationField ) ) + "( \"" + field.getName() - + "\" );" ); - sc.add( "if ( " + LOCATION_VAR + "s == null )" ); - sc.add( "{" ); + if (!inModel && locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" + + capitalise(singular(locationField)) + "( \"" + field.getName() + + "\" );"); + sc.add("if ( " + LOCATION_VAR + "s == null )"); + sc.add("{"); sc.indent(); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - if ( inModel ) - { - sc.add( "while ( !parser.peekEvent().is( Event.ID.SequenceEnd ) )" ); - sc.add( "{" ); + if (inModel) { + sc.add("while ( !parser.peekEvent().is( Event.ID.SequenceEnd ) )"); + sc.add("{"); - sc.addIndented( adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );" ); + sc.addIndented( + adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );"); - sc.add( "}" ); + sc.add("}"); - sc.add( "parser.getEvent();" ); - } - else - { + sc.add("parser.getEvent();"); + } else { String key; - if ( ModelDefault.SET.equals( type ) ) - { + if (ModelDefault.SET.equals(type)) { key = "?"; + } else { + key = (hasJavaSourceSupport(5) ? "Integer.valueOf" : "new java.lang.Integer") + "( " + + associationName + ".size() )"; } - else - { - key = ( hasJavaSourceSupport( 5 ) ? "Integer.valueOf" : "new java.lang.Integer" ) + "( " + associationName - + ".size() )"; - } - writePrimitiveField( association, association.getTo(), associationName, LOCATION_VAR + "s", key, - "add", sc, false ); + writePrimitiveField( + association, + association.getTo(), + associationName, + LOCATION_VAR + "s", + key, + "add", + sc, + false); } sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( tagComparison ); + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s;" ); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s;"); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); } - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "if ( !parser.getEvent().is( Event.ID.SequenceStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected '" - + field.getName() - + "' data to start with a Sequence\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("if ( !parser.getEvent().is( Event.ID.SequenceStart ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected '" + + field.getName() + + "' data to start with a Sequence\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "while ( !parser.peekEvent().is( Event.ID.SequenceEnd ) )" ); + sc.add("while ( !parser.peekEvent().is( Event.ID.SequenceEnd ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "event = parser.getEvent();" ); + sc.add("event = parser.getEvent();"); - sc.add( "" ); + sc.add(""); - sc.add( "if ( !event.is( Event.ID.MappingStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected '" - + fieldTagName - + "' item data to start with a Mapping\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !event.is( Event.ID.MappingStart ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected '" + + fieldTagName + + "' item data to start with a Mapping\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "String key = null;" ); + sc.add("String key = null;"); - sc.add( "String value = null;" ); + sc.add("String value = null;"); - sc.add( "Set parsedPropertiesElements = new HashSet();" ); + sc.add("Set parsedPropertiesElements = new HashSet();"); - sc.add( "while ( !( event = parser.getEvent() ).is( Event.ID.MappingEnd ) )" ); + sc.add("while ( !( event = parser.getEvent() ).is( Event.ID.MappingEnd ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( checkFieldWithDuplicate( event, \"key\", \"\", parsedPropertiesElements ) )" ); - sc.add( "{" ); + sc.add("if ( checkFieldWithDuplicate( event, \"key\", \"\", parsedPropertiesElements ) )"); + sc.add("{"); String parserGetter = "( (ScalarEvent) parser.getEvent() ).getValue()"; - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - sc.addIndented( "key = " + parserGetter + ";" ); + sc.addIndented("key = " + parserGetter + ";"); - sc.add( "}" ); - sc.add( "else if ( checkFieldWithDuplicate( event, \"value\", \"\", parsedPropertiesElements ) )" ); - sc.add( "{" ); + sc.add("}"); + sc.add( + "else if ( checkFieldWithDuplicate( event, \"value\", \"\", parsedPropertiesElements ) )"); + sc.add("{"); parserGetter = "( (ScalarEvent) parser.getEvent() ).getValue()"; - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - sc.addIndented( "value = " + parserGetter + ";" ); + sc.addIndented("value = " + parserGetter + ";"); - sc.add( "}" ); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); + sc.add("{"); - sc.addIndented( "checkUnknownElement( event, parser, strict );" ); + sc.addIndented("checkUnknownElement( event, parser, strict );"); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); - } - else - { - //INLINE Mode + sc.add("}"); + } else { + // INLINE Mode - sc.add( "if ( !parser.getEvent().is( Event.ID.MappingStart ) )" ); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Expected '" - + field.getName() - + "' data to start with a Mapping\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("if ( !parser.getEvent().is( Event.ID.MappingStart ) )"); + sc.add("{"); + sc.addIndented("throw new ParserException( \"Expected '" + + field.getName() + + "' data to start with a Mapping\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "while ( !parser.peekEvent().is( Event.ID.MappingEnd ) )" ); + sc.add("while ( !parser.peekEvent().is( Event.ID.MappingEnd ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = ( (ScalarEvent) parser.getEvent() ).getValue();" ); + sc.add("String key = ( (ScalarEvent) parser.getEvent() ).getValue();"); - writeNewSetLocation( "key", LOCATION_VAR + "s", null, sc ); + writeNewSetLocation("key", LOCATION_VAR + "s", null, sc); - sc.add( - "String value = ( (ScalarEvent) parser.getEvent() ).getValue()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + sc.add("String value = ( (ScalarEvent) parser.getEvent() ).getValue()" + + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "parser.getEvent();" ); + sc.add("parser.getEvent();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } } } - private void writeHelpers( JClass jClass ) - { - JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null ); + private void writeHelpers(JClass jClass) { + JMethod method = new JMethod("getTrimmedValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "s = s.trim();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = s.trim();"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null ); - method.addException( new JClass( "ParserException" ) ); + method = new JMethod("getRequiredAttributeValue", new JClass("String"), null); + method.addException(new JClass("ParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "Parser" ), "parser" ) ); - method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("Parser"), "parser")); + method.addParameter(new JParameter(JClass.BOOLEAN, "strict")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new ParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser.peekEvent().getStartMark(), \"\", null );" ); - sc.add( "}" ); + "throw new ParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser.peekEvent().getStartMark(), \"\", null );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null ); + method = new JMethod("checkFieldWithDuplicate", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Event" ), "event" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "alias" ) ); - method.addParameter( new JParameter( new JClass( "Set" ), "parsed" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("Event"), "event")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(new JClass("String"), "alias")); + method.addParameter(new JParameter(new JClass("Set"), "parsed")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "String currentName = ( (ScalarEvent) event ).getValue();" ); + sc.add("String currentName = ( (ScalarEvent) event ).getValue();"); - sc.add( "" ); + sc.add(""); - sc.add( "if ( !( currentName.equals( tagName ) || currentName.equals( alias ) ) )" ); + sc.add("if ( !( currentName.equals( tagName ) || currentName.equals( alias ) ) )"); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); - sc.add( "if ( !parsed.add( tagName ) )" ); + sc.add("if ( !parsed.add( tagName ) )"); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"Duplicated tag: '\" + tagName + \"'\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented( + "throw new ParserException( \"Duplicated tag: '\" + tagName + \"'\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "return true;" ); + sc.add("return true;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownElement", null, null ); + method = new JMethod("checkUnknownElement", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Event" ), "event" ) ); - method.addParameter( new JParameter( new JClass( "Parser" ), "parser" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("Event"), "event")); + method.addParameter(new JParameter(new JClass("Parser"), "parser")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new ParserException( \"Unrecognised tag: '\" + ( (ScalarEvent) event ).getValue() + \"'\", event.getStartMark(), \"\", null );" ); - sc.add( "}" ); + "throw new ParserException( \"Unrecognised tag: '\" + ( (ScalarEvent) event ).getValue() + \"'\", event.getStartMark(), \"\", null );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( "for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )" ); - sc.add( "{" ); + sc.add("for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )"); + sc.add("{"); sc.indent(); - sc.add( "event = parser.getEvent();" ); - sc.add( "if ( event.is( Event.ID.MappingStart ) )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount++;" ); - sc.add( "}" ); - sc.add( "else if ( event.is( Event.ID.MappingEnd ) )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount--;" ); - sc.add( "}" ); + sc.add("event = parser.getEvent();"); + sc.add("if ( event.is( Event.ID.MappingStart ) )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount++;"); + sc.add("}"); + sc.add("else if ( event.is( Event.ID.MappingEnd ) )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount--;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownAttribute", null, null ); + method = new JMethod("checkUnknownAttribute", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "Parser" ), "parser" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("Parser"), "parser")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - if ( strictXmlAttributes ) - { + if (strictXmlAttributes) { sc.add( - "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too" ); - sc.add( "if ( strict )" ); + "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too"); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new ParserException( \"\", parser.peekEvent().getStartMark(), \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser.peekEvent().getEndMark() );" ); - sc.add( "}" ); - } - else - { + "throw new ParserException( \"\", parser.peekEvent().getStartMark(), \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser.peekEvent().getEndMark() );"); + sc.add("}"); + } else { sc.add( - "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true" ); + "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true"); } - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getBooleanValue", JType.BOOLEAN, null ); + method = new JMethod("getBooleanValue", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return Boolean.valueOf( s ).booleanValue();"); + sc.add("}"); - sc.add( "return false;" ); + sc.add("return false;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getCharacterValue", JType.CHAR, null ); + method = new JMethod("getCharacterValue", JType.CHAR, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return s.charAt( 0 );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return s.charAt( 0 );"); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" ); + method = convertNumericalType("getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", - "a short integer" ); + method = convertNumericalType( + "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", "a short integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" ); + method = convertNumericalType("getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" ); + method = convertNumericalType("getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", - "a floating point number" ); + method = convertNumericalType( + "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", - "a floating point number" ); + method = convertNumericalType( + "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null ); + method = new JMethod("getDateValue", new JClass("java.util.Date"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "dateFormat" ) ); - method.addParameter( new JParameter( new JClass( "Event" ), "event" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "dateFormat")); + method.addParameter(new JParameter(new JClass("Event"), "event")); - writeDateParsingHelper( method.getSourceCode(), "new ParserException( \"\", event.getStartMark(), e.getMessage(), event.getEndMark() )" ); + writeDateParsingHelper( + method.getSourceCode(), + "new ParserException( \"\", event.getStartMark(), e.getMessage(), event.getEndMark() )"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getDefaultValue", new JClass( "String" ), null ); + method = new JMethod("getDefaultValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "v" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "v")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); - sc.addIndented( "s = v;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = v;"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private void addTrackingParameters( JMethod method ) - { - if ( sourceTracker != null ) - { - method.addParameter( new JParameter( new JClass( sourceTracker.getName() ), SOURCE_PARAM ) ); + private void addTrackingParameters(JMethod method) { + if (sourceTracker != null) { + method.addParameter(new JParameter(new JClass(sourceTracker.getName()), SOURCE_PARAM)); } } - private void writeNewSetLocation( ModelField field, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewSetLocation( "\"" + field.getName() + "\"", objectName, trackerVariable, sc ); + private void writeNewSetLocation(ModelField field, String objectName, String trackerVariable, JSourceCode sc) { + writeNewSetLocation("\"" + field.getName() + "\"", objectName, trackerVariable, sc); } - private void writeNewSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewLocation( trackerVariable, sc ); - writeSetLocation( key, objectName, trackerVariable, sc ); + private void writeNewSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + writeNewLocation(trackerVariable, sc); + writeSetLocation(key, objectName, trackerVariable, sc); } - private void writeNewLocation( String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeNewLocation(String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } String constr = "new " + locationTracker.getName() + "( parser.getLineNumber(), parser.getColumnNumber()"; - constr += ( sourceTracker != null ) ? ", " + SOURCE_PARAM : ""; + constr += (sourceTracker != null) ? ", " + SOURCE_PARAM : ""; constr += " )"; - sc.add( ( ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR ) + " = " + constr + ";" ); + sc.add(((trackerVariable != null) ? trackerVariable : LOCATION_VAR) + " = " + constr + ";"); } - private void writeSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } - String variable = ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR; + String variable = (trackerVariable != null) ? trackerVariable : LOCATION_VAR; - sc.add( objectName + ".set" + capitalise( singular( locationField ) ) + "( " + key + ", " + variable + " );" ); + sc.add(objectName + ".set" + capitalise(singular(locationField)) + "( " + key + ", " + variable + " );"); } /** - * Write code to set a primitive field with a value got from the parser, with appropriate default value, trimming - * and required check logic. - * - * @param field the model field to set (either XML attribute or element) - * @param type the type of the value read from XML - * @param objectName the object name in source - * @param setterName the setter method name - * @param sc the source code to add to - */ - private void writePrimitiveField( ModelField field, String type, String objectName, String locatorName, - String locationKey, String setterName, JSourceCode sc, boolean wrappedItem ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); - - String tagName = resolveTagName( field, xmlFieldMetadata ); - - String parserGetter = "( (ScalarEvent) parser.getEvent() ).getValue()"; - - /* TODO: - if ( xmlFieldMetadata.isRequired() ) - { - parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; - } - */ - if ( field.getDefaultValue() != null ) - { - parserGetter = "getDefaultValue( " + parserGetter + ", \"" + field.getDefaultValue() + "\" )"; - } + * Write code to set a primitive field with a value got from the parser, with appropriate default value, trimming + * and required check logic. + * + * @param field the model field to set (either XML attribute or element) + * @param type the type of the value read from XML + * @param objectName the object name in source + * @param setterName the setter method name + * @param sc the source code to add to + */ + private void writePrimitiveField( + ModelField field, + String type, + String objectName, + String locatorName, + String locationKey, + String setterName, + JSourceCode sc, + boolean wrappedItem) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); + + String tagName = resolveTagName(field, xmlFieldMetadata); + + String parserGetter = "( (ScalarEvent) parser.getEvent() ).getValue()"; + + /* TODO: + if ( xmlFieldMetadata.isRequired() ) + { + parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; + } + */ + if (field.getDefaultValue() != null) { + parserGetter = "getDefaultValue( " + parserGetter + ", \"" + field.getDefaultValue() + "\" )"; + } - if ( xmlFieldMetadata.isTrim() ) - { - parserGetter = "getTrimmedValue( " + parserGetter + " )"; - } + if (xmlFieldMetadata.isTrim()) { + parserGetter = "getTrimmedValue( " + parserGetter + " )"; + } - if ( "boolean".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getBooleanValue( " + parserGetter + " ) );" ); - } - else if ( "char".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName - + "\" ) );" ); - } - else if ( "double".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "float".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "int".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "long".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "short".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "byte".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName - + "\", parser.peekEvent(), strict ) );" ); - } - else if ( "String".equals( type ) || "Boolean".equals( type ) ) - { - // TODO: other Primitive types - sc.add( objectName + "." + setterName + "( " + parserGetter + " );" ); - } - else if ( "Date".equals( type ) ) - { - sc.add( "String dateFormat = " - + ( xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null" ) + ";" ); - sc.add( objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName - + "\", dateFormat, parser.peekEvent() ) );" ); - } - else - { - throw new IllegalArgumentException( "Unknown type " - + type - + " for field " - + field.getModelClass().getName() - + "." - + field.getName() ); - } + if ("boolean".equals(type)) { + sc.add(objectName + "." + setterName + "( getBooleanValue( " + parserGetter + " ) );"); + } else if ("char".equals(type)) { + sc.add(objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName + + "\" ) );"); + } else if ("double".equals(type)) { + sc.add(objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("float".equals(type)) { + sc.add(objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("int".equals(type)) { + sc.add(objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("long".equals(type)) { + sc.add(objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("short".equals(type)) { + sc.add(objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("byte".equals(type)) { + sc.add(objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName + + "\", parser.peekEvent(), strict ) );"); + } else if ("String".equals(type) || "Boolean".equals(type)) { + // TODO: other Primitive types + sc.add(objectName + "." + setterName + "( " + parserGetter + " );"); + } else if ("Date".equals(type)) { + sc.add("String dateFormat = " + + (xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null") + + ";"); + sc.add(objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName + + "\", dateFormat, parser.peekEvent() ) );"); + } else { + throw new IllegalArgumentException("Unknown type " + + type + + " for field " + + field.getModelClass().getName() + + "." + + field.getName()); } + } - private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc ) - { - JMethod method = new JMethod( methodName, returnType, null ); + private JMethod convertNumericalType(String methodName, JType returnType, String expression, String typeDesc) { + JMethod method = new JMethod(methodName, returnType, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "Event" ), "event" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("Event"), "event")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "try" ); + sc.add("try"); - sc.add( "{" ); - sc.addIndented( "return " + expression + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return " + expression + ";"); + sc.add("}"); - sc.add( "catch ( NumberFormatException nfe )" ); + sc.add("catch ( NumberFormatException nfe )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new ParserException( \"\", event.getStartMark(), \"Unable to parse element '\" + attribute + \"', must be " + sc.add("{"); + sc.addIndented( + "throw new ParserException( \"\", event.getStartMark(), \"Unable to parse element '\" + attribute + \"', must be " + typeDesc - + " but was '\" + s + \"'\", event.getEndMark() );" ); - sc.add( "}" ); + + " but was '\" + s + \"'\", event.getEndMark() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); return method; } - } diff --git a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlWriterGenerator.java b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlWriterGenerator.java index ee240197f..8305e4408 100644 --- a/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlWriterGenerator.java +++ b/modello-plugins/modello-plugin-snakeyaml/src/main/java/org/codehaus/modello/plugin/snakeyaml/SnakeYamlWriterGenerator.java @@ -48,439 +48,384 @@ /** * @author Simone Tripodi */ -@Component( role = ModelloGenerator.class, hint = "snakeyaml-writer" ) -public class SnakeYamlWriterGenerator - extends AbstractSnakeYamlGenerator -{ - - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); - - try - { +@Component(role = ModelloGenerator.class, hint = "snakeyaml-writer") +public class SnakeYamlWriterGenerator extends AbstractSnakeYamlGenerator { + + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + try { generateSnakeYamlWriter(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating SnakeYaml Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating SnakeYaml Writer.", ex); } } - private void generateSnakeYamlWriter() - throws ModelloException, IOException - { + private void generateSnakeYamlWriter() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.snakeyaml"; - - String marshallerName = getFileName( "SnakeYamlWriter" ); - - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); - - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - - jClass.addImport( "org.yaml.snakeyaml.DumperOptions" ); - jClass.addImport( "org.yaml.snakeyaml.DumperOptions.Version" ); - jClass.addImport( "org.yaml.snakeyaml.DumperOptions.FlowStyle" ); - jClass.addImport( "org.yaml.snakeyaml.DumperOptions.ScalarStyle" ); - jClass.addImport( "org.yaml.snakeyaml.emitter.Emitable" ); - jClass.addImport( "org.yaml.snakeyaml.emitter.Emitter" ); - jClass.addImport( "org.yaml.snakeyaml.error.Mark" ); - jClass.addImport( "org.yaml.snakeyaml.events.DocumentEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.DocumentStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.ImplicitTuple" ); - jClass.addImport( "org.yaml.snakeyaml.events.MappingEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.MappingStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.ScalarEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.SequenceEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.SequenceStartEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.StreamEndEvent" ); - jClass.addImport( "org.yaml.snakeyaml.events.StreamStartEvent" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.OutputStreamWriter" ); - jClass.addImport( "java.io.Writer" ); - - addModelImports( jClass, null ); - - JField factoryField = new JField( new JClass( "DumperOptions" ), "dumperOptions" ); - factoryField.getModifiers().setFinal( true ); - factoryField.setInitString( "new DumperOptions()" ); - jClass.addField( factoryField ); - - JConstructor jacksonWriterConstructor = new JConstructor( jClass ); + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.snakeyaml"; + + String marshallerName = getFileName("SnakeYamlWriter"); + + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); + + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + + jClass.addImport("org.yaml.snakeyaml.DumperOptions"); + jClass.addImport("org.yaml.snakeyaml.DumperOptions.Version"); + jClass.addImport("org.yaml.snakeyaml.DumperOptions.FlowStyle"); + jClass.addImport("org.yaml.snakeyaml.DumperOptions.ScalarStyle"); + jClass.addImport("org.yaml.snakeyaml.emitter.Emitable"); + jClass.addImport("org.yaml.snakeyaml.emitter.Emitter"); + jClass.addImport("org.yaml.snakeyaml.error.Mark"); + jClass.addImport("org.yaml.snakeyaml.events.DocumentEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.DocumentStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.ImplicitTuple"); + jClass.addImport("org.yaml.snakeyaml.events.MappingEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.MappingStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.ScalarEvent"); + jClass.addImport("org.yaml.snakeyaml.events.SequenceEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.SequenceStartEvent"); + jClass.addImport("org.yaml.snakeyaml.events.StreamEndEvent"); + jClass.addImport("org.yaml.snakeyaml.events.StreamStartEvent"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.OutputStreamWriter"); + jClass.addImport("java.io.Writer"); + + addModelImports(jClass, null); + + JField factoryField = new JField(new JClass("DumperOptions"), "dumperOptions"); + factoryField.getModifiers().setFinal(true); + factoryField.setInitString("new DumperOptions()"); + jClass.addField(factoryField); + + JConstructor jacksonWriterConstructor = new JConstructor(jClass); JSourceCode sc = jacksonWriterConstructor.getSourceCode(); - sc.add( "dumperOptions.setAllowUnicode( true );" ); - sc.add( "dumperOptions.setPrettyFlow( true );" ); - sc.add( "dumperOptions.setVersion( Version.V1_1 );" ); + sc.add("dumperOptions.setAllowUnicode( true );"); + sc.add("dumperOptions.setPrettyFlow( true );"); + sc.add("dumperOptions.setVersion( Version.V1_1 );"); - jClass.addConstructor( jacksonWriterConstructor ); + jClass.addConstructor(jacksonWriterConstructor); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); // ---------------------------------------------------------------------- // Write the write( Writer, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - String rootElementParameterName = uncapitalise( root ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + String rootElementParameterName = uncapitalise(root); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); sc = marshall.getSourceCode(); - sc.add( "Emitable generator = new Emitter( writer, dumperOptions );" ); + sc.add("Emitable generator = new Emitter( writer, dumperOptions );"); - sc.add( "generator.emit( new StreamStartEvent( null, null ) );" ); + sc.add("generator.emit( new StreamStartEvent( null, null ) );"); - sc.add( "generator.emit( new DocumentStartEvent( null, null, dumperOptions.isExplicitStart(), dumperOptions.getVersion(), dumperOptions.getTags() ) );" ); + sc.add( + "generator.emit( new DocumentStartEvent( null, null, dumperOptions.isExplicitStart(), dumperOptions.getVersion(), dumperOptions.getTags() ) );"); - sc.add( "write" + root + "( " + rootElementParameterName + ", generator );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", generator );"); - sc.add( "generator.emit( new DocumentEndEvent( null, null, dumperOptions.isExplicitEnd() ) );" ); + sc.add("generator.emit( new DocumentEndEvent( null, null, dumperOptions.isExplicitEnd() ) );"); - sc.add( "generator.emit( new StreamEndEvent( null, null ) );" ); + sc.add("generator.emit( new StreamEndEvent( null, null ) );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); sc = marshall.getSourceCode(); - sc.add( "write( new OutputStreamWriter( stream, " - + rootElementParameterName - + ".getModelEncoding() ), " - + rootElementParameterName - + " );" ); + sc.add("write( new OutputStreamWriter( stream, " + + rootElementParameterName + + ".getModelEncoding() ), " + + rootElementParameterName + + " );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "Emitable" ), "generator" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("Emitable"), "generator")); - marshall.addException( new JClass( "IOException" ) ); + marshall.addException(new JClass("IOException")); marshall.getModifiers().makePrivate(); JSourceCode sc = marshall.getSourceCode(); - sc.add( "generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK ) );" ); + sc.add("generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK ) );"); ModelField contentField = null; String contentValue = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // XML attributes - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeScalarKey( sc, fieldTagName ); - writeScalar( sc, getValue( field.getType(), value, xmlFieldMetadata ) ); + writeScalarKey(sc, fieldTagName); + writeScalar(sc, getValue(field.getType(), value, xmlFieldMetadata)); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - } - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - writeScalar( sc, getValue( contentField.getType(), contentValue, xmlFieldMetadata ) ); + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + writeScalar(sc, getValue(contentField.getType(), contentValue, xmlFieldMetadata)); } - final boolean useJava5 = hasJavaSourceSupport( 5 ); + final boolean useJava5 = hasJavaSourceSupport(5); // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // skip field with type Content continue; } - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { continue; } - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeScalarKey( sc, fieldTagName ); - sc.add( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", generator );" ); + writeScalarKey(sc, fieldTagName); + sc.add("write" + association.getTo() + "( (" + association.getTo() + ") " + value + + ", generator );"); sc.unindent(); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); type = association.getType(); String toType = association.getTo(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( getValueChecker( type, value, association ) ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeScalarKey( sc, fieldTagName ); - sc.add( "generator.emit( new SequenceStartEvent( null, null, true, null, null, false ) );" ); + writeScalarKey(sc, fieldTagName); + sc.add("generator.emit( new SequenceStartEvent( null, null, true, null, null, false ) );"); - if ( useJava5 ) - { - sc.add( "for ( " + toType + " o : " + value + " )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + value + ".iterator(); it.hasNext(); )" ); + if (useJava5) { + sc.add("for ( " + toType + " o : " + value + " )"); + } else { + sc.add("for ( java.util.Iterator it = " + value + ".iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( !useJava5 ) - { - sc.add( toType + " o = (" + toType + " ) it.next();" ); + if (!useJava5) { + sc.add(toType + " o = (" + toType + " ) it.next();"); } - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( "write" + toType + "( o, generator );" ); - } - else - { - writeScalar( sc, "o" ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add("write" + toType + "( o, generator );"); + } else { + writeScalar(sc, "o"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "generator.emit( new SequenceEndEvent( null, null ) );" ); + sc.add("generator.emit( new SequenceEndEvent( null, null ) );"); sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeScalarKey( sc, fieldTagName ); + writeScalarKey(sc, fieldTagName); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.emit( new SequenceStartEvent( null, null, true, null, null, false ) );" ); - } - else - { - sc.add( "generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK ) );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("generator.emit( new SequenceStartEvent( null, null, true, null, null, false ) );"); + } else { + sc.add( + "generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK ) );"); } + StringBuilder entryTypeBuilder = new StringBuilder("java.util.Map.Entry"); + if (useJava5) { + entryTypeBuilder.append('<'); - StringBuilder entryTypeBuilder = new StringBuilder( "java.util.Map.Entry" ); - - if ( useJava5 ) - { - entryTypeBuilder.append( '<' ); - - if ( association.getType().equals( ModelDefault.PROPERTIES ) ) - { - entryTypeBuilder.append( "Object, Object" ); - } - else - { - entryTypeBuilder.append( "String, " ).append( association.getTo() ); + if (association.getType().equals(ModelDefault.PROPERTIES)) { + entryTypeBuilder.append("Object, Object"); + } else { + entryTypeBuilder.append("String, ").append(association.getTo()); } - entryTypeBuilder.append( '>' ); + entryTypeBuilder.append('>'); } - if ( useJava5 ) - { - sc.add( "for ( " + entryTypeBuilder + " entry : " + value + ".entrySet() )" ); - } - else - { - sc.add( "for ( java.util.Iterator it = " + value + ".entrySet().iterator(); it.hasNext(); )" ); + if (useJava5) { + sc.add("for ( " + entryTypeBuilder + " entry : " + value + ".entrySet() )"); + } else { + sc.add("for ( java.util.Iterator it = " + value + + ".entrySet().iterator(); it.hasNext(); )"); } - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( !useJava5 ) - { - sc.add( entryTypeBuilder + " entry = (" + entryTypeBuilder + ") it.next();" ); + if (!useJava5) { + sc.add(entryTypeBuilder + " entry = (" + entryTypeBuilder + ") it.next();"); } - sc.add( "final String key = String.valueOf( entry.getKey() );" ); - sc.add( "final String value = String.valueOf( entry.getValue() );" ); - - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK) );" ); - writeScalarKey( sc, "key" ); - writeScalar( sc, "key" ); - writeScalarKey( sc, "value" ); - writeScalar( sc, "value" ); - sc.add( "generator.emit( new MappingEndEvent( null, null ) );" ); - } - else - { - writeScalar( sc, "key" ); - writeScalar( sc, "value" ); + sc.add("final String key = String.valueOf( entry.getKey() );"); + sc.add("final String value = String.valueOf( entry.getValue() );"); + + if (xmlAssociationMetadata.isMapExplode()) { + sc.add( + "generator.emit( new MappingStartEvent( null, null, true, null, null, FlowStyle.BLOCK) );"); + writeScalarKey(sc, "key"); + writeScalar(sc, "key"); + writeScalarKey(sc, "value"); + writeScalar(sc, "value"); + sc.add("generator.emit( new MappingEndEvent( null, null ) );"); + } else { + writeScalar(sc, "key"); + writeScalar(sc, "value"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "generator.emit( new SequenceEndEvent( null, null ) );" ); - } - else - { - sc.add( "generator.emit( new MappingEndEvent( null, null ) );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("generator.emit( new SequenceEndEvent( null, null ) );"); + } else { + sc.add("generator.emit( new MappingEndEvent( null, null ) );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); + } else { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeScalarKey( sc, fieldTagName ); - writeScalar( sc, getValue( field.getType(), value, xmlFieldMetadata ) ); + writeScalarKey(sc, fieldTagName); + writeScalar(sc, getValue(field.getType(), value, xmlFieldMetadata)); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - sc.add( "generator.emit( new MappingEndEvent( null, null ) );" ); + sc.add("generator.emit( new MappingEndEvent( null, null ) );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void writeScalarKey( JSourceCode sc, String key ) - { - writeScalar( sc, "\"" + key + "\"" ); + private void writeScalarKey(JSourceCode sc, String key) { + writeScalar(sc, "\"" + key + "\""); } - private void writeScalar( JSourceCode sc, String value ) - { - sc.add( "{" ); + private void writeScalar(JSourceCode sc, String value) { + sc.add("{"); sc.indent(); - sc.add( "String anchor = null, tag = null;" ); - sc.add( "Mark startMark = null, endMark = null;" ); - sc.add( "ScalarStyle style = ScalarStyle.DOUBLE_QUOTED;" ); - sc.add( "generator.emit( new ScalarEvent( anchor, tag, new ImplicitTuple( true, true ), " + sc.add("String anchor = null, tag = null;"); + sc.add("Mark startMark = null, endMark = null;"); + sc.add("ScalarStyle style = ScalarStyle.DOUBLE_QUOTED;"); + sc.add("generator.emit( new ScalarEvent( anchor, tag, new ImplicitTuple( true, true ), " + value - + ", startMark, endMark, style ) );" ); + + ", startMark, endMark, style ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - } diff --git a/modello-plugins/modello-plugin-stax/pom.xml b/modello-plugins/modello-plugin-stax/pom.xml index 71cd5eaac..bf3ca8c0a 100644 --- a/modello-plugins/modello-plugin-stax/pom.xml +++ b/modello-plugins/modello-plugin-stax/pom.xml @@ -1,18 +1,16 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-stax Modello StAX Plugin - - Modello StAX Plugin generates XML readers and writers based on StAX API, plus reader delegates to be able to read - multiple model versions. - + Modello StAX Plugin generates XML readers and writers based on StAX API, plus reader delegates to be able to read + multiple model versions. diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/AbstractStaxGenerator.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/AbstractStaxGenerator.java index 14cc7a736..22917e03a 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/AbstractStaxGenerator.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/AbstractStaxGenerator.java @@ -22,6 +22,11 @@ * SOFTWARE. */ +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -30,84 +35,62 @@ import org.codehaus.modello.plugins.xml.AbstractXmlJavaGenerator; import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - /** * @author Trygve Laugstøl */ -public abstract class AbstractStaxGenerator - extends AbstractXmlJavaGenerator -{ +public abstract class AbstractStaxGenerator extends AbstractXmlJavaGenerator { private Set parts; - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { - super.initialize( model, parameters ); + protected void initialize(Model model, Properties parameters) throws ModelloException { + super.initialize(model, parameters); parts = null; } - protected ModelField getReferenceIdentifierField( ModelAssociation association ) - throws ModelloException - { + protected ModelField getReferenceIdentifierField(ModelAssociation association) throws ModelloException { XmlAssociationMetadata xmlAssocMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); ModelField referenceIdentifierField = null; - if ( xmlAssocMetadata.isReference() ) - { + if (xmlAssocMetadata.isReference()) { String associationName = association.getName(); ModelClass modelClass = association.getModelClass(); - if ( !isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - throw new ModelloException( "Can't use xml.reference on the '" + associationName + "' association of '" - + modelClass.getName() + "' because the target class '" + association.getTo() - + "' is not in the model" ); + if (!isClassInModel(association.getTo(), modelClass.getModel())) { + throw new ModelloException("Can't use xml.reference on the '" + associationName + "' association of '" + + modelClass.getName() + "' because the target class '" + association.getTo() + + "' is not in the model"); } - List identifierFields = association.getToClass().getIdentifierFields( getGeneratedVersion() ); - if ( identifierFields.size() == 1 ) - { - referenceIdentifierField = identifierFields.get( 0 ); - } - else - { + List identifierFields = association.getToClass().getIdentifierFields(getGeneratedVersion()); + if (identifierFields.size() == 1) { + referenceIdentifierField = identifierFields.get(0); + } else { referenceIdentifierField = new DummyIdModelField(); - referenceIdentifierField.setName( "modello.refid" ); + referenceIdentifierField.setName("modello.refid"); } } return referenceIdentifierField; } - protected boolean isAssociationPartToClass( ModelClass modelClass ) - { - if ( parts == null ) - { + protected boolean isAssociationPartToClass(ModelClass modelClass) { + if (parts == null) { parts = new HashSet(); - for ( ModelClass clazz : modelClass.getModel().getClasses( getGeneratedVersion() ) ) - { - for ( ModelField modelField : clazz.getFields( getGeneratedVersion() ) ) - { - if ( modelField instanceof ModelAssociation ) - { + for (ModelClass clazz : modelClass.getModel().getClasses(getGeneratedVersion())) { + for (ModelField modelField : clazz.getFields(getGeneratedVersion())) { + if (modelField instanceof ModelAssociation) { ModelAssociation assoc = (ModelAssociation) modelField; XmlAssociationMetadata xmlAssocMetadata = - (XmlAssociationMetadata) assoc.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) assoc.getAssociationMetadata(XmlAssociationMetadata.ID); - if ( xmlAssocMetadata.isReference() ) - { - parts.add( assoc.getToClass() ); + if (xmlAssocMetadata.isReference()) { + parts.add(assoc.getToClass()); } } } } } - return parts.contains( modelClass ); + return parts.contains(modelClass); } } diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/DummyIdModelField.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/DummyIdModelField.java index 7cbb421b3..e910127b7 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/DummyIdModelField.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/DummyIdModelField.java @@ -24,11 +24,8 @@ import org.codehaus.modello.model.ModelField; -public class DummyIdModelField - extends ModelField -{ - public String getName() - { +public class DummyIdModelField extends ModelField { + public String getName() { return "modello.refid"; } } diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java index a736ecf6a..eff5e390c 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java @@ -1,13 +1,13 @@ package org.codehaus.modello.plugin.stax; -import org.codehaus.modello.model.ModelAssociation; - import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.codehaus.modello.model.ModelAssociation; + /* * Copyright (c) 2006, Codehaus.org * @@ -30,8 +30,7 @@ * SOFTWARE. */ -class GeneratorNode -{ +class GeneratorNode { private final String to; private boolean referencableChildren; @@ -46,90 +45,73 @@ class GeneratorNode private List chain; - GeneratorNode( String to, GeneratorNode parent ) - { - this( to, parent, null ); + GeneratorNode(String to, GeneratorNode parent) { + this(to, parent, null); } - GeneratorNode( ModelAssociation association, GeneratorNode parent ) - { - this( association.getTo(), parent, association ); + GeneratorNode(ModelAssociation association, GeneratorNode parent) { + this(association.getTo(), parent, association); } - private GeneratorNode( String to, GeneratorNode parent, ModelAssociation association ) - { + private GeneratorNode(String to, GeneratorNode parent, ModelAssociation association) { this.to = to; this.association = association; - this.chain = parent != null ? new ArrayList( parent.getChain() ) : new ArrayList(); - this.chain.add( to ); + this.chain = parent != null ? new ArrayList(parent.getChain()) : new ArrayList(); + this.chain.add(to); } - public boolean isReferencableChildren() - { + public boolean isReferencableChildren() { return referencableChildren; } - public void setReferencableChildren( boolean referencableChildren ) - { + public void setReferencableChildren(boolean referencableChildren) { this.referencableChildren = referencableChildren; } - public void addChild( GeneratorNode child ) - { - children.add( child ); - if ( child.referencableChildren ) - { - nodesWithReferencableChildren.put( child.to, child ); + public void addChild(GeneratorNode child) { + children.add(child); + if (child.referencableChildren) { + nodesWithReferencableChildren.put(child.to, child); } } - public List getChildren() - { + public List getChildren() { return children; } - public String toString() - { + public String toString() { return "to = " + to + "; referencableChildren = " + referencableChildren + "; children = " + children; } - public String getTo() - { + public String getTo() { return to; } - public ModelAssociation getAssociation() - { + public ModelAssociation getAssociation() { return association; } - public void setAssociation( ModelAssociation association ) - { + public void setAssociation(ModelAssociation association) { this.association = association; } - public void setReferencable( boolean referencable ) - { + public void setReferencable(boolean referencable) { this.referencable = referencable; } - public boolean isReferencable() - { + public boolean isReferencable() { return referencable; } - public Map getNodesWithReferencableChildren() - { + public Map getNodesWithReferencableChildren() { return nodesWithReferencableChildren; } - public void addNodesWithReferencableChildren( Map allChildNodes ) - { - this.nodesWithReferencableChildren.putAll( allChildNodes ); + public void addNodesWithReferencableChildren(Map allChildNodes) { + this.nodesWithReferencableChildren.putAll(allChildNodes); } - public List getChain() - { + public List getChain() { return chain; } } diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxReaderGenerator.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxReaderGenerator.java index de79e8d87..cb116ef3b 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxReaderGenerator.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxReaderGenerator.java @@ -22,6 +22,11 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.model.Model; @@ -47,47 +52,33 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - /** * @author Jason van Zyl * @author Emmanuel Venisse */ -@Component( role = ModelloGenerator.class, hint = "stax-reader" ) -public class StaxReaderGenerator - extends AbstractStaxGenerator -{ +@Component(role = ModelloGenerator.class, hint = "stax-reader") +public class StaxReaderGenerator extends AbstractStaxGenerator { private boolean requiresDomSupport; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateStaxReader(); VersionDefinition versionDefinition = model.getVersionDefinition(); - if ( versionDefinition != null ) - { - String versions = parameters.getProperty( ModelloParameterConstants.ALL_VERSIONS ); + if (versionDefinition != null) { + String versions = parameters.getProperty(ModelloParameterConstants.ALL_VERSIONS); - if ( versions != null ) - { - generateStaxReaderDelegate( Arrays.asList( versions.split( "," ) ) ); + if (versions != null) { + generateStaxReaderDelegate(Arrays.asList(versions.split(","))); } } - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating StAX Reader.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating StAX Reader.", ex); } } @@ -98,572 +89,549 @@ public void generate( Model model, Properties parameters ) * @throws ModelloException * @throws IOException */ - private void generateStaxReader() - throws ModelloException, IOException - { + private void generateStaxReader() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.stax"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.stax"; - String unmarshallerName = getFileName( "StaxReader" ); + String unmarshallerName = getFileName("StaxReader"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + unmarshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); - jClass.addImport( "java.io.FileInputStream" ); - jClass.addImport( "java.io.InputStream" ); - jClass.addImport( "java.io.StringWriter" ); - jClass.addImport( "java.io.StringReader" ); - jClass.addImport( "java.io.ByteArrayInputStream" ); - jClass.addImport( "java.io.InputStreamReader" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.text.ParsePosition" ); - jClass.addImport( "java.util.regex.Matcher" ); - jClass.addImport( "java.util.regex.Pattern" ); - jClass.addImport( "java.util.Locale" ); - jClass.addImport( "javax.xml.XMLConstants" ); - jClass.addImport( "javax.xml.stream.*" ); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); + jClass.addImport("java.io.FileInputStream"); + jClass.addImport("java.io.InputStream"); + jClass.addImport("java.io.StringWriter"); + jClass.addImport("java.io.StringReader"); + jClass.addImport("java.io.ByteArrayInputStream"); + jClass.addImport("java.io.InputStreamReader"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.text.ParsePosition"); + jClass.addImport("java.util.regex.Matcher"); + jClass.addImport("java.util.regex.Pattern"); + jClass.addImport("java.util.Locale"); + jClass.addImport("javax.xml.XMLConstants"); + jClass.addImport("javax.xml.stream.*"); - addModelImports( jClass, null ); + addModelImports(jClass, null); // ---------------------------------------------------------------------- // Write reference resolvers. // ---------------------------------------------------------------------- - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); - JClass rootType = new JClass( root.getName() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); + JClass rootType = new JClass(root.getName()); - GeneratorNode rootNode = findRequiredReferenceResolvers( root, null ); + GeneratorNode rootNode = findRequiredReferenceResolvers(root, null); - writeReferenceResolvers( rootNode, jClass ); - for ( GeneratorNode node : rootNode.getNodesWithReferencableChildren().values() ) - { - writeReferenceResolvers( node, jClass ); + writeReferenceResolvers(rootNode, jClass); + for (GeneratorNode node : rootNode.getNodesWithReferencableChildren().values()) { + writeReferenceResolvers(node, jClass); } // ---------------------------------------------------------------------- // Write the class parsers // ---------------------------------------------------------------------- - writeAllClassesParser( objectModel, jClass ); + writeAllClassesParser(objectModel, jClass); // ---------------------------------------------------------------------- // Write helpers // ---------------------------------------------------------------------- - writeHelpers( jClass ); + writeHelpers(jClass); - if ( requiresDomSupport ) - { - writeBuildDomMethod( jClass ); + if (requiresDomSupport) { + writeBuildDomMethod(jClass); } // ---------------------------------------------------------------------- // Write the read(XMLStreamReader,boolean) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod unmarshall = new JMethod( "read", rootType, null ); + JMethod unmarshall = new JMethod("read", rootType, null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); JSourceCode sc = unmarshall.getSourceCode(); - String tagName = resolveTagName( root ); + String tagName = resolveTagName(root); String className = root.getName(); - String variableName = uncapitalise( className ); + String variableName = uncapitalise(className); - if ( requiresDomSupport && !domAsXpp3 ) - { - sc.add( "if ( _doc_ == null )" ); - sc.add( "{" ); + if (requiresDomSupport && !domAsXpp3) { + sc.add("if ( _doc_ == null )"); + sc.add("{"); sc.indent(); - sc.add( "try" ); - sc.add( "{" ); - sc.addIndented( "initDoc();" ); - sc.add( "}" ); - sc.add( "catch ( javax.xml.parsers.ParserConfigurationException pce )" ); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Unable to create DOM document: \" + pce.getMessage(), pce );" ); - sc.add( "}" ); + sc.add("try"); + sc.add("{"); + sc.addIndented("initDoc();"); + sc.add("}"); + sc.add("catch ( javax.xml.parsers.ParserConfigurationException pce )"); + sc.add("{"); + sc.addIndented( + "throw new XMLStreamException( \"Unable to create DOM document: \" + pce.getMessage(), pce );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "int eventType = xmlStreamReader.getEventType();" ); + sc.add("int eventType = xmlStreamReader.getEventType();"); - sc.add( "String encoding = null;" ); + sc.add("String encoding = null;"); - sc.add( "while ( eventType != XMLStreamConstants.END_DOCUMENT )" ); + sc.add("while ( eventType != XMLStreamConstants.END_DOCUMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( eventType == XMLStreamConstants.START_DOCUMENT )" ); - sc.add( "{" ); - sc.addIndented( "encoding = xmlStreamReader.getCharacterEncodingScheme();" ); - sc.add( "}" ); + sc.add("if ( eventType == XMLStreamConstants.START_DOCUMENT )"); + sc.add("{"); + sc.addIndented("encoding = xmlStreamReader.getCharacterEncodingScheme();"); + sc.add("}"); - sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" ); + sc.add("if ( eventType == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict && ! \"" + tagName + "\".equals( xmlStreamReader.getLocalName() ) )" ); + sc.add("if ( strict && ! \"" + tagName + "\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Expected root element '" + tagName + "' but " - + "found '\" + xmlStreamReader.getLocalName() + \"'\", xmlStreamReader.getLocation(), null );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Expected root element '" + tagName + "' but " + + "found '\" + xmlStreamReader.getLocalName() + \"'\", xmlStreamReader.getLocation(), null );"); + sc.add("}"); VersionDefinition versionDefinition = objectModel.getVersionDefinition(); - if ( versionDefinition != null && versionDefinition.isNamespaceType() ) - { - sc.add( "String modelVersion = getVersionFromRootNamespace( xmlStreamReader );" ); + if (versionDefinition != null && versionDefinition.isNamespaceType()) { + sc.add("String modelVersion = getVersionFromRootNamespace( xmlStreamReader );"); - writeModelVersionCheck( sc ); + writeModelVersionCheck(sc); } - sc.add( className + ' ' + variableName + " = parse" + root.getName() + "( xmlStreamReader, strict );" ); + sc.add(className + ' ' + variableName + " = parse" + root.getName() + "( xmlStreamReader, strict );"); - sc.add( variableName + ".setModelEncoding( encoding );" ); + sc.add(variableName + ".setModelEncoding( encoding );"); - sc.add( "resolveReferences( " + variableName + " );" ); + sc.add("resolveReferences( " + variableName + " );"); - sc.add( "return " + variableName + ';' ); + sc.add("return " + variableName + ';'); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "eventType = xmlStreamReader.next();" ); + sc.add("eventType = xmlStreamReader.next();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "throw new XMLStreamException( \"Expected root element '" + tagName + "' but " - + "found no element at all: invalid XML document\", xmlStreamReader.getLocation(), null );" ); + sc.add("throw new XMLStreamException( \"Expected root element '" + tagName + "' but " + + "found no element at all: invalid XML document\", xmlStreamReader.getLocation(), null );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(Reader[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( reader );" ); + sc.add("XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( reader );"); - sc.add( "" ); + sc.add(""); - sc.add( "return read( xmlStreamReader, strict );" ); + sc.add("return read( xmlStreamReader, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( reader, true );" ); + sc.add("return read( reader, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(InputStream[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "stream" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "stream")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( stream );" ); + sc.add("XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( stream );"); - sc.add( "" ); + sc.add(""); - sc.add( "return read( xmlStreamReader, strict );" ); + sc.add("return read( xmlStreamReader, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "stream" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "stream")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( stream, true );" ); + sc.add("return read( stream, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(String[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "String" ), "filePath" ) ); + unmarshall.addParameter(new JParameter(new JClass("String"), "filePath")); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "java.io.File file = new java.io.File( filePath );" ); + sc.add("java.io.File file = new java.io.File( filePath );"); - sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( " - + "file.toURI().toURL().toExternalForm(), new FileInputStream( file ) );" ); + sc.add("XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( " + + "file.toURI().toURL().toExternalForm(), new FileInputStream( file ) );"); - sc.add( "" ); + sc.add(""); - sc.add( "return read( xmlStreamReader, strict );" ); + sc.add("return read( xmlStreamReader, strict );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - unmarshall = new JMethod( "read", rootType, null ); + unmarshall = new JMethod("read", rootType, null); - unmarshall.addParameter( new JParameter( new JClass( "String" ), "filePath" ) ); + unmarshall.addParameter(new JParameter(new JClass("String"), "filePath")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); sc = unmarshall.getSourceCode(); - sc.add( "return read( filePath, true );" ); + sc.add("return read( filePath, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // Determine the version. Currently, it causes the document to be reparsed, but could be made more efficient in // future by buffering the read XML and piping that into any consequent read method. - if ( versionDefinition != null ) - { - writeDetermineVersionMethod( jClass, objectModel ); + if (versionDefinition != null) { + writeDetermineVersionMethod(jClass, objectModel); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void generateStaxReaderDelegate( List versions ) - throws ModelloException, IOException - { + private void generateStaxReaderDelegate(List versions) throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( false, null ) + ".io.stax"; + String packageName = objectModel.getDefaultPackageName(false, null) + ".io.stax"; - String unmarshallerName = getFileName( "StaxReaderDelegate" ); + String unmarshallerName = getFileName("StaxReaderDelegate"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); + JClass jClass = new JClass(packageName + '.' + unmarshallerName); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); - jClass.addImport( "javax.xml.stream.*" ); + jClass.addImport("javax.xml.stream.*"); - jClass.addImport( "org.codehaus.plexus.util.IOUtil" ); - jClass.addImport( "org.codehaus.plexus.util.ReaderFactory" ); + jClass.addImport("org.codehaus.plexus.util.IOUtil"); + jClass.addImport("org.codehaus.plexus.util.ReaderFactory"); - JMethod method = new JMethod( "read", new JClass( "Object" ), null ); + JMethod method = new JMethod("read", new JClass("Object"), null); - method.addParameter( new JParameter( new JClass( "java.io.File" ), "f" ) ); + method.addParameter(new JParameter(new JClass("java.io.File"), "f")); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); - method.addException( new JClass( "IOException" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addException(new JClass("IOException")); + method.addException(new JClass("XMLStreamException")); - jClass.addMethod( method ); + jClass.addMethod(method); JSourceCode sc = method.getSourceCode(); - sc.add( "String modelVersion;" ); - sc.add( "Reader reader = ReaderFactory.newXmlReader( f );" ); - - sc.add( "try" ); - sc.add( "{" ); - sc.addIndented( "modelVersion = determineVersion( reader );" ); - sc.add( "}" ); - sc.add( "finally" ); - sc.add( "{" ); - sc.addIndented( "IOUtil.close( reader );" ); - sc.add( "}" ); - - sc.add( "reader = ReaderFactory.newXmlReader( f );" ); - sc.add( "try" ); - sc.add( "{" ); + sc.add("String modelVersion;"); + sc.add("Reader reader = ReaderFactory.newXmlReader( f );"); + + sc.add("try"); + sc.add("{"); + sc.addIndented("modelVersion = determineVersion( reader );"); + sc.add("}"); + sc.add("finally"); + sc.add("{"); + sc.addIndented("IOUtil.close( reader );"); + sc.add("}"); + + sc.add("reader = ReaderFactory.newXmlReader( f );"); + sc.add("try"); + sc.add("{"); sc.indent(); - writeModelVersionHack( sc ); + writeModelVersionHack(sc); String prefix = ""; - for ( String version : versions ) - { - sc.add( prefix + "if ( \"" + version + "\".equals( modelVersion ) )" ); - sc.add( "{" ); - sc.addIndented( "return new " + getModel().getDefaultPackageName( true, new Version( version ) ) - + ".io.stax." + getFileName( "StaxReader" ) + "().read( reader, strict );" ); - sc.add( "}" ); + for (String version : versions) { + sc.add(prefix + "if ( \"" + version + "\".equals( modelVersion ) )"); + sc.add("{"); + sc.addIndented("return new " + getModel().getDefaultPackageName(true, new Version(version)) + ".io.stax." + + getFileName("StaxReader") + "().read( reader, strict );"); + sc.add("}"); prefix = "else "; } - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Document version '\" + modelVersion + \"' has no " - + "corresponding reader.\" );" ); - sc.add( "}" ); + sc.add("else"); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Document version '\" + modelVersion + \"' has no " + + "corresponding reader.\" );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "finally" ); - sc.add( "{" ); - sc.addIndented( "IOUtil.close( reader );" ); - sc.add( "}" ); + sc.add("}"); + sc.add("finally"); + sc.add("{"); + sc.addIndented("IOUtil.close( reader );"); + sc.add("}"); // ---------------------------------------------------------------------- - method = new JMethod( "read", new JClass( "Object" ), null ); + method = new JMethod("read", new JClass("Object"), null); - method.addParameter( new JParameter( new JClass( "java.io.File" ), "f" ) ); + method.addParameter(new JParameter(new JClass("java.io.File"), "f")); - method.addException( new JClass( "IOException" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addException(new JClass("IOException")); + method.addException(new JClass("XMLStreamException")); sc = method.getSourceCode(); - sc.add( "return read( f, true );" ); + sc.add("return read( f, true );"); - jClass.addMethod( method ); + jClass.addMethod(method); - writeDetermineVersionMethod( jClass, objectModel ); + writeDetermineVersionMethod(jClass, objectModel); - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private static void writeModelVersionHack( JSourceCode sc ) - { - sc.add( "// legacy hack for pomVersion == 3" ); - sc.add( "if ( \"3\".equals( modelVersion ) )" ); - sc.add( "{" ); - sc.addIndented( "modelVersion = \"3.0.0\";" ); - sc.add( "}" ); + private static void writeModelVersionHack(JSourceCode sc) { + sc.add("// legacy hack for pomVersion == 3"); + sc.add("if ( \"3\".equals( modelVersion ) )"); + sc.add("{"); + sc.addIndented("modelVersion = \"3.0.0\";"); + sc.add("}"); } - private void writeDetermineVersionMethod( JClass jClass, Model objectModel ) - throws ModelloException - { + private void writeDetermineVersionMethod(JClass jClass, Model objectModel) throws ModelloException { VersionDefinition versionDefinition = objectModel.getVersionDefinition(); - JMethod method = new JMethod( "determineVersion", new JClass( "String" ), null ); + JMethod method = new JMethod("determineVersion", new JClass("String"), null); - method.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + method.addParameter(new JParameter(new JClass("Reader"), "reader")); - method.addException( new JClass( "IOException" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addException(new JClass("IOException")); + method.addException(new JClass("XMLStreamException")); JSourceCode sc = method.getSourceCode(); - sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( reader );" ); + sc.add("XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( reader );"); - sc.add( "while ( xmlStreamReader.hasNext() )" ); + sc.add("while ( xmlStreamReader.hasNext() )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "int eventType = xmlStreamReader.next();" ); + sc.add("int eventType = xmlStreamReader.next();"); - sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" ); + sc.add("if ( eventType == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( versionDefinition.isNamespaceType() ) - { - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) objectModel.getMetadata( XmlModelMetadata.ID ); + if (versionDefinition.isNamespaceType()) { + XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) objectModel.getMetadata(XmlModelMetadata.ID); String namespace = xmlModelMetadata.getNamespace(); - if ( namespace == null || !namespace.contains( "${version}" ) ) - { - throw new ModelloException( "versionDefinition is namespace, but the model does not declare " - + "xml.namespace on the model element" ); + if (namespace == null || !namespace.contains("${version}")) { + throw new ModelloException("versionDefinition is namespace, but the model does not declare " + + "xml.namespace on the model element"); } - sc.add( "return getVersionFromRootNamespace( xmlStreamReader );" ); + sc.add("return getVersionFromRootNamespace( xmlStreamReader );"); - writeNamespaceVersionGetMethod( namespace, jClass ); - } - else - { + writeNamespaceVersionGetMethod(namespace, jClass); + } else { String value = versionDefinition.getValue(); - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), - getGeneratedVersion() ); - ModelField field = root.getField( value, getGeneratedVersion() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); + ModelField field = root.getField(value, getGeneratedVersion()); - if ( field == null ) - { - throw new ModelloException( "versionDefinition is field, but the model root element does not declare a " - + "field '" + value + "'." ); + if (field == null) { + throw new ModelloException("versionDefinition is field, but the model root element does not declare a " + + "field '" + value + "'."); } - if ( !"String".equals( field.getType() ) ) - { - throw new ModelloException( "versionDefinition is field, but the field is not of type String" ); + if (!"String".equals(field.getType())) { + throw new ModelloException("versionDefinition is field, but the field is not of type String"); } - sc.add( "return getVersionFromField( xmlStreamReader );" ); + sc.add("return getVersionFromField( xmlStreamReader );"); - writeFieldVersionGetMethod( field, jClass ); + writeFieldVersionGetMethod(field, jClass); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "throw new XMLStreamException( \"Version not found in document\", xmlStreamReader.getLocation() );" ); + sc.add("throw new XMLStreamException( \"Version not found in document\", xmlStreamReader.getLocation() );"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private static void writeFieldVersionGetMethod( ModelField field, JClass jClass ) - { - JMethod method = new JMethod( "getVersionFromField", new JType( "String" ), null ); + private static void writeFieldVersionGetMethod(ModelField field, JClass jClass) { + JMethod method = new JMethod("getVersionFromField", new JType("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addException( new JClass( "XMLStreamException" ) ); - jClass.addMethod( method ); + method.addParameter(new JParameter(new JType("XMLStreamReader"), "xmlStreamReader")); + method.addException(new JClass("XMLStreamException")); + jClass.addMethod(method); JSourceCode sc = method.getSourceCode(); - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); String value = xmlFieldMetadata.getTagName(); - if ( value == null ) - { + if (value == null) { value = field.getName(); } // we are now at the root element. Search child elements for the correct tag name - sc.add( "int depth = 0;" ); + sc.add("int depth = 0;"); - sc.add( "while ( depth >= 0 )" ); + sc.add("while ( depth >= 0 )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "int eventType = xmlStreamReader.next();" ); + sc.add("int eventType = xmlStreamReader.next();"); - sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" ); - sc.add( "{" ); + sc.add("if ( eventType == XMLStreamConstants.START_ELEMENT )"); + sc.add("{"); sc.indent(); - sc.add( "if ( depth == 0 && \"" + value + "\".equals( xmlStreamReader.getLocalName() ) )" ); - sc.add( "{" ); - sc.addIndented( "return xmlStreamReader.getElementText();" ); - sc.add( "}" ); - - if ( field.getAlias() != null ) - { - sc.add( "if ( depth == 0 && \"" + field.getAlias() + "\".equals( xmlStreamReader.getLocalName() ) )" ); - sc.add( "{" ); - sc.addIndented( "return xmlStreamReader.getElementText();" ); - sc.add( "}" ); + sc.add("if ( depth == 0 && \"" + value + "\".equals( xmlStreamReader.getLocalName() ) )"); + sc.add("{"); + sc.addIndented("return xmlStreamReader.getElementText();"); + sc.add("}"); + + if (field.getAlias() != null) { + sc.add("if ( depth == 0 && \"" + field.getAlias() + "\".equals( xmlStreamReader.getLocalName() ) )"); + sc.add("{"); + sc.addIndented("return xmlStreamReader.getElementText();"); + sc.add("}"); } - sc.add( "depth++;" ); + sc.add("depth++;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "if ( eventType == XMLStreamConstants.END_ELEMENT )" ); - sc.add( "{" ); - sc.addIndented( "depth--;" ); - sc.add( "}" ); + sc.add("if ( eventType == XMLStreamConstants.END_ELEMENT )"); + sc.add("{"); + sc.addIndented("depth--;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "throw new XMLStreamException( \"Field: '" + value - + "' does not exist in the document.\", xmlStreamReader.getLocation() );" ); + sc.add("throw new XMLStreamException( \"Field: '" + value + + "' does not exist in the document.\", xmlStreamReader.getLocation() );"); } - private static void writeNamespaceVersionGetMethod( String namespace, JClass jClass ) - { - JMethod method = new JMethod( "getVersionFromRootNamespace", new JType( "String" ), null ); + private static void writeNamespaceVersionGetMethod(String namespace, JClass jClass) { + JMethod method = new JMethod("getVersionFromRootNamespace", new JType("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addException( new JClass( "XMLStreamException" ) ); - jClass.addMethod( method ); + method.addParameter(new JParameter(new JType("XMLStreamReader"), "xmlStreamReader")); + method.addException(new JClass("XMLStreamException")); + jClass.addMethod(method); JSourceCode sc = method.getSourceCode(); - sc.add( "String uri = xmlStreamReader.getNamespaceURI( \"\" );" ); + sc.add("String uri = xmlStreamReader.getNamespaceURI( \"\" );"); - sc.add( "if ( uri == null )" ); + sc.add("if ( uri == null )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"No namespace specified, but versionDefinition requires it\", " - + "xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"No namespace specified, but versionDefinition requires it\", " + + "xmlStreamReader.getLocation() );"); + sc.add("}"); - int index = namespace.indexOf( "${version}" ); + int index = namespace.indexOf("${version}"); - sc.add( "String uriPrefix = \"" + namespace.substring( 0, index ) + "\";" ); - sc.add( "String uriSuffix = \"" + namespace.substring( index + 10 ) + "\";" ); + sc.add("String uriPrefix = \"" + namespace.substring(0, index) + "\";"); + sc.add("String uriSuffix = \"" + namespace.substring(index + 10) + "\";"); - sc.add( "if ( !uri.startsWith( uriPrefix ) || !uri.endsWith( uriSuffix ) )" ); + sc.add("if ( !uri.startsWith( uriPrefix ) || !uri.endsWith( uriSuffix ) )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Namespace URI: '\" + uri + \"' does not match pattern '" - + namespace + "'\", xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Namespace URI: '\" + uri + \"' does not match pattern '" + + namespace + "'\", xmlStreamReader.getLocation() );"); + sc.add("}"); - sc.add( "return uri.substring( uriPrefix.length(), uri.length() - uriSuffix.length() );" ); + sc.add("return uri.substring( uriPrefix.length(), uri.length() - uriSuffix.length() );"); } /** @@ -674,14 +642,11 @@ private static void writeNamespaceVersionGetMethod( String namespace, JClass jCl * @throws ModelloException * @see {@link #writeClassParser(ModelClass, JClass, boolean)} */ - private void writeAllClassesParser( Model objectModel, JClass jClass ) - throws ModelloException - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); - - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) ); + private void writeAllClassesParser(Model objectModel, JClass jClass) throws ModelloException { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); + + for (ModelClass clazz : getClasses(objectModel)) { + writeClassParser(clazz, jClass, root.getName().equals(clazz.getName())); } } @@ -693,285 +658,255 @@ private void writeAllClassesParser( Model objectModel, JClass jClass ) * @param rootElement is this class the root from the model? * @throws ModelloException */ - private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement ) - throws ModelloException - { + private void writeClassParser(ModelClass modelClass, JClass jClass, boolean rootElement) throws ModelloException { String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null ); + JMethod unmarshall = new JMethod("parse" + capClassName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + unmarshall.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + unmarshall.addParameter(new JParameter(JType.BOOLEAN, "strict")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XMLStreamException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XMLStreamException")); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( className + ' ' + uncapClassName + " = new " + className + "();" ); + sc.add(className + ' ' + uncapClassName + " = new " + className + "();"); - ModelField contentField = getContentField( modelClass.getAllFields( getGeneratedVersion(), true ) ); + ModelField contentField = getContentField(modelClass.getAllFields(getGeneratedVersion(), true)); - if ( contentField != null ) - { - writeAttributes( modelClass, uncapClassName, sc ); + if (contentField != null) { + writeAttributes(modelClass, uncapClassName, sc); - writePrimitiveField( contentField, contentField.getType(), uncapClassName, - "set" + capitalise( contentField.getName() ), sc ); - } - else - { - sc.add( "java.util.Set parsed = new java.util.HashSet();" ); + writePrimitiveField( + contentField, + contentField.getType(), + uncapClassName, + "set" + capitalise(contentField.getName()), + sc); + } else { + sc.add("java.util.Set parsed = new java.util.HashSet();"); - String instanceFieldName = getInstanceFieldName( className ); + String instanceFieldName = getInstanceFieldName(className); - writeAttributes( modelClass, uncapClassName, sc ); + writeAttributes(modelClass, uncapClassName, sc); - if ( isAssociationPartToClass( modelClass ) ) - { - jClass.addField( new JField( new JType( "java.util.Map" ), instanceFieldName ) ); + if (isAssociationPartToClass(modelClass)) { + jClass.addField(new JField(new JType("java.util.Map"), instanceFieldName)); - sc.add( "if ( " + instanceFieldName + " == null )" ); - sc.add( "{" ); - sc.addIndented( instanceFieldName + " = new java.util.HashMap();" ); - sc.add( "}" ); + sc.add("if ( " + instanceFieldName + " == null )"); + sc.add("{"); + sc.addIndented(instanceFieldName + " = new java.util.HashMap();"); + sc.add("}"); - sc.add( "String v = xmlStreamReader.getAttributeValue( null, \"modello.id\" );" ); - sc.add( "if ( v != null )" ); - sc.add( "{" ); - sc.addIndented( instanceFieldName + ".put( v, " + uncapClassName + " );" ); - sc.add( "}" ); + sc.add("String v = xmlStreamReader.getAttributeValue( null, \"modello.id\" );"); + sc.add("if ( v != null )"); + sc.add("{"); + sc.addIndented(instanceFieldName + ".put( v, " + uncapClassName + " );"); + sc.add("}"); } - sc.add( "while ( ( strict ? xmlStreamReader.nextTag() : nextTag( xmlStreamReader ) ) == XMLStreamConstants.START_ELEMENT )" ); + sc.add( + "while ( ( strict ? xmlStreamReader.nextTag() : nextTag( xmlStreamReader ) ) == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); boolean addElse = false; // Write other fields - for ( ModelField field : modelClass.getAllFields( getGeneratedVersion(), true ) ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelClass.getAllFields(getGeneratedVersion(), true)) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( !xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient() ) - { - processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, rootElement, jClass ); + if (!xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient()) { + processField(field, xmlFieldMetadata, addElse, sc, uncapClassName, rootElement, jClass); addElse = true; } } /* - if ( modelClass.getFields( getGeneratedVersion() ).size() > 0 ) - { - sc.add( "else" ); + if ( modelClass.getFields( getGeneratedVersion() ).size() > 0 ) + { + sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "parser.nextText();" ); - sc.add( "}" ); - } -*/ + sc.add( "{" ); + sc.addIndented( "parser.nextText();" ); + sc.add( "}" ); + } + */ - if ( addElse ) - { - sc.add( "else" ); + if (addElse) { + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.indent(); } - sc.add( "checkUnknownElement( xmlStreamReader, strict );" ); + sc.add("checkUnknownElement( xmlStreamReader, strict );"); - if ( addElse ) - { + if (addElse) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); // This must be last so that we guarantee the ID has been filled already - if ( isAssociationPartToClass( modelClass ) ) - { - List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() ); + if (isAssociationPartToClass(modelClass)) { + List identifierFields = modelClass.getIdentifierFields(getGeneratedVersion()); - if ( identifierFields.size() == 1 ) - { - ModelField field = (ModelField) identifierFields.get( 0 ); + if (identifierFields.size() == 1) { + ModelField field = (ModelField) identifierFields.get(0); - String v = uncapClassName + ".get" + capitalise( field.getName() ) + "()"; - v = getValue( field.getType(), v, (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ) ); - sc.add( instanceFieldName + ".put( " + v + ", " + uncapClassName + " );" ); + String v = uncapClassName + ".get" + capitalise(field.getName()) + "()"; + v = getValue(field.getType(), v, (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID)); + sc.add(instanceFieldName + ".put( " + v + ", " + uncapClassName + " );"); } } } - sc.add( "return " + uncapClassName + ";" ); + sc.add("return " + uncapClassName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } - private GeneratorNode findRequiredReferenceResolvers( ModelClass modelClass, GeneratorNode parent ) - throws ModelloException - { + private GeneratorNode findRequiredReferenceResolvers(ModelClass modelClass, GeneratorNode parent) + throws ModelloException { String className = modelClass.getName(); - GeneratorNode value = new GeneratorNode( className, parent ); + GeneratorNode value = new GeneratorNode(className, parent); - for ( ModelField field : modelClass.getAllFields( getGeneratedVersion(), true ) ) - { - if ( field instanceof ModelAssociation ) - { + for (ModelField field : modelClass.getAllFields(getGeneratedVersion(), true)) { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; - if ( isClassInModel( association.getTo(), getModel() ) ) - { - ModelField referenceIdentifierField = getReferenceIdentifierField( association ); + if (isClassInModel(association.getTo(), getModel())) { + ModelField referenceIdentifierField = getReferenceIdentifierField(association); GeneratorNode child = null; - if ( referenceIdentifierField != null ) - { - child = new GeneratorNode( association, parent ); - child.setReferencable( true ); - } - else - { - if ( !value.getChain().contains( association.getTo() ) ) - { + if (referenceIdentifierField != null) { + child = new GeneratorNode(association, parent); + child.setReferencable(true); + } else { + if (!value.getChain().contains(association.getTo())) { // descend into child - child = findRequiredReferenceResolvers( association.getToClass(), value ); - child.setAssociation( association ); + child = findRequiredReferenceResolvers(association.getToClass(), value); + child.setAssociation(association); } } - if ( child != null ) - { - value.addChild( child ); + if (child != null) { + value.addChild(child); } } } } // propagate the flag up - for ( GeneratorNode child : value.getChildren() ) - { - if ( child.isReferencable() || child.isReferencableChildren() ) - { - value.setReferencableChildren( true ); + for (GeneratorNode child : value.getChildren()) { + if (child.isReferencable() || child.isReferencableChildren()) { + value.setReferencableChildren(true); } - value.addNodesWithReferencableChildren( child.getNodesWithReferencableChildren() ); + value.addNodesWithReferencableChildren(child.getNodesWithReferencableChildren()); } return value; } - private void writeReferenceResolvers( GeneratorNode node, JClass jClass ) - { - JMethod unmarshall = new JMethod( "resolveReferences" ); + private void writeReferenceResolvers(GeneratorNode node, JClass jClass) { + JMethod unmarshall = new JMethod("resolveReferences"); - unmarshall.addParameter( new JParameter( new JClass( node.getTo() ), "value" ) ); + unmarshall.addParameter(new JParameter(new JClass(node.getTo()), "value")); unmarshall.getModifiers().makePrivate(); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( "java.util.Map refs;" ); + sc.add("java.util.Map refs;"); - for ( GeneratorNode child : node.getChildren() ) - { - if ( child.isReferencable() ) - { + for (GeneratorNode child : node.getChildren()) { + if (child.isReferencable()) { ModelAssociation association = child.getAssociation(); - String refFieldName = getRefFieldName( association ); + String refFieldName = getRefFieldName(association); String to = association.getTo(); - String instanceFieldName = getInstanceFieldName( to ); + String instanceFieldName = getInstanceFieldName(to); - sc.add( "if ( " + refFieldName + " != null )" ); - sc.add( "{" ); + sc.add("if ( " + refFieldName + " != null )"); + sc.add("{"); sc.indent(); - sc.add( "refs = (java.util.Map) " + refFieldName + ".get( value );" ); + sc.add("refs = (java.util.Map) " + refFieldName + ".get( value );"); - sc.add( "if ( refs != null )" ); - sc.add( "{" ); + sc.add("if ( refs != null )"); + sc.add("{"); sc.indent(); - String capAssocName = capitalise( association.getName() ); - if ( association.isOneMultiplicity() ) - { - sc.add( "String id = (String) refs.get( \"" + association.getName() + "\" );" ); - sc.add( to + " ref = (" + to + ") " + instanceFieldName + ".get( id );" ); + String capAssocName = capitalise(association.getName()); + if (association.isOneMultiplicity()) { + sc.add("String id = (String) refs.get( \"" + association.getName() + "\" );"); + sc.add(to + " ref = (" + to + ") " + instanceFieldName + ".get( id );"); // Don't set if it already is, since the Java plugin generates create/break that will throw an // exception - sc.add( "if ( ref != null && !ref.equals( value.get" + capAssocName + "() ) )" ); - sc.add( "{" ); - sc.addIndented( "value.set" + capAssocName + "( ref );" ); - sc.add( "}" ); - } - else - { - sc.add( "for ( int i = 0; i < value.get" + capAssocName + "().size(); i++ )" ); - sc.add( "{" ); + sc.add("if ( ref != null && !ref.equals( value.get" + capAssocName + "() ) )"); + sc.add("{"); + sc.addIndented("value.set" + capAssocName + "( ref );"); + sc.add("}"); + } else { + sc.add("for ( int i = 0; i < value.get" + capAssocName + "().size(); i++ )"); + sc.add("{"); sc.indent(); - sc.add( "String id = (String) refs.get( \"" + association.getName() + ".\" + i );" ); - sc.add( to + " ref = (" + to + ") " + instanceFieldName + ".get( id );" ); - sc.add( "if ( ref != null )" ); - sc.add( "{" ); - sc.addIndented( "value.get" + capAssocName + "().set( i, ref );" ); - sc.add( "}" ); + sc.add("String id = (String) refs.get( \"" + association.getName() + ".\" + i );"); + sc.add(to + " ref = (" + to + ") " + instanceFieldName + ".get( id );"); + sc.add("if ( ref != null )"); + sc.add("{"); + sc.addIndented("value.get" + capAssocName + "().set( i, ref );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - if ( child.isReferencableChildren() ) - { + if (child.isReferencableChildren()) { ModelAssociation association = child.getAssociation(); - if ( association.isOneMultiplicity() ) - { - sc.add( "resolveReferences( value.get" + capitalise( association.getName() ) + "() );" ); - } - else - { - sc.add( "for ( java.util.Iterator i = value.get" + capitalise( association.getName() ) - + "().iterator(); i.hasNext(); )" ); - sc.add( "{" ); - sc.addIndented( "resolveReferences( (" + association.getTo() + ") i.next() );" ); - sc.add( "}" ); + if (association.isOneMultiplicity()) { + sc.add("resolveReferences( value.get" + capitalise(association.getName()) + "() );"); + } else { + sc.add("for ( java.util.Iterator i = value.get" + capitalise(association.getName()) + + "().iterator(); i.hasNext(); )"); + sc.add("{"); + sc.addIndented("resolveReferences( (" + association.getTo() + ") i.next() );"); + sc.add("}"); } } } - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } - private static String getRefFieldName( ModelAssociation association ) - { - return uncapitalise( association.getTo() ) + "References"; + private static String getRefFieldName(ModelAssociation association) { + return uncapitalise(association.getTo()) + "References"; } - private static String getInstanceFieldName( String to ) - { - return uncapitalise( to ) + "Instances"; + private static String getInstanceFieldName(String to) { + return uncapitalise(to) + "Instances"; } /** @@ -982,17 +917,12 @@ private static String getInstanceFieldName( String to ) * @param sc the source code to add to * @throws ModelloException */ - private void writeAttributes( ModelClass modelClass, String uncapClassName, JSourceCode sc ) - throws ModelloException - { - for ( ModelField field : modelClass.getAllFields( getGeneratedVersion(), true ) ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); - - if ( xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient() ) - { - writePrimitiveField( field, field.getType(), uncapClassName, "set" + capitalise( field.getName() ), - sc ); + private void writeAttributes(ModelClass modelClass, String uncapClassName, JSourceCode sc) throws ModelloException { + for (ModelField field : modelClass.getAllFields(getGeneratedVersion(), true)) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); + + if (xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient()) { + writePrimitiveField(field, field.getType(), uncapClassName, "set" + capitalise(field.getName()), sc); } } } @@ -1009,364 +939,333 @@ private void writeAttributes( ModelClass modelClass, String uncapClassName, JSou * @param jClass the generated class source file * @throws ModelloException */ - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc, - String objectName, boolean rootElement, JClass jClass ) - throws ModelloException - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + boolean addElse, + JSourceCode sc, + String objectName, + boolean rootElement, + JClass jClass) + throws ModelloException { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String capFieldName = capitalise( field.getName() ); + String capFieldName = capitalise(field.getName()); - String singularName = singular( field.getName() ); + String singularName = singular(field.getName()); String alias; - if ( StringUtils.isEmpty( field.getAlias() ) ) - { + if (StringUtils.isEmpty(field.getAlias())) { alias = "null"; - } - else - { + } else { alias = "\"" + field.getAlias() + "\""; } - String tagComparison = ( addElse ? "else " : "" ) - + "if ( checkFieldWithDuplicate( xmlStreamReader, \"" + fieldTagName + "\", " + alias + ", parsed ) )"; + String tagComparison = (addElse ? "else " : "") + "if ( checkFieldWithDuplicate( xmlStreamReader, \"" + + fieldTagName + "\", " + alias + ", parsed ) )"; - if ( !( field instanceof ModelAssociation ) ) - { - sc.add( tagComparison ); + if (!(field instanceof ModelAssociation)) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - //ModelField - writePrimitiveField( field, field.getType(), objectName, "set" + capFieldName, sc ); + // ModelField + writePrimitiveField(field, field.getType(), objectName, "set" + capFieldName, sc); - if ( rootElement && field.isModelVersionField() ) - { - sc.add( "String modelVersion = " + objectName + ".get" + capFieldName + "();" ); + if (rootElement && field.isModelVersionField()) { + sc.add("String modelVersion = " + objectName + ".get" + capFieldName + "();"); - writeModelVersionCheck( sc ); + writeModelVersionCheck(sc); } sc.unindent(); - sc.add( "}" ); - } - else - { // model association + sc.add("}"); + } else { // model association ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( tagComparison ); + if (association.isOneMultiplicity()) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - ModelField referenceIdentifierField = getReferenceIdentifierField( association ); + ModelField referenceIdentifierField = getReferenceIdentifierField(association); - if ( referenceIdentifierField != null ) - { - addCodeToAddReferences( association, jClass, sc, referenceIdentifierField, objectName ); + if (referenceIdentifierField != null) { + addCodeToAddReferences(association, jClass, sc, referenceIdentifierField, objectName); // gobble the rest of the tag - sc.add( "while ( xmlStreamReader.getEventType() != XMLStreamConstants.END_ELEMENT )" ); - sc.add( "{" ); - sc.addIndented( "xmlStreamReader.next();" ); - sc.add( "}" ); - } - else - { - sc.add( objectName + ".set" + capFieldName + "( parse" + association.getTo() - + "( xmlStreamReader, strict ) );" ); + sc.add("while ( xmlStreamReader.getEventType() != XMLStreamConstants.END_ELEMENT )"); + sc.add("{"); + sc.addIndented("xmlStreamReader.next();"); + sc.add("}"); + } else { + sc.add(objectName + ".set" + capFieldName + "( parse" + association.getTo() + + "( xmlStreamReader, strict ) );"); } sc.unindent(); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); String type = association.getType(); boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) association.getMetadata( JavaFieldMetadata.ID ); - JavaAssociationMetadata javaAssociationMetadata = (JavaAssociationMetadata) association.getAssociationMetadata( JavaAssociationMetadata.ID ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) association.getMetadata(JavaFieldMetadata.ID); + JavaAssociationMetadata javaAssociationMetadata = + (JavaAssociationMetadata) association.getAssociationMetadata(JavaAssociationMetadata.ID); String adder; - if ( wrappedItems ) - { - sc.add( tagComparison ); + if (wrappedItems) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( javaFieldMetadata.isSetter() ) - { - sc.add( type + " " + associationName + " = " + association.getDefaultValue() + ";" ); + if (javaFieldMetadata.isSetter()) { + sc.add(type + " " + associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } - sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" ); + sc.add("while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"" + valuesTagName + "\".equals( xmlStreamReader.getLocalName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - } - else - { - sc.add( ( addElse ? "else " : "" ) - + "if ( \"" + valuesTagName + "\".equals( xmlStreamReader.getLocalName() ) )" ); + } else { + sc.add((addElse ? "else " : "") + "if ( \"" + valuesTagName + + "\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter() ) - { - sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" ); + if (javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter()) { + sc.add(type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();"); - sc.add( "if ( " + associationName + " == null )" ); + sc.add("if ( " + associationName + " == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( associationName + " = " + association.getDefaultValue() + ";" ); + sc.add(associationName + " = " + association.getDefaultValue() + ";"); - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } } - if ( isClassInModel( association.getTo(), field.getModelClass().getModel() ) ) - { - ModelField referenceIdentifierField = getReferenceIdentifierField( association ); + if (isClassInModel( + association.getTo(), field.getModelClass().getModel())) { + ModelField referenceIdentifierField = getReferenceIdentifierField(association); - if ( referenceIdentifierField != null ) - { - addCodeToAddReferences( association, jClass, sc, referenceIdentifierField, objectName ); + if (referenceIdentifierField != null) { + addCodeToAddReferences(association, jClass, sc, referenceIdentifierField, objectName); } - if ( association.getTo().equals( field.getModelClass().getName() ) || !javaAssociationMetadata.isAdder() ) - { + if (association.getTo().equals(field.getModelClass().getName()) + || !javaAssociationMetadata.isAdder()) { // HACK: the addXXX method will cause an OOME when compiling a self-referencing class, so we // just add it to the array. This could disrupt the links if you are using break/create // constraints in modello. // MODELLO-273 update: Use addXXX only if no other methods are available! - sc.add( adder + "( parse" + association.getTo() + "( xmlStreamReader, strict ) );" ); - } - else - { - sc.add( objectName + ".add" + capitalise( singular( associationName ) ) + "( parse" - + association.getTo() + "( xmlStreamReader, strict ) );" ); + sc.add(adder + "( parse" + association.getTo() + "( xmlStreamReader, strict ) );"); + } else { + sc.add(objectName + ".add" + capitalise(singular(associationName)) + "( parse" + + association.getTo() + "( xmlStreamReader, strict ) );"); } - } - else - { - writePrimitiveField( association, association.getTo(), associationName, "add", sc ); + } else { + writePrimitiveField(association, association.getTo(), associationName, "add", sc); } - if ( wrappedItems ) - { + if (wrappedItems) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Unrecognised tag: '\" + " - + "xmlStreamReader.getLocalName() + \"'\", xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Unrecognised tag: '\" + " + + "xmlStreamReader.getLocalName() + \"'\", xmlStreamReader.getLocation() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - } - else - { + sc.add("}"); + } else { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - } - else - { - //Map or Properties + } else { + // Map or Properties - sc.add( tagComparison ); + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"" + valuesTagName + "\".equals( xmlStreamReader.getLocalName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = null;" ); + sc.add("String key = null;"); - sc.add( "String value = null;" ); + sc.add("String value = null;"); - sc.add( "// " + xmlAssociationMetadata.getMapStyle() + " mode." ); + sc.add("// " + xmlAssociationMetadata.getMapStyle() + " mode."); - sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" ); + sc.add("while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"key\".equals( xmlStreamReader.getLocalName() ) )" ); + sc.add("if ( \"key\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); - sc.addIndented( "key = xmlStreamReader.getElementText();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("key = xmlStreamReader.getElementText();"); + sc.add("}"); - sc.add( "else if ( \"value\".equals( xmlStreamReader.getLocalName() ) )" ); + sc.add("else if ( \"value\".equals( xmlStreamReader.getLocalName() ) )"); - sc.add( "{" ); - sc.addIndented( "value = xmlStreamReader.getElementText()" - + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("value = xmlStreamReader.getElementText()" + + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.addIndented( "xmlStreamReader.getText();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("xmlStreamReader.getText();"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "xmlStreamReader.next();" ); + sc.add("xmlStreamReader.next();"); sc.unindent(); - sc.add( "}" ); - } - else - { - //INLINE Mode + sc.add("}"); + } else { + // INLINE Mode - sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" ); + sc.add("while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = xmlStreamReader.getLocalName();" ); + sc.add("String key = xmlStreamReader.getLocalName();"); - sc.add( "String value = xmlStreamReader.getElementText()" - + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + sc.add("String value = xmlStreamReader.getElementText()" + + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } } } - private static void addCodeToAddReferences( ModelAssociation association, JClass jClass, JSourceCode sc, - ModelField referenceIdentifierField, String referredFromClass ) - { - String refFieldName = getRefFieldName( association ); - if ( jClass.getField( refFieldName ) == null ) - { - jClass.addField( new JField( new JType( "java.util.Map" ), refFieldName ) ); + private static void addCodeToAddReferences( + ModelAssociation association, + JClass jClass, + JSourceCode sc, + ModelField referenceIdentifierField, + String referredFromClass) { + String refFieldName = getRefFieldName(association); + if (jClass.getField(refFieldName) == null) { + jClass.addField(new JField(new JType("java.util.Map"), refFieldName)); } - sc.add( "String value = xmlStreamReader.getAttributeValue( null, \"" + referenceIdentifierField.getName() - + "\" );" ); - sc.add( "if ( value != null )" ); - sc.add( "{" ); + sc.add("String value = xmlStreamReader.getAttributeValue( null, \"" + referenceIdentifierField.getName() + + "\" );"); + sc.add("if ( value != null )"); + sc.add("{"); sc.indent(); - sc.add( "// This is a reference to an element elsewhere in the model" ); - sc.add( "if ( " + refFieldName + " == null )" ); - sc.add( "{" ); - sc.addIndented( refFieldName + " = new java.util.HashMap();" ); - sc.add( "}" ); + sc.add("// This is a reference to an element elsewhere in the model"); + sc.add("if ( " + refFieldName + " == null )"); + sc.add("{"); + sc.addIndented(refFieldName + " = new java.util.HashMap();"); + sc.add("}"); - sc.add( "java.util.Map refs = (java.util.Map) " + refFieldName + ".get( " + referredFromClass + " );" ); - sc.add( "if ( refs == null )" ); - sc.add( "{" ); + sc.add("java.util.Map refs = (java.util.Map) " + refFieldName + ".get( " + referredFromClass + " );"); + sc.add("if ( refs == null )"); + sc.add("{"); sc.indent(); - sc.add( "refs = new java.util.HashMap();" ); - sc.add( refFieldName + ".put( " + referredFromClass + ", refs );" ); + sc.add("refs = new java.util.HashMap();"); + sc.add(refFieldName + ".put( " + referredFromClass + ", refs );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( association.isOneMultiplicity() ) - { - sc.add( "refs.put( \"" + association.getName() + "\", value );" ); - } - else - { - sc.add( "refs.put( \"" + association.getName() + ".\" + " + association.getName() + ".size(), value );" ); + if (association.isOneMultiplicity()) { + sc.add("refs.put( \"" + association.getName() + "\", value );"); + } else { + sc.add("refs.put( \"" + association.getName() + ".\" + " + association.getName() + ".size(), value );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - private void writeModelVersionCheck( JSourceCode sc ) - { - writeModelVersionHack( sc ); + private void writeModelVersionCheck(JSourceCode sc) { + writeModelVersionHack(sc); - sc.add( "if ( !\"" + getGeneratedVersion() + "\".equals( modelVersion ) )" ); - sc.add( "{" ); + sc.add("if ( !\"" + getGeneratedVersion() + "\".equals( modelVersion ) )"); + sc.add("{"); sc.addIndented( - "throw new XMLStreamException( \"Document model version of '\" + modelVersion + \"' doesn't match reader " - + "version of '" + getGeneratedVersion() + "'\", xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + "throw new XMLStreamException( \"Document model version of '\" + modelVersion + \"' doesn't match reader " + + "version of '" + getGeneratedVersion() + "'\", xmlStreamReader.getLocation() );"); + sc.add("}"); } /** @@ -1379,566 +1278,534 @@ private void writeModelVersionCheck( JSourceCode sc ) * @param setterName the setter method name * @param sc the source code to add to */ - private void writePrimitiveField( ModelField field, String type, String objectName, String setterName, - JSourceCode sc ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + private void writePrimitiveField( + ModelField field, String type, String objectName, String setterName, JSourceCode sc) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - String tagName = resolveTagName( field, xmlFieldMetadata ); + String tagName = resolveTagName(field, xmlFieldMetadata); String parserGetter; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { parserGetter = "xmlStreamReader.getAttributeValue( null, \"" + tagName + "\" )"; - } - else - { + } else { parserGetter = "xmlStreamReader.getElementText()"; } -/* TODO: - if ( xmlFieldMetadata.isRequired() ) - { - parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; - } -*/ - if ( field.getDefaultValue() != null ) - { + /* TODO: + if ( xmlFieldMetadata.isRequired() ) + { + parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; + } + */ + if (field.getDefaultValue() != null) { parserGetter = "getDefaultValue( " + parserGetter + ", \"" + field.getDefaultValue() + "\" )"; } - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "getTrimmedValue( " + parserGetter + " )"; } - if ( "boolean".equals( type ) || "Boolean".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader ) );" ); - } - else if ( "char".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader ) );" ); - } - else if ( "double".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "float".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "int".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "long".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "short".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "byte".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName - + "\", xmlStreamReader, strict ) );" ); - } - else if ( "String".equals( type ) ) - { + if ("boolean".equals(type) || "Boolean".equals(type)) { + sc.add(objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader ) );"); + } else if ("char".equals(type)) { + sc.add(objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader ) );"); + } else if ("double".equals(type)) { + sc.add(objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("float".equals(type)) { + sc.add(objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("int".equals(type)) { + sc.add(objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("long".equals(type)) { + sc.add(objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("short".equals(type)) { + sc.add(objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("byte".equals(type)) { + sc.add(objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName + + "\", xmlStreamReader, strict ) );"); + } else if ("String".equals(type)) { // TODO: other Primitive types - sc.add( objectName + "." + setterName + "( " + parserGetter + " );" ); - } - else if ( "Date".equals( type ) ) - { - sc.add( "String dateFormat = " - + ( xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null" ) + ";" ); - sc.add( objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName - + "\", dateFormat, xmlStreamReader ) );" ); - } - else if ( "DOM".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( buildDom( xmlStreamReader, " + xmlFieldMetadata.isTrim() + " ) );" ); + sc.add(objectName + "." + setterName + "( " + parserGetter + " );"); + } else if ("Date".equals(type)) { + sc.add("String dateFormat = " + + (xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null") + + ";"); + sc.add(objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName + + "\", dateFormat, xmlStreamReader ) );"); + } else if ("DOM".equals(type)) { + sc.add(objectName + "." + setterName + "( buildDom( xmlStreamReader, " + xmlFieldMetadata.isTrim() + + " ) );"); requiresDomSupport = true; - } - else - { - throw new IllegalArgumentException( "Unknown type: " + type ); + } else { + throw new IllegalArgumentException("Unknown type: " + type); } } - private void writeBuildDomMethod( JClass jClass ) - { - if ( domAsXpp3 ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); - } - else - { - jClass.addField( new JField( new JClass( "org.w3c.dom.Document" ), "_doc_" ) ); - JMethod method = new JMethod( "initDoc", null, null ); + private void writeBuildDomMethod(JClass jClass) { + if (domAsXpp3) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); + } else { + jClass.addField(new JField(new JClass("org.w3c.dom.Document"), "_doc_")); + JMethod method = new JMethod("initDoc", null, null); method.getModifiers().makePrivate(); - method.addException( new JClass( "javax.xml.parsers.ParserConfigurationException" ) ); + method.addException(new JClass("javax.xml.parsers.ParserConfigurationException")); JSourceCode sc = method.getSourceCode(); - sc.add( "javax.xml.parsers.DocumentBuilderFactory dbfac = javax.xml.parsers.DocumentBuilderFactory.newInstance();" ); - sc.add( "javax.xml.parsers.DocumentBuilder docBuilder = dbfac.newDocumentBuilder();" ); - sc.add( "_doc_ = docBuilder.newDocument();" ); - jClass.addMethod( method ); + sc.add( + "javax.xml.parsers.DocumentBuilderFactory dbfac = javax.xml.parsers.DocumentBuilderFactory.newInstance();"); + sc.add("javax.xml.parsers.DocumentBuilder docBuilder = dbfac.newDocumentBuilder();"); + sc.add("_doc_ = docBuilder.newDocument();"); + jClass.addMethod(method); } String type = domAsXpp3 ? "Xpp3Dom" : "org.w3c.dom.Element"; - JMethod method = new JMethod( "buildDom", new JType( type ), null ); + JMethod method = new JMethod("buildDom", new JType(type), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "trim" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addParameter(new JParameter(new JType("XMLStreamReader"), "xmlStreamReader")); + method.addParameter(new JParameter(JType.BOOLEAN, "trim")); + method.addException(new JClass("XMLStreamException")); JSourceCode sc = method.getSourceCode(); - sc.add( "java.util.Stack elements = new java.util.Stack();" ); + sc.add("java.util.Stack elements = new java.util.Stack();"); - sc.add( "java.util.Stack values = new java.util.Stack();" ); + sc.add("java.util.Stack values = new java.util.Stack();"); - sc.add( "int eventType = xmlStreamReader.getEventType();" ); + sc.add("int eventType = xmlStreamReader.getEventType();"); - sc.add( "boolean spacePreserve = false;" ); + sc.add("boolean spacePreserve = false;"); - sc.add( "while ( xmlStreamReader.hasNext() )" ); - sc.add( "{" ); + sc.add("while ( xmlStreamReader.hasNext() )"); + sc.add("{"); sc.indent(); - sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" ); - sc.add( "{" ); + sc.add("if ( eventType == XMLStreamConstants.START_ELEMENT )"); + sc.add("{"); sc.indent(); - sc.add( "spacePreserve = false;" ); - sc.add( "String rawName = xmlStreamReader.getLocalName();" ); + sc.add("spacePreserve = false;"); + sc.add("String rawName = xmlStreamReader.getLocalName();"); - if ( domAsXpp3 ) - { - sc.add( "Xpp3Dom element = new Xpp3Dom( rawName );" ); - } - else - { - sc.add( "org.w3c.dom.Element element = _doc_.createElement( rawName );" ); + if (domAsXpp3) { + sc.add("Xpp3Dom element = new Xpp3Dom( rawName );"); + } else { + sc.add("org.w3c.dom.Element element = _doc_.createElement( rawName );"); } - sc.add( "if ( !elements.empty() )" ); - sc.add( "{" ); + sc.add("if ( !elements.empty() )"); + sc.add("{"); sc.indent(); - sc.add( type + " parent = (" + type + ") elements.peek();" ); + sc.add(type + " parent = (" + type + ") elements.peek();"); - sc.add( "parent." + ( domAsXpp3 ? "addChild" : "appendChild" ) + "( element );" ); + sc.add("parent." + (domAsXpp3 ? "addChild" : "appendChild") + "( element );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "elements.push( element );" ); + sc.add("elements.push( element );"); - sc.add( "if ( xmlStreamReader.isEndElement() )" ); - sc.add( "{" ); - sc.addIndented( "values.push( null );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "values.push( new StringBuilder() );" ); - sc.add( "}" ); + sc.add("if ( xmlStreamReader.isEndElement() )"); + sc.add("{"); + sc.addIndented("values.push( null );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("values.push( new StringBuilder() );"); + sc.add("}"); - sc.add( "int attributesSize = xmlStreamReader.getAttributeCount();" ); + sc.add("int attributesSize = xmlStreamReader.getAttributeCount();"); - sc.add( "for ( int i = 0; i < attributesSize; i++ )" ); - sc.add( "{" ); + sc.add("for ( int i = 0; i < attributesSize; i++ )"); + sc.add("{"); sc.indent(); - sc.add( "String prefix = xmlStreamReader.getAttributePrefix( i );" ); - sc.add( "String localName = xmlStreamReader.getAttributeLocalName( i );" ); - sc.add( "String value = xmlStreamReader.getAttributeValue( i );" ); - sc.add( "if ( XMLConstants.DEFAULT_NS_PREFIX.equals( xmlStreamReader.getAttributeName( i ).getPrefix() ) )" ); - sc.add( "{" ); - sc.addIndented( "element.setAttribute( localName, value );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "element.setAttribute( prefix + ':'+ localName , value );" ); - sc.add( "}" ); - sc.add( "spacePreserve = spacePreserve || ( \"xml\".equals( prefix ) && \"space\".equals( localName ) && \"preserve\".equals( value ) );" ); + sc.add("String prefix = xmlStreamReader.getAttributePrefix( i );"); + sc.add("String localName = xmlStreamReader.getAttributeLocalName( i );"); + sc.add("String value = xmlStreamReader.getAttributeValue( i );"); + sc.add("if ( XMLConstants.DEFAULT_NS_PREFIX.equals( xmlStreamReader.getAttributeName( i ).getPrefix() ) )"); + sc.add("{"); + sc.addIndented("element.setAttribute( localName, value );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("element.setAttribute( prefix + ':'+ localName , value );"); + sc.add("}"); + sc.add( + "spacePreserve = spacePreserve || ( \"xml\".equals( prefix ) && \"space\".equals( localName ) && \"preserve\".equals( value ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "else if ( eventType == XMLStreamConstants.CHARACTERS )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("else if ( eventType == XMLStreamConstants.CHARACTERS )"); + sc.add("{"); sc.indent(); - sc.add( "StringBuilder valueBuffer = (StringBuilder) values.peek();" ); + sc.add("StringBuilder valueBuffer = (StringBuilder) values.peek();"); - sc.add( "String text = xmlStreamReader.getText();" ); + sc.add("String text = xmlStreamReader.getText();"); - sc.add( "if ( trim && !spacePreserve )" ); - sc.add( "{" ); - sc.addIndented( "text = text.trim();" ); - sc.add( "}" ); + sc.add("if ( trim && !spacePreserve )"); + sc.add("{"); + sc.addIndented("text = text.trim();"); + sc.add("}"); - sc.add( "valueBuffer.append( text );" ); + sc.add("valueBuffer.append( text );"); sc.unindent(); - sc.add( "}" ); - sc.add( "else if ( eventType == XMLStreamConstants.END_ELEMENT )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("else if ( eventType == XMLStreamConstants.END_ELEMENT )"); + sc.add("{"); sc.indent(); - sc.add( type + " element = (" + type + ") elements.pop();" ); + sc.add(type + " element = (" + type + ") elements.pop();"); - sc.add( "// this Object could be null if it is a singleton tag" ); - sc.add( "Object accumulatedValue = values.pop();" ); + sc.add("// this Object could be null if it is a singleton tag"); + sc.add("Object accumulatedValue = values.pop();"); - sc.add( "if ( " + ( domAsXpp3 ? "element.getChildCount() == 0" : "!element.hasChildNodes()" ) + " )" ); - sc.add( "{" ); - sc.addIndented( "element." + ( domAsXpp3 ? "setValue" : "setTextContent" ) + "( ( accumulatedValue == null ) ? null : accumulatedValue.toString() );" ); - sc.add( "}" ); + sc.add("if ( " + (domAsXpp3 ? "element.getChildCount() == 0" : "!element.hasChildNodes()") + " )"); + sc.add("{"); + sc.addIndented("element." + (domAsXpp3 ? "setValue" : "setTextContent") + + "( ( accumulatedValue == null ) ? null : accumulatedValue.toString() );"); + sc.add("}"); - sc.add( "if ( values.empty() )" ); - sc.add( "{" ); - sc.addIndented( "return element;" ); - sc.add( "}" ); + sc.add("if ( values.empty() )"); + sc.add("{"); + sc.addIndented("return element;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "eventType = xmlStreamReader.next();" ); + sc.add("eventType = xmlStreamReader.next();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "throw new IllegalStateException( \"End of document found before returning to 0 depth\" );" ); + sc.add("throw new IllegalStateException( \"End of document found before returning to 0 depth\" );"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private void writeHelpers( JClass jClass ) - { - JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null ); + private void writeHelpers(JClass jClass) { + JMethod method = new JMethod("getTrimmedValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "s = s.trim();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = s.trim();"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getDefaultValue", new JClass( "String" ), null ); + method = new JMethod("getDefaultValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "v" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "v")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); - sc.addIndented( "s = v;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = v;"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null ); - method.addException( new JClass( "XMLStreamException" ) ); + method = new JMethod("getRequiredAttributeValue", new JClass("String"), null); + method.addException(new JClass("XMLStreamException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Missing required value for attribute '\" + attribute + \"'\", " - + "xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Missing required value for attribute '\" + attribute + \"'\", " + + "xmlStreamReader.getLocation() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getBooleanValue", JType.BOOLEAN, null ); - method.addException( new JClass( "XMLStreamException" ) ); + method = new JMethod("getBooleanValue", JType.BOOLEAN, null); + method.addException(new JClass("XMLStreamException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return Boolean.valueOf( s ).booleanValue();"); + sc.add("}"); - sc.add( "return false;" ); + sc.add("return false;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getCharacterValue", JType.CHAR, null ); - method.addException( new JClass( "XMLStreamException" ) ); + method = new JMethod("getCharacterValue", JType.CHAR, null); + method.addException(new JClass("XMLStreamException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return s.charAt( 0 );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return s.charAt( 0 );"); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" ); + method = convertNumericalType("getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", - "a short integer" ); + method = convertNumericalType( + "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", "a short integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" ); + method = convertNumericalType("getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" ); + method = convertNumericalType("getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", - "a floating point number" ); + method = convertNumericalType( + "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", - "a floating point number" ); + method = convertNumericalType( + "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", "a floating point number"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null ); - method.addException( new JClass( "XMLStreamException" ) ); + method = new JMethod("getDateValue", new JClass("java.util.Date"), null); + method.addException(new JClass("XMLStreamException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "dateFormat" ) ); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("String"), "dateFormat")); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addException(new JClass("XMLStreamException")); - writeDateParsingHelper( method.getSourceCode(), "new XMLStreamException( e.getMessage(), xmlStreamReader.getLocation(), e )" ); + writeDateParsingHelper( + method.getSourceCode(), "new XMLStreamException( e.getMessage(), xmlStreamReader.getLocation(), e )"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null ); + method = new JMethod("checkFieldWithDuplicate", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "alias" ) ); - method.addParameter( new JParameter( new JClass( "java.util.Set" ), "parsed" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(new JClass("String"), "alias")); + method.addParameter(new JParameter(new JClass("java.util.Set"), "parsed")); + method.addException(new JClass("XMLStreamException")); sc = method.getSourceCode(); - sc.add( "if ( !( xmlStreamReader.getLocalName().equals( tagName ) ||" - + " xmlStreamReader.getLocalName().equals( alias ) ) )" ); + sc.add("if ( !( xmlStreamReader.getLocalName().equals( tagName ) ||" + + " xmlStreamReader.getLocalName().equals( alias ) ) )"); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); - sc.add( "if ( !parsed.add( tagName ) )" ); + sc.add("if ( !parsed.add( tagName ) )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new XMLStreamException( \"Duplicated tag: '\" + tagName + \"'\", xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + "throw new XMLStreamException( \"Duplicated tag: '\" + tagName + \"'\", xmlStreamReader.getLocation() );"); + sc.add("}"); - sc.add( "return true;" ); + sc.add("return true;"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "checkUnknownElement", null, null ); + method = new JMethod("checkUnknownElement", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("XMLStreamException")); sc = method.getSourceCode(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Unrecognised tag: '\" + xmlStreamReader.getLocalName() + " - + "\"'\", xmlStreamReader.getLocation() );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Unrecognised tag: '\" + xmlStreamReader.getLocalName() + " + + "\"'\", xmlStreamReader.getLocation() );"); + sc.add("}"); - sc.add( "int unrecognizedTagCount = 1;" ); - sc.add( "while( unrecognizedTagCount != 0 )" ); + sc.add("int unrecognizedTagCount = 1;"); + sc.add("while( unrecognizedTagCount != 0 )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "xmlStreamReader.next();" ); - sc.add( "if ( xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT )" ); + sc.add("xmlStreamReader.next();"); + sc.add("if ( xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT )"); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount++;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("unrecognizedTagCount++;"); + sc.add("}"); - sc.add( "else if ( xmlStreamReader.getEventType() == XMLStreamConstants.END_ELEMENT )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount--;" ); - sc.add( "}" ); + sc.add("else if ( xmlStreamReader.getEventType() == XMLStreamConstants.END_ELEMENT )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount--;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); // -------------------------------------------------------------------- - method = new JMethod( "nextTag", JType.INT, null ); + method = new JMethod("nextTag", JType.INT, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addException( new JClass( "XMLStreamException" ) ); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addException(new JClass("XMLStreamException")); sc = method.getSourceCode(); - sc.add( "while ( true )" ); - sc.add( "{" ); + sc.add("while ( true )"); + sc.add("{"); sc.indent(); - sc.add( "int eventType = xmlStreamReader.next();" ); - sc.add( "switch ( eventType )" ); - sc.add( "{" ); + sc.add("int eventType = xmlStreamReader.next();"); + sc.add("switch ( eventType )"); + sc.add("{"); sc.indent(); - sc.add( "case XMLStreamConstants.CHARACTERS:" ); - sc.add( "case XMLStreamConstants.CDATA:" ); - sc.add( "case XMLStreamConstants.SPACE:" ); - sc.add( "case XMLStreamConstants.PROCESSING_INSTRUCTION:" ); - sc.add( "case XMLStreamConstants.COMMENT:" ); - sc.addIndented( "break;" ); - sc.add( "case XMLStreamConstants.START_ELEMENT:" ); - sc.add( "case XMLStreamConstants.END_ELEMENT:" ); - sc.addIndented( "return eventType;" ); - sc.add( "default:" ); - sc.addIndented( "throw new XMLStreamException( \"expected start or end tag\", xmlStreamReader.getLocation() );" ); + sc.add("case XMLStreamConstants.CHARACTERS:"); + sc.add("case XMLStreamConstants.CDATA:"); + sc.add("case XMLStreamConstants.SPACE:"); + sc.add("case XMLStreamConstants.PROCESSING_INSTRUCTION:"); + sc.add("case XMLStreamConstants.COMMENT:"); + sc.addIndented("break;"); + sc.add("case XMLStreamConstants.START_ELEMENT:"); + sc.add("case XMLStreamConstants.END_ELEMENT:"); + sc.addIndented("return eventType;"); + sc.add("default:"); + sc.addIndented("throw new XMLStreamException( \"expected start or end tag\", xmlStreamReader.getLocation() );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc ) - { - JMethod method = new JMethod( methodName, returnType, null ); - method.addException( new JClass( "XMLStreamException" ) ); + private JMethod convertNumericalType(String methodName, JType returnType, String expression, String typeDesc) { + JMethod method = new JMethod(methodName, returnType, null); + method.addException(new JClass("XMLStreamException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XMLStreamReader"), "xmlStreamReader")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "try" ); + sc.add("try"); - sc.add( "{" ); - sc.addIndented( "return " + expression + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return " + expression + ";"); + sc.add("}"); - sc.add( "catch ( NumberFormatException nfe )" ); + sc.add("catch ( NumberFormatException nfe )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( "throw new XMLStreamException( \"Unable to parse element '\" + attribute + \"', must be " - + typeDesc + " but was '\" + s + \"'\", xmlStreamReader.getLocation(), nfe );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XMLStreamException( \"Unable to parse element '\" + attribute + \"', must be " + + typeDesc + " but was '\" + s + \"'\", xmlStreamReader.getLocation(), nfe );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); return method; } diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxSerializerGenerator.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxSerializerGenerator.java index d67ec1cab..5866afebd 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxSerializerGenerator.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxSerializerGenerator.java @@ -22,9 +22,13 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; -import org.codehaus.modello.plugin.ModelloGenerator; import org.codehaus.modello.plugin.java.javasource.JClass; import org.codehaus.modello.plugin.java.javasource.JConstructor; import org.codehaus.modello.plugin.java.javasource.JField; @@ -36,330 +40,335 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - /** * Generates the IndentingXMLStreamWriter used by the writer for pretty printing. - * + * * @author Benjamin Bentmann */ -@Component( role = StaxSerializerGenerator.class, hint = "stax-serializer" ) -public class StaxSerializerGenerator - extends AbstractStaxGenerator -{ - - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); - - try - { +@Component(role = StaxSerializerGenerator.class, hint = "stax-serializer") +public class StaxSerializerGenerator extends AbstractStaxGenerator { + + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + try { generateStaxSerializer(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating StAX serializer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating StAX serializer.", ex); } } - private void generateStaxSerializer() - throws ModelloException, IOException - { + private void generateStaxSerializer() throws ModelloException, IOException { Model objectModel = getModel(); String packageName = - objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) + ".io.stax"; + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.stax"; String className = "IndentingXMLStreamWriter"; - JSourceWriter sourceWriter = newJSourceWriter( packageName, className ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, className); - JClass jClass = new JClass( packageName + '.' + className ); + JClass jClass = new JClass(packageName + '.' + className); jClass.getModifiers().makePackage(); - jClass.addInterface( "XMLStreamWriter" ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); - - jClass.addImport( "javax.xml.namespace.NamespaceContext" ); - jClass.addImport( "javax.xml.stream.XMLStreamException" ); - jClass.addImport( "javax.xml.stream.XMLStreamWriter" ); - - addField( jClass, "XMLStreamWriter", "out", null, false ); - addField( jClass, "String", "NEW_LINE", "\"\\n\"", true ); - addField( jClass, "String", "newLine", "NEW_LINE", false ); - addField( jClass, "String", "indent", "\" \"", false ); - addField( jClass, "char[]", "linePrefix", "\" \".toCharArray()", false ); - addField( jClass, "int", "depth", null, false ); - addField( jClass, "byte[]", "states", "{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", false ); - addField( jClass, "int", "ELEMENT_HAS_DATA", "0x1", true ); - addField( jClass, "int", "ELEMENT_HAS_MARKUP", "0x2", true ); + jClass.addInterface("XMLStreamWriter"); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); + + jClass.addImport("javax.xml.namespace.NamespaceContext"); + jClass.addImport("javax.xml.stream.XMLStreamException"); + jClass.addImport("javax.xml.stream.XMLStreamWriter"); + + addField(jClass, "XMLStreamWriter", "out", null, false); + addField(jClass, "String", "NEW_LINE", "\"\\n\"", true); + addField(jClass, "String", "newLine", "NEW_LINE", false); + addField(jClass, "String", "indent", "\" \"", false); + addField(jClass, "char[]", "linePrefix", "\" \".toCharArray()", false); + addField(jClass, "int", "depth", null, false); + addField(jClass, "byte[]", "states", "{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }", false); + addField(jClass, "int", "ELEMENT_HAS_DATA", "0x1", true); + addField(jClass, "int", "ELEMENT_HAS_MARKUP", "0x2", true); JConstructor constructor = jClass.createConstructor(); - constructor.addParameter( new JParameter( new JType( "XMLStreamWriter" ), "out" ) ); - constructor.getSourceCode().add( "this.out = out;" ); + constructor.addParameter(new JParameter(new JType("XMLStreamWriter"), "out")); + constructor.getSourceCode().add("this.out = out;"); JMethod jMethod; JSourceCode sc; - jMethod = new JMethod( "setNewLine" ); - jMethod.addParameter( new JParameter( new JType( "String" ), "newLine" ) ); - jMethod.getSourceCode().add( "this.newLine = newLine;" ); - jClass.addMethod( jMethod ); + jMethod = new JMethod("setNewLine"); + jMethod.addParameter(new JParameter(new JType("String"), "newLine")); + jMethod.getSourceCode().add("this.newLine = newLine;"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "getLineSeparator", new JType( "String" ), null ); + jMethod = new JMethod("getLineSeparator", new JType("String"), null); sc = jMethod.getSourceCode(); - sc.add( "try" ); - sc.add( "{" ); - sc.addIndented( "return System.getProperty( \"line.separator\", NEW_LINE );" ); - sc.add( "}" ); - sc.add( "catch ( Exception e )" ); - sc.add( "{" ); - sc.addIndented( "return NEW_LINE;" ); - sc.add( "}" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "beforeMarkup" ); + sc.add("try"); + sc.add("{"); + sc.addIndented("return System.getProperty( \"line.separator\", NEW_LINE );"); + sc.add("}"); + sc.add("catch ( Exception e )"); + sc.add("{"); + sc.addIndented("return NEW_LINE;"); + sc.add("}"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("beforeMarkup"); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "int state = states[depth];" ); - sc.add( "if ( ( state & ELEMENT_HAS_DATA ) == 0 && ( depth > 0 || state != 0 ) )" ); - sc.add( "{" ); + sc.add("int state = states[depth];"); + sc.add("if ( ( state & ELEMENT_HAS_DATA ) == 0 && ( depth > 0 || state != 0 ) )"); + sc.add("{"); sc.indent(); - sc.add( "newLine( depth );" ); - sc.add( "if ( depth > 0 && indent.length() > 0 )" ); - sc.add( "{" ); - sc.addIndented( "afterMarkup();" ); - sc.add( "}" ); + sc.add("newLine( depth );"); + sc.add("if ( depth > 0 && indent.length() > 0 )"); + sc.add("{"); + sc.addIndented("afterMarkup();"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - jClass.addMethod( jMethod ); + sc.add("}"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "afterMarkup" ); + jMethod = new JMethod("afterMarkup"); jMethod.getModifiers().makePrivate(); - jMethod.getSourceCode().add( "states[depth] |= ELEMENT_HAS_MARKUP;" ); - jClass.addMethod( jMethod ); + jMethod.getSourceCode().add("states[depth] |= ELEMENT_HAS_MARKUP;"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "beforeStartElement" ); + jMethod = new JMethod("beforeStartElement"); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "beforeMarkup();" ); - sc.add( "if ( states.length <= depth + 1 )" ); - sc.add( "{" ); + sc.add("beforeMarkup();"); + sc.add("if ( states.length <= depth + 1 )"); + sc.add("{"); sc.indent(); - sc.add( "byte[] tmp = new byte[states.length * 2];" ); - sc.add( "System.arraycopy( states, 0, tmp, 0, states.length );" ); - sc.add( "states = tmp;" ); + sc.add("byte[] tmp = new byte[states.length * 2];"); + sc.add("System.arraycopy( states, 0, tmp, 0, states.length );"); + sc.add("states = tmp;"); sc.unindent(); - sc.add( "}" ); - sc.add( "states[depth + 1] = 0;" ); - jClass.addMethod( jMethod ); + sc.add("}"); + sc.add("states[depth + 1] = 0;"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "afterStartElement" ); + jMethod = new JMethod("afterStartElement"); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "afterMarkup();" ); - sc.add( "depth++;" ); - jClass.addMethod( jMethod ); + sc.add("afterMarkup();"); + sc.add("depth++;"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "beforeEndElement" ); + jMethod = new JMethod("beforeEndElement"); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "if ( depth > 0 && states[depth] == ELEMENT_HAS_MARKUP )" ); - sc.add( "{" ); - sc.addIndented( "newLine( depth - 1 );" ); - sc.add( "}" ); - jClass.addMethod( jMethod ); + sc.add("if ( depth > 0 && states[depth] == ELEMENT_HAS_MARKUP )"); + sc.add("{"); + sc.addIndented("newLine( depth - 1 );"); + sc.add("}"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "afterEndElement" ); + jMethod = new JMethod("afterEndElement"); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "if ( depth > 0 )" ); - sc.add( "{" ); + sc.add("if ( depth > 0 )"); + sc.add("{"); sc.indent(); - sc.add( "depth--;" ); - sc.add( "if ( depth <= 0 )" ); - sc.add( "{" ); - sc.addIndented( "newLine( 0 );" ); - sc.add( "}" ); + sc.add("depth--;"); + sc.add("if ( depth <= 0 )"); + sc.add("{"); + sc.addIndented("newLine( 0 );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - jClass.addMethod( jMethod ); + sc.add("}"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "afterData" ); + jMethod = new JMethod("afterData"); jMethod.getModifiers().makePrivate(); - jMethod.getSourceCode().add( "states[depth] |= ELEMENT_HAS_DATA;" ); - jClass.addMethod( jMethod ); + jMethod.getSourceCode().add("states[depth] |= ELEMENT_HAS_DATA;"); + jClass.addMethod(jMethod); - jMethod = new JMethod( "newLine" ); - jMethod.addParameter( new JParameter( JType.INT, "depth" ) ); + jMethod = new JMethod("newLine"); + jMethod.addParameter(new JParameter(JType.INT, "depth")); jMethod.getModifiers().makePrivate(); sc = jMethod.getSourceCode(); - sc.add( "try" ); - sc.add( "{" ); + sc.add("try"); + sc.add("{"); sc.indent(); - sc.add( "out.writeCharacters( newLine );" ); - sc.add( "int prefixLength = depth * indent.length();" ); - sc.add( "while ( linePrefix.length < prefixLength )" ); - sc.add( "{" ); + sc.add("out.writeCharacters( newLine );"); + sc.add("int prefixLength = depth * indent.length();"); + sc.add("while ( linePrefix.length < prefixLength )"); + sc.add("{"); sc.indent(); - sc.add( "char[] tmp = new char[linePrefix.length * 2];" ); - sc.add( "System.arraycopy( linePrefix, 0, tmp, 0, linePrefix.length );" ); - sc.add( "System.arraycopy( linePrefix, 0, tmp, linePrefix.length, linePrefix.length );" ); - sc.add( "linePrefix = tmp;" ); + sc.add("char[] tmp = new char[linePrefix.length * 2];"); + sc.add("System.arraycopy( linePrefix, 0, tmp, 0, linePrefix.length );"); + sc.add("System.arraycopy( linePrefix, 0, tmp, linePrefix.length, linePrefix.length );"); + sc.add("linePrefix = tmp;"); sc.unindent(); - sc.add( "}" ); - sc.add( "out.writeCharacters( linePrefix, 0, prefixLength );" ); + sc.add("}"); + sc.add("out.writeCharacters( linePrefix, 0, prefixLength );"); sc.unindent(); - sc.add( "}" ); - sc.add( "catch ( Exception e )" ); - sc.add( "{" ); - sc.add( "}" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "close" ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.getSourceCode().add( "out.close();" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "flush" ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.getSourceCode().add( "out.flush();" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "getNamespaceContext", new JType( "NamespaceContext" ), null ); - jMethod.getSourceCode().add( "return out.getNamespaceContext();" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "getPrefix", new JType( "String" ), null ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.addParameter( param( "String", "uri" ) ); - jMethod.getSourceCode().add( "return out.getPrefix( uri );" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "getProperty", new JType( "Object" ), null ); - jMethod.addException( new JClass( "IllegalArgumentException" ) ); - jMethod.addParameter( param( "String", "name" ) ); - jMethod.getSourceCode().add( "return out.getProperty( name );" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "setDefaultNamespace" ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.addParameter( param( "String", "uri" ) ); - jMethod.getSourceCode().add( "out.setDefaultNamespace( uri );" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "setNamespaceContext" ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.addParameter( param( "NamespaceContext", "context" ) ); - jMethod.getSourceCode().add( "out.setNamespaceContext( context );" ); - jClass.addMethod( jMethod ); - - jMethod = new JMethod( "setPrefix" ); - jMethod.addException( new JClass( "XMLStreamException" ) ); - jMethod.addParameter( param( "String", "prefix" ) ); - jMethod.addParameter( param( "String", "uri" ) ); - jMethod.getSourceCode().add( "out.setPrefix( prefix, uri );" ); - jClass.addMethod( jMethod ); - - add( jClass, "Attribute", null, null, param( "String", "localName" ), param( "String", "value" ) ); - add( jClass, "Attribute", null, null, param( "String", "namespaceURI" ), param( "String", "localName" ), - param( "String", "value" ) ); - add( jClass, "Attribute", null, null, param( "String", "prefix" ), param( "String", "namespaceURI" ), - param( "String", "localName" ), param( "String", "value" ) ); - - add( jClass, "CData", null, "Data", param( "String", "data" ) ); - - add( jClass, "Characters", null, "Data", param( "String", "text" ) ); - add( jClass, "Characters", null, "Data", param( "char[]", "text" ), param( "int", "start" ), param( "int", - "len" ) ); - - add( jClass, "Comment", "Markup", "Markup", param( "String", "data" ) ); - - add( jClass, "DTD", "Markup", "Markup", param( "String", "dtd" ) ); - - add( jClass, "DefaultNamespace", null, null, param( "String", "namespaceURI" ) ); - - add( jClass, "EmptyElement", "Markup", "Markup", param( "String", "localName" ) ); - add( jClass, "EmptyElement", "Markup", "Markup", param( "String", "namespaceURI" ), param( "String", - "localName" ) ); - add( jClass, "EmptyElement", "Markup", "Markup", param( "String", "prefix" ), - param( "String", "namespaceURI" ), param( "String", "localName" ) ); - - add( jClass, "EndDocument", null, null ); - - add( jClass, "EndElement", "EndElement", "EndElement" ); - - add( jClass, "EntityRef", null, "Data", param( "String", "name" ) ); - - add( jClass, "Namespace", null, null, param( "String", "prefix" ), param( "String", "namespaceURI" ) ); - - add( jClass, "ProcessingInstruction", "Markup", "Markup", param( "String", "target" ) ); - add( jClass, "ProcessingInstruction", "Markup", "Markup", param( "String", "target" ), param( "String", "data" ) ); - - add( jClass, "StartDocument", "Markup", "Markup" ); - add( jClass, "StartDocument", "Markup", "Markup", param( "String", "version" ) ); - add( jClass, "StartDocument", "Markup", "Markup", param( "String", "encoding" ), param( "String", "version" ) ); - - add( jClass, "StartElement", "StartElement", "StartElement", param( "String", "localName" ) ); - add( jClass, "StartElement", "StartElement", "StartElement", param( "String", "namespaceURI" ), - param( "String", "localName" ) ); - add( jClass, "StartElement", "StartElement", "StartElement", param( "String", "prefix" ), param( "String", - "localName" ), - param( "String", "namespaceURI" ) ); - - jClass.print( sourceWriter ); + sc.add("}"); + sc.add("catch ( Exception e )"); + sc.add("{"); + sc.add("}"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("close"); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.getSourceCode().add("out.close();"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("flush"); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.getSourceCode().add("out.flush();"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("getNamespaceContext", new JType("NamespaceContext"), null); + jMethod.getSourceCode().add("return out.getNamespaceContext();"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("getPrefix", new JType("String"), null); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.addParameter(param("String", "uri")); + jMethod.getSourceCode().add("return out.getPrefix( uri );"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("getProperty", new JType("Object"), null); + jMethod.addException(new JClass("IllegalArgumentException")); + jMethod.addParameter(param("String", "name")); + jMethod.getSourceCode().add("return out.getProperty( name );"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("setDefaultNamespace"); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.addParameter(param("String", "uri")); + jMethod.getSourceCode().add("out.setDefaultNamespace( uri );"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("setNamespaceContext"); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.addParameter(param("NamespaceContext", "context")); + jMethod.getSourceCode().add("out.setNamespaceContext( context );"); + jClass.addMethod(jMethod); + + jMethod = new JMethod("setPrefix"); + jMethod.addException(new JClass("XMLStreamException")); + jMethod.addParameter(param("String", "prefix")); + jMethod.addParameter(param("String", "uri")); + jMethod.getSourceCode().add("out.setPrefix( prefix, uri );"); + jClass.addMethod(jMethod); + + add(jClass, "Attribute", null, null, param("String", "localName"), param("String", "value")); + add( + jClass, + "Attribute", + null, + null, + param("String", "namespaceURI"), + param("String", "localName"), + param("String", "value")); + add( + jClass, + "Attribute", + null, + null, + param("String", "prefix"), + param("String", "namespaceURI"), + param("String", "localName"), + param("String", "value")); + + add(jClass, "CData", null, "Data", param("String", "data")); + + add(jClass, "Characters", null, "Data", param("String", "text")); + add(jClass, "Characters", null, "Data", param("char[]", "text"), param("int", "start"), param("int", "len")); + + add(jClass, "Comment", "Markup", "Markup", param("String", "data")); + + add(jClass, "DTD", "Markup", "Markup", param("String", "dtd")); + + add(jClass, "DefaultNamespace", null, null, param("String", "namespaceURI")); + + add(jClass, "EmptyElement", "Markup", "Markup", param("String", "localName")); + add(jClass, "EmptyElement", "Markup", "Markup", param("String", "namespaceURI"), param("String", "localName")); + add( + jClass, + "EmptyElement", + "Markup", + "Markup", + param("String", "prefix"), + param("String", "namespaceURI"), + param("String", "localName")); + + add(jClass, "EndDocument", null, null); + + add(jClass, "EndElement", "EndElement", "EndElement"); + + add(jClass, "EntityRef", null, "Data", param("String", "name")); + + add(jClass, "Namespace", null, null, param("String", "prefix"), param("String", "namespaceURI")); + + add(jClass, "ProcessingInstruction", "Markup", "Markup", param("String", "target")); + add(jClass, "ProcessingInstruction", "Markup", "Markup", param("String", "target"), param("String", "data")); + + add(jClass, "StartDocument", "Markup", "Markup"); + add(jClass, "StartDocument", "Markup", "Markup", param("String", "version")); + add(jClass, "StartDocument", "Markup", "Markup", param("String", "encoding"), param("String", "version")); + + add(jClass, "StartElement", "StartElement", "StartElement", param("String", "localName")); + add( + jClass, + "StartElement", + "StartElement", + "StartElement", + param("String", "namespaceURI"), + param("String", "localName")); + add( + jClass, + "StartElement", + "StartElement", + "StartElement", + param("String", "prefix"), + param("String", "localName"), + param("String", "namespaceURI")); + + jClass.print(sourceWriter); sourceWriter.close(); } - private void addField( JClass jClass, String fieldType, String fieldName, String initializer, boolean constant ) - { - JField jField = new JField( new JType( fieldType ), fieldName ); - jField.setInitString( initializer ); - if ( constant ) - { - jField.getModifiers().setFinal( true ); - jField.getModifiers().setStatic( true ); + private void addField(JClass jClass, String fieldType, String fieldName, String initializer, boolean constant) { + JField jField = new JField(new JType(fieldType), fieldName); + jField.setInitString(initializer); + if (constant) { + jField.getModifiers().setFinal(true); + jField.getModifiers().setStatic(true); } - jClass.addField( jField ); + jClass.addField(jField); } - private void add( JClass jClass, String name, String before, String after, JParameter... params ) - { + private void add(JClass jClass, String name, String before, String after, JParameter... params) { List names = new ArrayList(); - JMethod jMethod = new JMethod( "write" + name ); - jMethod.addException( new JClass( "XMLStreamException" ) ); + JMethod jMethod = new JMethod("write" + name); + jMethod.addException(new JClass("XMLStreamException")); - for ( JParameter param : params ) - { - jMethod.addParameter( param ); - names.add( param.getName() ); + for (JParameter param : params) { + jMethod.addParameter(param); + names.add(param.getName()); } JSourceCode sc = jMethod.getSourceCode(); - if ( before != null ) - { - sc.add( "before" + before + "();" ); + if (before != null) { + sc.add("before" + before + "();"); } - sc.add( "out.write" + name + "( " + StringUtils.join( names.iterator(), ", " ) + " );" ); + sc.add("out.write" + name + "( " + StringUtils.join(names.iterator(), ", ") + " );"); - if ( after != null ) - { - sc.add( "after" + after + "();" ); + if (after != null) { + sc.add("after" + after + "();"); } - jClass.addMethod( jMethod ); + jClass.addMethod(jMethod); } - private static JParameter param( String type, String name ) - { - return new JParameter( new JType( type ), name ); + private static JParameter param(String type, String name) { + return new JParameter(new JType(type), name); } - } diff --git a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxWriterGenerator.java b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxWriterGenerator.java index 5ca8e23d9..28f3e1cde 100644 --- a/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxWriterGenerator.java +++ b/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxWriterGenerator.java @@ -22,6 +22,10 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelAssociation; @@ -45,259 +49,238 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - /** * @author Jason van Zyl * @author Emmanuel Venisse */ -@Component( role = ModelloGenerator.class, hint = "stax-writer" ) -public class StaxWriterGenerator - extends AbstractStaxGenerator -{ +@Component(role = ModelloGenerator.class, hint = "stax-writer") +public class StaxWriterGenerator extends AbstractStaxGenerator { private boolean requiresDomSupport; @Requirement private StaxSerializerGenerator serializerGenerator; - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); requiresDomSupport = false; - try - { + try { generateStaxWriter(); + } catch (IOException ex) { + throw new ModelloException("Exception while generating StAX Writer.", ex); } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating StAX Writer.", ex ); - } - - serializerGenerator.generate( model, parameters ); + + serializerGenerator.generate(model, parameters); } - private void generateStaxWriter() - throws ModelloException, IOException - { + private void generateStaxWriter() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.stax"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.stax"; - String marshallerName = getFileName( "StaxWriter" ); + String marshallerName = getFileName("StaxWriter"); - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.Writer" ); - jClass.addImport( "java.io.StringWriter" ); - jClass.addImport( "java.text.DateFormat" ); - jClass.addImport( "java.util.Iterator" ); - jClass.addImport( "java.util.Locale" ); - jClass.addImport( "java.util.jar.Manifest" ); - jClass.addImport( "javax.xml.stream.*" ); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.Writer"); + jClass.addImport("java.io.StringWriter"); + jClass.addImport("java.text.DateFormat"); + jClass.addImport("java.util.Iterator"); + jClass.addImport("java.util.Locale"); + jClass.addImport("java.util.jar.Manifest"); + jClass.addImport("javax.xml.stream.*"); - addModelImports( jClass, null ); + addModelImports(jClass, null); - jClass.addField( new JField( JType.INT, "curId" ) ); - jClass.addField( new JField( new JType( "java.util.Map" ), "idMap" ) ); - JConstructor constructor = new JConstructor( jClass ); - constructor.getSourceCode().add( "idMap = new java.util.HashMap();" ); - jClass.addConstructor( constructor ); + jClass.addField(new JField(JType.INT, "curId")); + jClass.addField(new JField(new JType("java.util.Map"), "idMap")); + JConstructor constructor = new JConstructor(jClass); + constructor.getSourceCode().add("idMap = new java.util.HashMap();"); + jClass.addConstructor(constructor); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - String rootElement = resolveTagName( rootClass ); + String rootElement = resolveTagName(rootClass); // ---------------------------------------------------------------------- // Write the write( Writer, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - String rootElementParameterName = uncapitalise( root ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + String rootElementParameterName = uncapitalise(root); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "java.io.IOException" ) ); - marshall.addException( new JClass( "XMLStreamException" ) ); + marshall.addException(new JClass("java.io.IOException")); + marshall.addException(new JClass("XMLStreamException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "XMLOutputFactory factory = XMLOutputFactory.newInstance();" ); + sc.add("XMLOutputFactory factory = XMLOutputFactory.newInstance();"); // currently, only woodstox supports Windows line endings. It works with Java 6/RI and stax <= 1.1.1 as well // but we have no way to detect them - sc.add( "boolean supportWindowsLineEndings = false;" ); - sc.add( "if ( factory.isPropertySupported( \"com.ctc.wstx.outputEscapeCr\" ) )" ); - sc.add( "{" ); + sc.add("boolean supportWindowsLineEndings = false;"); + sc.add("if ( factory.isPropertySupported( \"com.ctc.wstx.outputEscapeCr\" ) )"); + sc.add("{"); sc.indent(); - sc.add( "factory.setProperty( \"com.ctc.wstx.outputEscapeCr\", Boolean.FALSE );" ); - sc.add( "supportWindowsLineEndings = true;" ); + sc.add("factory.setProperty( \"com.ctc.wstx.outputEscapeCr\", Boolean.FALSE );"); + sc.add("supportWindowsLineEndings = true;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "if ( factory.isPropertySupported( \"org.codehaus.stax2.automaticEmptyElements\" ) )" ); - sc.add( "{" ); - sc.addIndented( "factory.setProperty( \"org.codehaus.stax2.automaticEmptyElements\", Boolean.FALSE );" ); - sc.add( "}" ); + sc.add("if ( factory.isPropertySupported( \"org.codehaus.stax2.automaticEmptyElements\" ) )"); + sc.add("{"); + sc.addIndented("factory.setProperty( \"org.codehaus.stax2.automaticEmptyElements\", Boolean.FALSE );"); + sc.add("}"); sc.add( - "IndentingXMLStreamWriter serializer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( writer ) );" ); + "IndentingXMLStreamWriter serializer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( writer ) );"); - sc.add( "if ( supportWindowsLineEndings )" ); - sc.add( "{" ); - sc.addIndented( "serializer.setNewLine( serializer.getLineSeparator() );" ); - sc.add( "}" ); + sc.add("if ( supportWindowsLineEndings )"); + sc.add("{"); + sc.addIndented("serializer.setNewLine( serializer.getLineSeparator() );"); + sc.add("}"); - sc.add( "serializer.writeStartDocument( " + rootElementParameterName + ".getModelEncoding(), \"1.0\" );" ); + sc.add("serializer.writeStartDocument( " + rootElementParameterName + ".getModelEncoding(), \"1.0\" );"); - sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );"); - sc.add( "serializer.writeEndDocument();" ); + sc.add("serializer.writeEndDocument();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "java.io.IOException" ) ); - marshall.addException( new JClass( "XMLStreamException" ) ); + marshall.addException(new JClass("java.io.IOException")); + marshall.addException(new JClass("XMLStreamException")); sc = marshall.getSourceCode(); - sc.add( "XMLOutputFactory factory = XMLOutputFactory.newInstance();" ); + sc.add("XMLOutputFactory factory = XMLOutputFactory.newInstance();"); // currently, only woodstox supports Windows line endings. It works with Java 6/RI and stax <= 1.1.1 as well // but we have no way to detect them - sc.add( "boolean supportWindowsLineEndings = false;" ); - sc.add( "if ( factory.isPropertySupported( \"com.ctc.wstx.outputEscapeCr\" ) )" ); - sc.add( "{" ); + sc.add("boolean supportWindowsLineEndings = false;"); + sc.add("if ( factory.isPropertySupported( \"com.ctc.wstx.outputEscapeCr\" ) )"); + sc.add("{"); sc.indent(); - sc.add( "factory.setProperty( \"com.ctc.wstx.outputEscapeCr\", Boolean.FALSE );" ); - sc.add( "supportWindowsLineEndings = true;" ); + sc.add("factory.setProperty( \"com.ctc.wstx.outputEscapeCr\", Boolean.FALSE );"); + sc.add("supportWindowsLineEndings = true;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "if ( factory.isPropertySupported( \"org.codehaus.stax2.automaticEmptyElements\" ) )" ); - sc.add( "{" ); - sc.addIndented( "factory.setProperty( \"org.codehaus.stax2.automaticEmptyElements\", Boolean.FALSE );" ); - sc.add( "}" ); + sc.add("if ( factory.isPropertySupported( \"org.codehaus.stax2.automaticEmptyElements\" ) )"); + sc.add("{"); + sc.addIndented("factory.setProperty( \"org.codehaus.stax2.automaticEmptyElements\", Boolean.FALSE );"); + sc.add("}"); - sc.add( "IndentingXMLStreamWriter serializer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( stream, " - + rootElementParameterName + ".getModelEncoding() ) );" ); + sc.add( + "IndentingXMLStreamWriter serializer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( stream, " + + rootElementParameterName + ".getModelEncoding() ) );"); - sc.add( "if ( supportWindowsLineEndings )" ); - sc.add( "{" ); - sc.addIndented( "serializer.setNewLine( serializer.getLineSeparator() );" ); - sc.add( "}" ); + sc.add("if ( supportWindowsLineEndings )"); + sc.add("{"); + sc.addIndented("serializer.setNewLine( serializer.getLineSeparator() );"); + sc.add("}"); - sc.add( "serializer.writeStartDocument( " + rootElementParameterName + ".getModelEncoding(), \"1.0\" );" ); + sc.add("serializer.writeStartDocument( " + rootElementParameterName + ".getModelEncoding(), \"1.0\" );"); - sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );"); - sc.add( "serializer.writeEndDocument();" ); + sc.add("serializer.writeEndDocument();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); - if ( requiresDomSupport ) - { - createWriteDomMethod( jClass ); + if (requiresDomSupport) { + createWriteDomMethod(jClass); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); marshall.getModifiers().makePrivate(); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - marshall.addParameter( new JParameter( new JClass( "XMLStreamWriter" ), "serializer" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("String"), "tagName")); + marshall.addParameter(new JParameter(new JClass("XMLStreamWriter"), "serializer")); - marshall.addException( new JClass( "java.io.IOException" ) ); - marshall.addException( new JClass( "XMLStreamException" ) ); + marshall.addException(new JClass("java.io.IOException")); + marshall.addException(new JClass("XMLStreamException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "if ( " + uncapClassName + " != null )" ); + sc.add("if ( " + uncapClassName + " != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); String namespace = null; - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID ); + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) modelClass.getModel().getMetadata(XmlModelMetadata.ID); // add namespace information for root element only - if ( classMetadata.isRootElement() && ( xmlModelMetadata.getNamespace() != null ) ) - { - namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() ); - sc.add( "serializer.setDefaultNamespace( \"" + namespace + "\" );" ); + if (classMetadata.isRootElement() && (xmlModelMetadata.getNamespace() != null)) { + namespace = xmlModelMetadata.getNamespace(getGeneratedVersion()); + sc.add("serializer.setDefaultNamespace( \"" + namespace + "\" );"); } - sc.add( "serializer.writeStartElement( tagName );" ); + sc.add("serializer.writeStartElement( tagName );"); - if ( namespace != null ) - { - sc.add( "serializer.writeDefaultNamespace( \"" + namespace + "\" );" ); + if (namespace != null) { + sc.add("serializer.writeDefaultNamespace( \"" + namespace + "\" );"); - if ( xmlModelMetadata.getSchemaLocation() != null ) - { - String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); + if (xmlModelMetadata.getSchemaLocation() != null) { + String url = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); - sc.add( "serializer.setPrefix( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); - sc.add( "serializer.writeNamespace( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); - sc.add( "serializer.writeAttribute( \"http://www.w3.org/2001/XMLSchema-instance\", \"schemaLocation\", \"" - + namespace + " " + url + "\" );" ); + sc.add("serializer.setPrefix( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); + sc.add("serializer.writeNamespace( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); + sc.add( + "serializer.writeAttribute( \"http://www.w3.org/2001/XMLSchema-instance\", \"schemaLocation\", \"" + + namespace + " " + url + "\" );"); } } - if ( isAssociationPartToClass( modelClass ) ) - { - if ( modelClass.getIdentifierFields( getGeneratedVersion() ).size() != 1 ) - { - writeIdMapCheck( sc, uncapClassName, "modello.id" ); + if (isAssociationPartToClass(modelClass)) { + if (modelClass.getIdentifierFields(getGeneratedVersion()).size() != 1) { + writeIdMapCheck(sc, uncapClassName, "modello.id"); } } @@ -305,381 +288,333 @@ private void writeClass( ModelClass modelClass, JClass jClass ) String contentValue = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // XML attributes - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = getFieldValue( uncapClassName, field ); + String value = getFieldValue(uncapClassName, field); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); - sc.addIndented( "serializer.writeAttribute( \"" + fieldTagName + "\", " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("serializer.writeAttribute( \"" + fieldTagName + "\", " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("}"); } } - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - sc.add( "serializer.writeCharacters( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + " );" ); + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + sc.add("serializer.writeCharacters( " + getValue(contentField.getType(), contentValue, xmlFieldMetadata) + + " );"); } // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // skip field with type Content continue; } - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = getFieldValue( uncapClassName, field ); + String value = getFieldValue(uncapClassName, field); - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { continue; } - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - ModelField referenceIdentifierField = getReferenceIdentifierField( association ); + ModelField referenceIdentifierField = getReferenceIdentifierField(association); - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); - sc.add( "{" ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); + sc.add("{"); sc.indent(); - if ( referenceIdentifierField != null ) - { + if (referenceIdentifierField != null) { // if xml.reference, then store as a reference instead - sc.add( "serializer.writeStartElement( \"" + fieldTagName + "\" );" ); + sc.add("serializer.writeStartElement( \"" + fieldTagName + "\" );"); - writeElementAttribute( sc, referenceIdentifierField, value ); + writeElementAttribute(sc, referenceIdentifierField, value); - sc.add( "serializer.writeEndElement();" ); - } - else - { - sc.add( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" - + fieldTagName + "\", serializer );" ); + sc.add("serializer.writeEndElement();"); + } else { + sc.add("write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" + + fieldTagName + "\", serializer );"); } sc.unindent(); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); type = association.getType(); String toType = association.getTo(); boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - sc.add( getValueChecker( type, value, association ) ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.writeStartElement( " + "\"" + fieldTagName + "\" );"); } - sc.add( "for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( toType + " o = (" + toType + ") iter.next();" ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add(toType + " o = (" + toType + ") iter.next();"); - if ( referenceIdentifierField != null ) - { - sc.add( "serializer.writeStartElement( \"" + valuesTagName + "\" );" ); + if (referenceIdentifierField != null) { + sc.add("serializer.writeStartElement( \"" + valuesTagName + "\" );"); - writeElementAttribute( sc, referenceIdentifierField, "o" ); + writeElementAttribute(sc, referenceIdentifierField, "o"); - sc.add( "serializer.writeEndElement();" ); - } - else - { - sc.add( "write" + toType + "( o, \"" + valuesTagName + "\", serializer );" ); + sc.add("serializer.writeEndElement();"); + } else { + sc.add("write" + toType + "( o, \"" + valuesTagName + "\", serializer );"); } - } - else - { - sc.add( toType + " " + singular( uncapitalise( field.getName() ) ) + " = (" + toType - + ") iter.next();" ); - - sc.add( "serializer.writeStartElement( " + "\"" + valuesTagName + "\" );" ); - sc.add( - "serializer.writeCharacters( " + singular( uncapitalise( field.getName() ) ) + " );" ); - sc.add( "serializer.writeEndElement();" ); + } else { + sc.add(toType + " " + singular(uncapitalise(field.getName())) + " = (" + toType + + ") iter.next();"); + + sc.add("serializer.writeStartElement( " + "\"" + valuesTagName + "\" );"); + sc.add("serializer.writeCharacters( " + singular(uncapitalise(field.getName())) + " );"); + sc.add("serializer.writeEndElement();"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "serializer.writeEndElement();" ); + if (wrappedItems) { + sc.add("serializer.writeEndElement();"); } sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.writeStartElement( " + "\"" + fieldTagName + "\" );"); } - sc.add( "for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = (String) iter.next();" ); - - sc.add( "String value = (String) " + value + ".get( key );" ); - - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "serializer.writeStartElement( \"" + singular( associationName ) + "\" );" ); - sc.add( "serializer.writeStartElement( \"key\" );" ); - sc.add( "serializer.writeCharacters( key );" ); - sc.add( "serializer.writeEndElement();" ); - sc.add( "serializer.writeStartElement( \"value\" );" ); - sc.add( "serializer.writeCharacters( value );" ); - sc.add( "serializer.writeEndElement();" ); - sc.add( "serializer.writeEndElement();" ); - } - else - { - sc.add( "serializer.writeStartElement( \"\" + key + \"\" );" ); - sc.add( "serializer.writeCharacters( value );" ); - sc.add( "serializer.writeEndElement();" ); + sc.add("String key = (String) iter.next();"); + + sc.add("String value = (String) " + value + ".get( key );"); + + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("serializer.writeStartElement( \"" + singular(associationName) + "\" );"); + sc.add("serializer.writeStartElement( \"key\" );"); + sc.add("serializer.writeCharacters( key );"); + sc.add("serializer.writeEndElement();"); + sc.add("serializer.writeStartElement( \"value\" );"); + sc.add("serializer.writeCharacters( value );"); + sc.add("serializer.writeEndElement();"); + sc.add("serializer.writeEndElement();"); + } else { + sc.add("serializer.writeStartElement( \"\" + key + \"\" );"); + sc.add("serializer.writeCharacters( value );"); + sc.add("serializer.writeEndElement();"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "serializer.writeEndElement();" ); + if (wrappedItems) { + sc.add("serializer.writeEndElement();"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); + } else { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( "DOM".equals( field.getType() ) ) - { - sc.add( "writeDom( (" + ( domAsXpp3 ? "Xpp3Dom" : "org.w3c.dom.Element" ) + ") " + value - + ", serializer );" ); + if ("DOM".equals(field.getType())) { + sc.add("writeDom( (" + (domAsXpp3 ? "Xpp3Dom" : "org.w3c.dom.Element") + ") " + value + + ", serializer );"); requiresDomSupport = true; - } - else - { - sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" ); - sc.add( - "serializer.writeCharacters( " + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "serializer.writeEndElement();" ); + } else { + sc.add("serializer.writeStartElement( " + "\"" + fieldTagName + "\" );"); + sc.add("serializer.writeCharacters( " + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("serializer.writeEndElement();"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - sc.add( "serializer.writeEndElement();" ); + sc.add("serializer.writeEndElement();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void writeElementAttribute( JSourceCode sc, ModelField referenceIdentifierField, String value ) - { - if ( referenceIdentifierField instanceof DummyIdModelField ) - { - writeIdMapCheck( sc, value, referenceIdentifierField.getName() ); - } - else - { - String v = getValue( referenceIdentifierField.getType(), getFieldValue( value, referenceIdentifierField ), - (XmlFieldMetadata) referenceIdentifierField.getMetadata( XmlFieldMetadata.ID ) ); - sc.add( "serializer.writeAttribute( \"" + referenceIdentifierField.getName() + "\", " + v + " );" ); + private void writeElementAttribute(JSourceCode sc, ModelField referenceIdentifierField, String value) { + if (referenceIdentifierField instanceof DummyIdModelField) { + writeIdMapCheck(sc, value, referenceIdentifierField.getName()); + } else { + String v = getValue( + referenceIdentifierField.getType(), + getFieldValue(value, referenceIdentifierField), + (XmlFieldMetadata) referenceIdentifierField.getMetadata(XmlFieldMetadata.ID)); + sc.add("serializer.writeAttribute( \"" + referenceIdentifierField.getName() + "\", " + v + " );"); } } - private static void writeIdMapCheck( JSourceCode sc, String value, String attributeName ) - { - sc.add( "if ( !idMap.containsKey( " + value + " ) )" ); - sc.add( "{" ); + private static void writeIdMapCheck(JSourceCode sc, String value, String attributeName) { + sc.add("if ( !idMap.containsKey( " + value + " ) )"); + sc.add("{"); sc.indent(); - sc.add( "++curId;" ); - sc.add( "String id = String.valueOf( curId );" ); - sc.add( "idMap.put( " + value + ", id );" ); - sc.add( "serializer.writeAttribute( \"" + attributeName + "\", id );" ); + sc.add("++curId;"); + sc.add("String id = String.valueOf( curId );"); + sc.add("idMap.put( " + value + ", id );"); + sc.add("serializer.writeAttribute( \"" + attributeName + "\", id );"); sc.unindent(); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "serializer.writeAttribute( \"" + attributeName + "\", (String) idMap.get( " + value + " ) );" ); - sc.add( "}" ); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("serializer.writeAttribute( \"" + attributeName + "\", (String) idMap.get( " + value + " ) );"); + sc.add("}"); } - private String getFieldValue( String uncapClassName, ModelField field ) - { - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + private String getFieldValue(String uncapClassName, ModelField field) { + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - return uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + return uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; } - private void createWriteDomMethod( JClass jClass ) - { - if ( domAsXpp3 ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); + private void createWriteDomMethod(JClass jClass) { + if (domAsXpp3) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); } String type = domAsXpp3 ? "Xpp3Dom" : "org.w3c.dom.Element"; - JMethod method = new JMethod( "writeDom" ); + JMethod method = new JMethod("writeDom"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( type ), "dom" ) ); - method.addParameter( new JParameter( new JType( "XMLStreamWriter" ), "serializer" ) ); + method.addParameter(new JParameter(new JType(type), "dom")); + method.addParameter(new JParameter(new JType("XMLStreamWriter"), "serializer")); - method.addException( new JClass( "XMLStreamException" ) ); + method.addException(new JClass("XMLStreamException")); JSourceCode sc = method.getSourceCode(); // start element - sc.add( "serializer.writeStartElement( dom.get" + ( domAsXpp3 ? "Name" : "TagName" ) + "() );" ); + sc.add("serializer.writeStartElement( dom.get" + (domAsXpp3 ? "Name" : "TagName") + "() );"); // attributes - if ( domAsXpp3 ) - { - sc.add( "String[] attributeNames = dom.getAttributeNames();" ); - sc.add( "for ( int i = 0; i < attributeNames.length; i++ )" ); - sc.add( "{" ); - + if (domAsXpp3) { + sc.add("String[] attributeNames = dom.getAttributeNames();"); + sc.add("for ( int i = 0; i < attributeNames.length; i++ )"); + sc.add("{"); + sc.indent(); - sc.add( "String attributeName = attributeNames[i];" ); - sc.add( "serializer.writeAttribute( attributeName, dom.getAttribute( attributeName ) );" ); + sc.add("String attributeName = attributeNames[i];"); + sc.add("serializer.writeAttribute( attributeName, dom.getAttribute( attributeName ) );"); sc.unindent(); - - sc.add( "}" ); - } - else - { - sc.add( "org.w3c.dom.NamedNodeMap attributes = dom.getAttributes();" ); - sc.add( "for ( int i = 0; i < attributes.getLength(); i++ )" ); - sc.add( "{" ); - + + sc.add("}"); + } else { + sc.add("org.w3c.dom.NamedNodeMap attributes = dom.getAttributes();"); + sc.add("for ( int i = 0; i < attributes.getLength(); i++ )"); + sc.add("{"); + sc.indent(); - sc.add( "org.w3c.dom.Node attribute = attributes.item( i );" ); - sc.add( "serializer.writeAttribute( attribute.getNodeName(), attribute.getNodeValue() );" ); + sc.add("org.w3c.dom.Node attribute = attributes.item( i );"); + sc.add("serializer.writeAttribute( attribute.getNodeName(), attribute.getNodeValue() );"); sc.unindent(); - - sc.add( "}" ); + + sc.add("}"); } // child nodes & text - if ( domAsXpp3 ) - { - sc.add( "Xpp3Dom[] children = dom.getChildren();" ); - sc.add( "for ( int i = 0; i < children.length; i++ )" ); - sc.add( "{" ); - sc.addIndented( "writeDom( children[i], serializer );" ); - sc.add( "}" ); - - sc.add( "String value = dom.getValue();" ); - sc.add( "if ( value != null )" ); - sc.add( "{" ); - sc.addIndented( "serializer.writeCharacters( value );" ); - sc.add( "}" ); - } - else - { - sc.add( "org.w3c.dom.NodeList children = dom.getChildNodes();" ); - sc.add( "for ( int i = 0; i < children.getLength(); i++ )" ); - sc.add( "{" ); + if (domAsXpp3) { + sc.add("Xpp3Dom[] children = dom.getChildren();"); + sc.add("for ( int i = 0; i < children.length; i++ )"); + sc.add("{"); + sc.addIndented("writeDom( children[i], serializer );"); + sc.add("}"); + + sc.add("String value = dom.getValue();"); + sc.add("if ( value != null )"); + sc.add("{"); + sc.addIndented("serializer.writeCharacters( value );"); + sc.add("}"); + } else { + sc.add("org.w3c.dom.NodeList children = dom.getChildNodes();"); + sc.add("for ( int i = 0; i < children.getLength(); i++ )"); + sc.add("{"); sc.indent(); - sc.add( "org.w3c.dom.Node node = children.item( i );" ); - sc.add( "if ( node instanceof org.w3c.dom.Element)" ); - sc.add( "{" ); - sc.addIndented( "writeDom( (org.w3c.dom.Element) children.item( i ), serializer );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "serializer.writeCharacters( node.getTextContent() );" ); - sc.add( "}" ); + sc.add("org.w3c.dom.Node node = children.item( i );"); + sc.add("if ( node instanceof org.w3c.dom.Element)"); + sc.add("{"); + sc.addIndented("writeDom( (org.w3c.dom.Element) children.item( i ), serializer );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("serializer.writeCharacters( node.getTextContent() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "serializer.writeEndElement();" ); + sc.add("serializer.writeEndElement();"); - jClass.addMethod( method ); + jClass.addMethod(method); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/AbstractStaxGeneratorTestCase.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/AbstractStaxGeneratorTestCase.java index b7ef4f189..7d548f560 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/AbstractStaxGeneratorTestCase.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/AbstractStaxGeneratorTestCase.java @@ -22,67 +22,56 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; import org.codehaus.plexus.util.StringUtils; -import java.util.Properties; - -public abstract class AbstractStaxGeneratorTestCase - extends AbstractModelloJavaGeneratorTest -{ +public abstract class AbstractStaxGeneratorTestCase extends AbstractModelloJavaGeneratorTest { protected ModelloCore modello; - protected AbstractStaxGeneratorTestCase( String name ) - { - super( name ); + protected AbstractStaxGeneratorTestCase(String name) { + super(name); } - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - modello = (ModelloCore) lookup( ModelloCore.ROLE ); + modello = (ModelloCore) lookup(ModelloCore.ROLE); } - protected void verifyModel( Model model, String className ) - throws Exception - { - verifyModel( model, className, null ); + protected void verifyModel(Model model, String className) throws Exception { + verifyModel(model, className, null); } - protected void verifyModel( Model model, String className, String[] versions ) - throws Exception - { - Properties parameters = getModelloParameters( "4.0.0" ); + protected void verifyModel(Model model, String className, String[] versions) throws Exception { + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-writer", parameters ); - modello.generate( model, "stax-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-writer", parameters); + modello.generate(model, "stax-reader", parameters); - if ( versions != null && versions.length > 0 ) - { - parameters.setProperty( ModelloParameterConstants.ALL_VERSIONS, StringUtils.join( versions, "," ) ); + if (versions != null && versions.length > 0) { + parameters.setProperty(ModelloParameterConstants.ALL_VERSIONS, StringUtils.join(versions, ",")); - for ( String version : versions ) - { - parameters.setProperty( ModelloParameterConstants.VERSION, version ); - parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( true ) ); + for (String version : versions) { + parameters.setProperty(ModelloParameterConstants.VERSION, version); + parameters.setProperty(ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString(true)); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-writer", parameters ); - modello.generate( model, "stax-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-writer", parameters); + modello.generate(model, "stax-reader", parameters); } } - addDependency( "org.codehaus.woodstox", "stax2-api" ); - addDependency( "com.fasterxml.woodstox", "woodstox-core" ); + addDependency("org.codehaus.woodstox", "stax2-api"); + addDependency("com.fasterxml.woodstox", "woodstox-core"); compileGeneratedSources(); - verifyCompiledGeneratedSources( className ); + verifyCompiledGeneratedSources(className); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/BooleanTypeStaxGeneratorTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/BooleanTypeStaxGeneratorTest.java index f0020937a..d3acbda7d 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/BooleanTypeStaxGeneratorTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/BooleanTypeStaxGeneratorTest.java @@ -25,27 +25,22 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -public class BooleanTypeStaxGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public BooleanTypeStaxGeneratorTest() - { - super( "testBooleanType" ); +public class BooleanTypeStaxGeneratorTest extends AbstractModelloJavaGeneratorTest { + public BooleanTypeStaxGeneratorTest() { + super("testBooleanType"); } - public void testBooleanType() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testBooleanType() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/boolean.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/boolean.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); + Properties parameters = getModelloParameters("1.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-reader", parameters ); - modello.generate( model, "stax-writer", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-reader", parameters); + modello.generate(model, "stax-writer", parameters); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxDomGeneratorTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxDomGeneratorTest.java index 361d02f51..8eeee0618 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxDomGeneratorTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxDomGeneratorTest.java @@ -22,46 +22,41 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesStaxDomGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesStaxDomGeneratorTest() - { - super( "features-dom" ); +public class FeaturesStaxDomGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesStaxDomGeneratorTest() { + super("features-dom"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); - parameters.put( "modello.dom.xpp3", "false" ); + Properties parameters = getModelloParameters("1.0.0"); + parameters.put("modello.dom.xpp3", "false"); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-writer", parameters ); - modello.generate( model, "stax-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-writer", parameters); + modello.generate(model, "stax-reader", parameters); - addDependency( "org.codehaus.woodstox", "stax2-api" ); - addDependency( "com.fasterxml.woodstox", "woodstox-core" ); - addDependency( "org.xmlunit", "xmlunit-core" ); + addDependency("org.codehaus.woodstox", "stax2-api"); + addDependency("com.fasterxml.woodstox", "woodstox-core"); + addDependency("org.xmlunit", "xmlunit-core"); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); // TODO: see why without this, version system property is set to "2.4.1" value after verify - System.setProperty( "version", getModelloVersion() ); + System.setProperty("version", getModelloVersion()); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.stax.StaxFeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.stax.StaxFeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxGeneratorTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxGeneratorTest.java index 2dbf1780d..bf422122d 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxGeneratorTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/FeaturesStaxGeneratorTest.java @@ -22,45 +22,40 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesStaxGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesStaxGeneratorTest() - { - super( "features" ); +public class FeaturesStaxGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesStaxGeneratorTest() { + super("features"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-writer", parameters ); - modello.generate( model, "stax-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-writer", parameters); + modello.generate(model, "stax-reader", parameters); - addDependency( "org.codehaus.woodstox", "stax2-api" ); - addDependency( "com.fasterxml.woodstox", "woodstox-core" ); - addDependency( "org.xmlunit", "xmlunit-core" ); + addDependency("org.codehaus.woodstox", "stax2-api"); + addDependency("com.fasterxml.woodstox", "woodstox-core"); + addDependency("org.xmlunit", "xmlunit-core"); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); // TODO: see why without this, version system property is set to "2.4.1" value after verify - System.setProperty( "version", getModelloVersion() ); + System.setProperty("version", getModelloVersion()); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.stax.StaxFeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.stax.StaxFeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/NoAdderStaxGeneratorTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/NoAdderStaxGeneratorTest.java index 57d2087c7..739b6d3c5 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/NoAdderStaxGeneratorTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/NoAdderStaxGeneratorTest.java @@ -25,26 +25,21 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -public class NoAdderStaxGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public NoAdderStaxGeneratorTest() - { - super( "testNoAdder" ); +public class NoAdderStaxGeneratorTest extends AbstractModelloJavaGeneratorTest { + public NoAdderStaxGeneratorTest() { + super("testNoAdder"); } - public void testNoAdder() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testNoAdder() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/noAdder.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/noAdder.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "stax-reader", parameters ); - modello.generate( model, "stax-writer", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "stax-reader", parameters); + modello.generate(model, "stax-writer", parameters); compileGeneratedSources(); } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorPartsTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorPartsTest.java index 73c9bc1d2..c65513019 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorPartsTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorPartsTest.java @@ -22,38 +22,31 @@ * SOFTWARE. */ +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.Version; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** */ -public class StaxGeneratorPartsTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorPartsTest() - throws ComponentLookupException - { - super( "stax-parts" ); +public class StaxGeneratorPartsTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorPartsTest() throws ComponentLookupException { + super("stax-parts"); } - public void testStaxReaderParts() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/parts.mdo" ) ); + public void testStaxReaderParts() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/parts.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 12, classesList.size() ); + assertEquals(12, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierParts" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierParts"); } - } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorTest.java index 3f3c44e22..048566e6f 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorTest.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.ModelField; @@ -29,56 +31,48 @@ import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class StaxGeneratorTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorTest() - throws ComponentLookupException - { - super( "stax" ); +public class StaxGeneratorTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorTest() throws ComponentLookupException { + super("stax"); } - public void testStaxGenerator() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + public void testStaxGenerator() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 27, classesList.size() ); + assertEquals(27, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifier" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifier"); } } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInFieldTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInFieldTest.java index 1d51ed922..757665844 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInFieldTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInFieldTest.java @@ -1,39 +1,32 @@ package org.codehaus.modello.generator.xml.stax; +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.Version; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class StaxGeneratorVersionInFieldTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorVersionInFieldTest() - throws ComponentLookupException - { - super( "stax-version-in-field" ); +public class StaxGeneratorVersionInFieldTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorVersionInFieldTest() throws ComponentLookupException { + super("stax-version-in-field"); } - public void testStaxReaderVersionInField() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/version-in-field.mdo" ) ); + public void testStaxReaderVersionInField() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/version-in-field.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 1, classesList.size() ); + assertEquals(1, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionInField" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionInField"); } - } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInNamespaceTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInNamespaceTest.java index aa813a944..9eeccc77a 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInNamespaceTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionInNamespaceTest.java @@ -1,39 +1,32 @@ package org.codehaus.modello.generator.xml.stax; +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.Version; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class StaxGeneratorVersionInNamespaceTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorVersionInNamespaceTest() - throws ComponentLookupException - { - super( "stax-version-in-namespace" ); +public class StaxGeneratorVersionInNamespaceTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorVersionInNamespaceTest() throws ComponentLookupException { + super("stax-version-in-namespace"); } - public void testStaxReaderVersionInField() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/version-in-namespace.mdo" ) ); + public void testStaxReaderVersionInField() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/version-in-namespace.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 1, classesList.size() ); + assertEquals(1, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionInNamespace" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionInNamespace"); } - } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionReaderDelegateTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionReaderDelegateTest.java index 6fba27ad8..b478213d9 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionReaderDelegateTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorVersionReaderDelegateTest.java @@ -27,22 +27,16 @@ /** */ -public class StaxGeneratorVersionReaderDelegateTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorVersionReaderDelegateTest() - throws ComponentLookupException - { - super( "stax-version-reader-delegate" ); +public class StaxGeneratorVersionReaderDelegateTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorVersionReaderDelegateTest() throws ComponentLookupException { + super("stax-version-reader-delegate"); } - public void testStaxReaderVersionInField() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/version-in-namespace.mdo" ) ); + public void testStaxReaderVersionInField() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/version-in-namespace.mdo")); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionReaderDelegate", - new String[] { "4.0.0", "4.0.1" } ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierVersionReaderDelegate", new String[] { + "4.0.0", "4.0.1" + }); } - } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionInNamespaceTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionInNamespaceTest.java index 6fc6b9d26..ffd2d1738 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionInNamespaceTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionInNamespaceTest.java @@ -1,39 +1,32 @@ package org.codehaus.modello.generator.xml.stax; +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.Version; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class StaxGeneratorWrongVersionInNamespaceTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorWrongVersionInNamespaceTest() - throws ComponentLookupException - { - super( "stax-wrong-version-in-namespace" ); +public class StaxGeneratorWrongVersionInNamespaceTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorWrongVersionInNamespaceTest() throws ComponentLookupException { + super("stax-wrong-version-in-namespace"); } - public void testStaxReaderVersionInField() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/version-in-namespace.mdo" ) ); + public void testStaxReaderVersionInField() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/version-in-namespace.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 1, classesList.size() ); + assertEquals(1, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierWrongVersionNamespace" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierWrongVersionNamespace"); } - } diff --git a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionTest.java b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionTest.java index b97151196..f3d3b83e1 100644 --- a/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionTest.java +++ b/modello-plugins/modello-plugin-stax/src/test/java/org/codehaus/modello/generator/xml/stax/StaxGeneratorWrongVersionTest.java @@ -1,39 +1,32 @@ package org.codehaus.modello.generator.xml.stax; +import java.util.List; + import org.codehaus.modello.model.Model; import org.codehaus.modello.model.ModelClass; import org.codehaus.modello.model.Version; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.util.List; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class StaxGeneratorWrongVersionTest - extends AbstractStaxGeneratorTestCase -{ - public StaxGeneratorWrongVersionTest() - throws ComponentLookupException - { - super( "stax-wrong-version" ); +public class StaxGeneratorWrongVersionTest extends AbstractStaxGeneratorTestCase { + public StaxGeneratorWrongVersionTest() throws ComponentLookupException { + super("stax-wrong-version"); } - public void testStaxReaderVersionInField() - throws Throwable - { - Model model = modello.loadModel( getXmlResourceReader( "/version-in-field.mdo" ) ); + public void testStaxReaderVersionInField() throws Throwable { + Model model = modello.loadModel(getXmlResourceReader("/version-in-field.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 1, classesList.size() ); + assertEquals(1, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - verifyModel( model, "org.codehaus.modello.generator.xml.stax.StaxVerifierWrongVersion" ); + verifyModel(model, "org.codehaus.modello.generator.xml.stax.StaxVerifierWrongVersion"); } - } diff --git a/modello-plugins/modello-plugin-velocity/pom.xml b/modello-plugins/modello-plugin-velocity/pom.xml index 723d9a30e..725ae7ea0 100644 --- a/modello-plugins/modello-plugin-velocity/pom.xml +++ b/modello-plugins/modello-plugin-velocity/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-velocity Modello Velocity Plugin - - Modello Velocity Plugin generates files from the Modello model using Velocity templates. - + Modello Velocity Plugin generates files from the Modello model using Velocity templates. diff --git a/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/Helper.java b/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/Helper.java index 6267c5478..8f7609f66 100644 --- a/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/Helper.java +++ b/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/Helper.java @@ -44,50 +44,44 @@ * {@code #set ( $ancestors = $Helper.ancestors( $class ) )} *

*/ -@SuppressWarnings( "unused" ) -public class Helper -{ +@SuppressWarnings("unused") +public class Helper { private final Version version; - public Helper( Version version ) - { + public Helper(Version version) { this.version = version; } /** * Returns the capitalised version of the given string. */ - public String capitalise( String str ) - { - return StringUtils.isEmpty( str ) ? str : Character.toTitleCase( str.charAt( 0 ) ) + str.substring( 1 ); + public String capitalise(String str) { + return StringUtils.isEmpty(str) ? str : Character.toTitleCase(str.charAt(0)) + str.substring(1); } /** * Returns the uncapitalised version of the given string. */ - public String uncapitalise( String str ) - { - return StringUtils.isEmpty( str ) ? str : Character.toLowerCase( str.charAt( 0 ) ) + str.substring( 1 ); + public String uncapitalise(String str) { + return StringUtils.isEmpty(str) ? str : Character.toLowerCase(str.charAt(0)) + str.substring(1); } /** * Returns the singular name for the given string. */ - public String singular( String str ) - { - return AbstractModelloGenerator.singular( str ); + public String singular(String str) { + return AbstractModelloGenerator.singular(str); } /** * Returns the list of ancestors for the given {@code ModelClass}. */ - public List ancestors( ModelClass clazz ) - { + public List ancestors(ModelClass clazz) { List ancestors = new ArrayList<>(); - for ( ModelClass cl = clazz; cl != null; cl = cl.getSuperClass() != null - ? cl.getModel().getClass( cl.getSuperClass(), version ) : null ) - { - ancestors.add( 0, cl ); + for (ModelClass cl = clazz; + cl != null; + cl = cl.getSuperClass() != null ? cl.getModel().getClass(cl.getSuperClass(), version) : null) { + ancestors.add(0, cl); } return ancestors; } @@ -95,34 +89,29 @@ public List ancestors( ModelClass clazz ) /** * Returns the {@code XmlClassMetadata} for the given {@code ModelClass}. */ - public XmlClassMetadata xmlClassMetadata( ModelClass clazz ) - { - return (XmlClassMetadata) clazz.getMetadata( XmlClassMetadata.ID ); + public XmlClassMetadata xmlClassMetadata(ModelClass clazz) { + return (XmlClassMetadata) clazz.getMetadata(XmlClassMetadata.ID); } /** * Returns the {@code XmlFieldMetadata} for the given {@code ModelField}. */ - public XmlFieldMetadata xmlFieldMetadata( ModelField field ) - { - return (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + public XmlFieldMetadata xmlFieldMetadata(ModelField field) { + return (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); } /** * Returns the {@code XmlAssociationMetadata} for the given {@code ModelField}. */ - public XmlAssociationMetadata xmAssociationMetadata( ModelField field ) - { - return (XmlAssociationMetadata) ( (ModelAssociation) field ) - .getAssociationMetadata( XmlAssociationMetadata.ID ); + public XmlAssociationMetadata xmAssociationMetadata(ModelField field) { + return (XmlAssociationMetadata) ((ModelAssociation) field).getAssociationMetadata(XmlAssociationMetadata.ID); } /** * Checks if the given {@code ModelField} is a flat item. */ - public boolean isFlatItems( ModelField field ) - { - return field instanceof ModelAssociation && xmAssociationMetadata( field ).isFlatItems(); + public boolean isFlatItems(ModelField field) { + return field instanceof ModelAssociation && xmAssociationMetadata(field).isFlatItems(); } /** @@ -130,62 +119,50 @@ public boolean isFlatItems( ModelField field ) * The list will contain all fields defined on the class and on its parents, * excluding any field flagged as being xml transient. */ - public List xmlFields( ModelClass modelClass ) - { + public List xmlFields(ModelClass modelClass) { List classes = new ArrayList<>(); // get the full inheritance - while ( modelClass != null ) - { - classes.add( modelClass ); + while (modelClass != null) { + classes.add(modelClass); String superClass = modelClass.getSuperClass(); - if ( superClass != null ) - { + if (superClass != null) { // superClass can be located outside (not generated by modello) - modelClass = modelClass.getModel().getClass( superClass, version, true ); - } - else - { + modelClass = modelClass.getModel().getClass(superClass, version, true); + } else { modelClass = null; } } List fields = new ArrayList<>(); - for ( int i = classes.size() - 1; i >= 0; i-- ) - { - modelClass = classes.get( i ); + for (int i = classes.size() - 1; i >= 0; i--) { + modelClass = classes.get(i); Iterator parentIter = fields.iterator(); fields = new ArrayList<>(); - for ( ModelField field : modelClass.getFields( version ) ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); - if ( xmlFieldMetadata.isTransient() ) - { + for (ModelField field : modelClass.getFields(version)) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); + if (xmlFieldMetadata.isTransient()) { // just ignore xml.transient fields continue; } - if ( xmlFieldMetadata.getInsertParentFieldsUpTo() != null ) - { + if (xmlFieldMetadata.getInsertParentFieldsUpTo() != null) { // insert fields from parent up to the specified field boolean found = false; - while ( !found && parentIter.hasNext() ) - { + while (!found && parentIter.hasNext()) { ModelField parentField = parentIter.next(); - fields.add( parentField ); - found = parentField.getName().equals( xmlFieldMetadata.getInsertParentFieldsUpTo() ); + fields.add(parentField); + found = parentField.getName().equals(xmlFieldMetadata.getInsertParentFieldsUpTo()); } - if ( !found ) - { + if (!found) { // interParentFieldsUpTo not found - throw new ModelloRuntimeException( "parent field not found: class " + throw new ModelloRuntimeException("parent field not found: class " + modelClass.getName() + " xml.insertParentFieldUpTo='" - + xmlFieldMetadata.getInsertParentFieldsUpTo() + "'" ); + + xmlFieldMetadata.getInsertParentFieldsUpTo() + "'"); } } - fields.add( field ); + fields.add(field); } // add every remaining fields from parent class - while ( parentIter.hasNext() ) - { - fields.add( parentIter.next() ); + while (parentIter.hasNext()) { + fields.add(parentIter.next()); } } return fields; diff --git a/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/VelocityGenerator.java b/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/VelocityGenerator.java index 219b6ba03..a785e0fc0 100644 --- a/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/VelocityGenerator.java +++ b/modello-plugins/modello-plugin-velocity/src/main/java/org/codehaus/modello/plugin/velocity/VelocityGenerator.java @@ -41,10 +41,8 @@ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.io.CachingWriter; -@Component( role = ModelloGenerator.class, hint = "velocity" ) -public class VelocityGenerator - extends AbstractModelloGenerator -{ +@Component(role = ModelloGenerator.class, hint = "velocity") +public class VelocityGenerator extends AbstractModelloGenerator { public static final String VELOCITY_BASEDIR = "modello.velocity.basedir"; public static final String VELOCITY_TEMPLATES = "modello.velocity.templates"; @@ -54,121 +52,94 @@ public class VelocityGenerator public static final String MODELLO_VELOCITY_OUTPUT = "#MODELLO-VELOCITY#SAVE-OUTPUT-TO "; @Override - public void generate( Model model, Properties parameters ) throws ModelloException - { - try - { - Map params = ( Map ) Objects.requireNonNull( parameters.get( VELOCITY_PARAMETERS ) ); - String templates = getParameter( parameters, VELOCITY_TEMPLATES ); - String output = getParameter( parameters, ModelloParameterConstants.OUTPUT_DIRECTORY ); + public void generate(Model model, Properties parameters) throws ModelloException { + try { + Map params = (Map) Objects.requireNonNull(parameters.get(VELOCITY_PARAMETERS)); + String templates = getParameter(parameters, VELOCITY_TEMPLATES); + String output = getParameter(parameters, ModelloParameterConstants.OUTPUT_DIRECTORY); Properties props = new Properties(); - props.put( "resource.loader.file.path", getParameter( parameters, VELOCITY_BASEDIR ) ); + props.put("resource.loader.file.path", getParameter(parameters, VELOCITY_BASEDIR)); RuntimeInstance velocity = new RuntimeInstance(); - velocity.init( props ); + velocity.init(props); VelocityContext context = new VelocityContext(); - for ( Map.Entry prop : parameters.entrySet() ) - { - context.put( prop.getKey().toString(), prop.getValue() ); + for (Map.Entry prop : parameters.entrySet()) { + context.put(prop.getKey().toString(), prop.getValue()); } - for ( Map.Entry prop : params.entrySet() ) - { - context.put( prop.getKey(), prop.getValue() ); + for (Map.Entry prop : params.entrySet()) { + context.put(prop.getKey(), prop.getValue()); } - Version version = new Version( getParameter( parameters, ModelloParameterConstants.VERSION ) ); - context.put( "version", version ); - context.put( "model", model ); - context.put( "Helper", new Helper( version ) ); - - for ( String templatePath : templates.split( "," ) ) - { - Template template = velocity.getTemplate( templatePath ); - context.put( "template", templatePath ); - - try ( Writer w = new RedirectingWriter( Paths.get( output ) ) ) - { - template.merge( context, w ); + Version version = new Version(getParameter(parameters, ModelloParameterConstants.VERSION)); + context.put("version", version); + context.put("model", model); + context.put("Helper", new Helper(version)); + + for (String templatePath : templates.split(",")) { + Template template = velocity.getTemplate(templatePath); + context.put("template", templatePath); + + try (Writer w = new RedirectingWriter(Paths.get(output))) { + template.merge(context, w); } } + } catch (Exception e) { + throw new ModelloException("Unable to run velocity template", e); } - catch ( Exception e ) - { - throw new ModelloException( "Unable to run velocity template", e ); - } - } - static class RedirectingWriter extends Writer - { + static class RedirectingWriter extends Writer { Path dir; StringBuilder sb = new StringBuilder(); Writer current; - RedirectingWriter( Path dir ) - { + RedirectingWriter(Path dir) { this.dir = dir; } @Override - public void write( char[] cbuf, int off, int len ) throws IOException - { - for ( int i = 0; i < len; i++ ) - { - if ( cbuf[ off + i ] == '\n' ) - { - if ( sb.length() > 0 && sb.charAt( sb.length() - 1 ) == '\r' ) - { - sb.setLength( sb.length() - 1 ); + public void write(char[] cbuf, int off, int len) throws IOException { + for (int i = 0; i < len; i++) { + if (cbuf[off + i] == '\n') { + if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\r') { + sb.setLength(sb.length() - 1); } - writeLine( sb.toString() ); - sb.setLength( 0 ); - } - else - { - sb.append( cbuf[ off + i ] ); + writeLine(sb.toString()); + sb.setLength(0); + } else { + sb.append(cbuf[off + i]); } } } - protected void writeLine( String line ) throws IOException - { - if ( line.startsWith( MODELLO_VELOCITY_OUTPUT ) ) - { - String file = line.substring( MODELLO_VELOCITY_OUTPUT.length() ); - if ( current != null ) - { + protected void writeLine(String line) throws IOException { + if (line.startsWith(MODELLO_VELOCITY_OUTPUT)) { + String file = line.substring(MODELLO_VELOCITY_OUTPUT.length()); + if (current != null) { current.close(); } - Path out = dir.resolve( file ); - Files.createDirectories( out.getParent() ); - current = new CachingWriter( out, StandardCharsets.UTF_8 ); - } - else if ( current != null ) - { - current.write( line ); - current.write( "\n" ); + Path out = dir.resolve(file); + Files.createDirectories(out.getParent()); + current = new CachingWriter(out, StandardCharsets.UTF_8); + } else if (current != null) { + current.write(line); + current.write("\n"); } } @Override - public void flush() throws IOException - { - if ( current != null ) - { + public void flush() throws IOException { + if (current != null) { current.flush(); } } @Override - public void close() throws IOException - { - if ( current != null ) - { + public void close() throws IOException { + if (current != null) { current.close(); current = null; } } } - } diff --git a/modello-plugins/modello-plugin-xdoc/pom.xml b/modello-plugins/modello-plugin-xdoc/pom.xml index 651dbd5a0..9ec1ff1d2 100644 --- a/modello-plugins/modello-plugin-xdoc/pom.xml +++ b/modello-plugins/modello-plugin-xdoc/pom.xml @@ -1,18 +1,16 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-xdoc Modello XDOC Plugin - - Modello XDOC Plugin generates model documentation using xdoc markup to be included in a Maven-generated reporting - site. - + Modello XDOC Plugin generates model documentation using xdoc markup to be included in a Maven-generated reporting + site. diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java index 160dc1834..b52ca180d 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/XdocGenerator.java @@ -65,102 +65,88 @@ * @author Jason van Zyl * @author Emmanuel Venisse */ -@Component( role = ModelloGenerator.class, hint = "xdoc" ) -public class XdocGenerator - extends AbstractXmlGenerator -{ - private static final VersionRange DEFAULT_VERSION_RANGE = new VersionRange( "0.0.0+" ); +@Component(role = ModelloGenerator.class, hint = "xdoc") +public class XdocGenerator extends AbstractXmlGenerator { + private static final VersionRange DEFAULT_VERSION_RANGE = new VersionRange("0.0.0+"); private Version firstVersion = DEFAULT_VERSION_RANGE.getFromVersion(); private Version version = DEFAULT_VERSION_RANGE.getFromVersion(); - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); - if ( parameters.getProperty( ModelloParameterConstants.FIRST_VERSION ) != null ) - { - firstVersion = new Version( parameters.getProperty( ModelloParameterConstants.FIRST_VERSION ) ); + if (parameters.getProperty(ModelloParameterConstants.FIRST_VERSION) != null) { + firstVersion = new Version(parameters.getProperty(ModelloParameterConstants.FIRST_VERSION)); } - if ( parameters.getProperty( ModelloParameterConstants.VERSION ) != null ) - { - version = new Version( parameters.getProperty( ModelloParameterConstants.VERSION ) ); + if (parameters.getProperty(ModelloParameterConstants.VERSION) != null) { + version = new Version(parameters.getProperty(ModelloParameterConstants.VERSION)); } - try - { - generateXdoc( parameters ); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating XDoc.", ex ); + try { + generateXdoc(parameters); + } catch (IOException ex) { + throw new ModelloException("Exception while generating XDoc.", ex); } } - private void generateXdoc( Properties parameters ) - throws IOException - { + private void generateXdoc(Properties parameters) throws IOException { Model objectModel = getModel(); File directory = getOutputDirectory(); - if ( isPackageWithVersion() ) - { - directory = new File( directory, getGeneratedVersion().toString() ); + if (isPackageWithVersion()) { + directory = new File(directory, getGeneratedVersion().toString()); } - if ( !directory.exists() ) - { + if (!directory.exists()) { directory.mkdirs(); } // we assume parameters not null - String xdocFileName = parameters.getProperty( ModelloParameterConstants.OUTPUT_XDOC_FILE_NAME ); + String xdocFileName = parameters.getProperty(ModelloParameterConstants.OUTPUT_XDOC_FILE_NAME); - File f = new File( directory, objectModel.getId() + ".xml" ); + File f = new File(directory, objectModel.getId() + ".xml"); - if ( xdocFileName != null ) - { - f = new File( directory, xdocFileName ); + if (xdocFileName != null) { + f = new File(directory, xdocFileName); } - Writer writer = WriterFactory.newXmlWriter( f ); + Writer writer = WriterFactory.newXmlWriter(f); - XMLWriter w = new PrettyPrintXMLWriter( writer ); + XMLWriter w = new PrettyPrintXMLWriter(writer); - writer.write( "\n" ); + writer.write("\n"); - initHeader( w ); + initHeader(w); - w.startElement( "document" ); + w.startElement("document"); - w.startElement( "properties" ); + w.startElement("properties"); - writeTextElement( w, "title", objectModel.getName() ); + writeTextElement(w, "title", objectModel.getName()); w.endElement(); // Body - w.startElement( "body" ); + w.startElement("body"); - w.startElement( "section" ); + w.startElement("section"); - w.addAttribute( "name", objectModel.getName() ); + w.addAttribute("name", objectModel.getName()); - writeMarkupElement( w, "p", getDescription( objectModel ) ); + writeMarkupElement(w, "p", getDescription(objectModel)); // XML representation of the model with links - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - writeMarkupElement( w, "source", "\n" + getModelXmlDescriptor( root ) ); + writeMarkupElement(w, "source", "\n" + getModelXmlDescriptor(root)); // Element descriptors // Traverse from root so "abstract" models aren't included - writeModelDescriptor( w, root ); + writeModelDescriptor(w, root); w.endElement(); @@ -180,13 +166,12 @@ private void generateXdoc( Properties parameters ) * @param modelClass the model class, that eventually can have customized anchor name * @return the corresponding anchor name */ - private String getAnchorName( String tagName, ModelClass modelClass ) - { - XdocClassMetadata xdocClassMetadata = (XdocClassMetadata) modelClass.getMetadata( XdocClassMetadata.ID ); + private String getAnchorName(String tagName, ModelClass modelClass) { + XdocClassMetadata xdocClassMetadata = (XdocClassMetadata) modelClass.getMetadata(XdocClassMetadata.ID); String anchorName = xdocClassMetadata.getAnchorName(); - return "class_" + ( anchorName == null ? tagName : anchorName ); + return "class_" + (anchorName == null ? tagName : anchorName); } /** @@ -195,9 +180,8 @@ private String getAnchorName( String tagName, ModelClass modelClass ) * @param w the output writer * @param rootModelClass the root class of the model */ - private void writeModelDescriptor( XMLWriter w, ModelClass rootModelClass ) - { - writeElementDescriptor( w, rootModelClass, null, new HashSet<>(), new HashMap<>() ); + private void writeModelDescriptor(XMLWriter w, ModelClass rootModelClass) { + writeElementDescriptor(w, rootModelClass, null, new HashSet<>(), new HashMap<>()); } /** @@ -209,86 +193,80 @@ private void writeModelDescriptor( XMLWriter w, ModelClass rootModelClass ) * @param writtenIds set of data already written ids * @param writtenAnchors map of already written anchors with corresponding ids */ - private void writeElementDescriptor( XMLWriter w, ModelClass modelClass, ModelAssociation association, - Set writtenIds, Map writtenAnchors ) - { - String tagName = resolveTagName( modelClass, association ); - - String id = getId( tagName, modelClass ); - if ( writtenIds.contains( id ) ) - { + private void writeElementDescriptor( + XMLWriter w, + ModelClass modelClass, + ModelAssociation association, + Set writtenIds, + Map writtenAnchors) { + String tagName = resolveTagName(modelClass, association); + + String id = getId(tagName, modelClass); + if (writtenIds.contains(id)) { // tag already written for this model class accessed as this tag name return; } - writtenIds.add( id ); + writtenIds.add(id); - String anchorName = getAnchorName( tagName, modelClass ); - if ( writtenAnchors.containsKey( anchorName ) ) - { + String anchorName = getAnchorName(tagName, modelClass); + if (writtenAnchors.containsKey(anchorName)) { // TODO use logging API? - System.out.println( "[warn] model class " + id + " with tagName " + tagName + " gets duplicate anchorName " - + anchorName + ", conflicting with model class " + writtenAnchors.get( anchorName ) ); - } - else - { - writtenAnchors.put( anchorName, id ); + System.out.println("[warn] model class " + id + " with tagName " + tagName + " gets duplicate anchorName " + + anchorName + ", conflicting with model class " + writtenAnchors.get(anchorName)); + } else { + writtenAnchors.put(anchorName, id); } - w.startElement( "a" ); + w.startElement("a"); - w.addAttribute( "name", anchorName ); + w.addAttribute("name", anchorName); w.endElement(); - w.startElement( "subsection" ); + w.startElement("subsection"); - w.addAttribute( "name", tagName ); + w.addAttribute("name", tagName); - writeMarkupElement( w, "p", getDescription( modelClass ) ); + writeMarkupElement(w, "p", getDescription(modelClass)); - List elementFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List elementFields = getFieldsForXml(modelClass, getGeneratedVersion()); - ModelField contentField = getContentField( elementFields ); + ModelField contentField = getContentField(elementFields); - if ( contentField != null ) - { + if (contentField != null) { // this model class has a Content field - w.startElement( "p" ); + w.startElement("p"); - writeTextElement( w, "b", "Element Content: " ); + writeTextElement(w, "b", "Element Content: "); - w.writeMarkup( getDescription( contentField ) ); + w.writeMarkup(getDescription(contentField)); w.endElement(); } - List attributeFields = getXmlAttributeFields( elementFields ); + List attributeFields = getXmlAttributeFields(elementFields); - elementFields.removeAll( attributeFields ); + elementFields.removeAll(attributeFields); - writeFieldsTable( w, attributeFields, false ); // write attributes - writeFieldsTable( w, elementFields, true ); // write elements + writeFieldsTable(w, attributeFields, false); // write attributes + writeFieldsTable(w, elementFields, true); // write elements w.endElement(); // check every fields that are inner associations to write their element descriptor - for ( ModelField f : elementFields ) - { - if ( isInnerAssociation( f ) ) - { + for (ModelField f : elementFields) { + if (isInnerAssociation(f)) { ModelAssociation assoc = (ModelAssociation) f; - ModelClass fieldModelClass = getModel().getClass( assoc.getTo(), getGeneratedVersion() ); + ModelClass fieldModelClass = getModel().getClass(assoc.getTo(), getGeneratedVersion()); - if ( !writtenIds.contains( getId( resolveTagName( fieldModelClass, assoc ), fieldModelClass ) ) ) - { - writeElementDescriptor( w, fieldModelClass, assoc, writtenIds, writtenAnchors ); + if (!writtenIds.contains(getId(resolveTagName(fieldModelClass, assoc), fieldModelClass))) { + writeElementDescriptor(w, fieldModelClass, assoc, writtenIds, writtenAnchors); } } } } - private String getId( String tagName, ModelClass modelClass ) - { + private String getId(String tagName, ModelClass modelClass) { return tagName + '/' + modelClass.getPackageName() + '.' + modelClass.getName(); } @@ -299,106 +277,87 @@ private String getId( String tagName, ModelClass modelClass ) * @param fields the fields to add in the table * @param elementFields true if fields are elements, false if fields are attributes */ - private void writeFieldsTable( XMLWriter w, List fields, boolean elementFields ) - { - if ( fields == null || fields.isEmpty() ) - { + private void writeFieldsTable(XMLWriter w, List fields, boolean elementFields) { + if (fields == null || fields.isEmpty()) { // skip empty table return; } // skip if only one element field with xml.content == true - if ( elementFields && ( fields.size() == 1 ) && hasContentField( fields ) ) - { + if (elementFields && (fields.size() == 1) && hasContentField(fields)) { return; } - w.startElement( "table" ); + w.startElement("table"); - w.startElement( "tr" ); + w.startElement("tr"); - writeTextElement( w, "th", elementFields ? "Element" : "Attribute" ); + writeTextElement(w, "th", elementFields ? "Element" : "Attribute"); - writeTextElement( w, "th", "Type" ); + writeTextElement(w, "th", "Type"); - boolean showSinceColumn = version.greaterThan( firstVersion ); + boolean showSinceColumn = version.greaterThan(firstVersion); - if ( showSinceColumn ) - { - writeTextElement( w, "th", "Since" ); + if (showSinceColumn) { + writeTextElement(w, "th", "Since"); } - writeTextElement( w, "th", "Description" ); + writeTextElement(w, "th", "Description"); w.endElement(); // tr - for ( ModelField f : fields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID ); + for (ModelField f : fields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { continue; } - w.startElement( "tr" ); + w.startElement("tr"); // Element/Attribute column - String tagName = resolveTagName( f, xmlFieldMetadata ); + String tagName = resolveTagName(f, xmlFieldMetadata); - w.startElement( "td" ); + w.startElement("td"); - w.startElement( "code" ); + w.startElement("code"); boolean manyAssociation = false; - if ( f instanceof ModelAssociation ) - { + if (f instanceof ModelAssociation) { ModelAssociation assoc = (ModelAssociation) f; XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) assoc.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) assoc.getAssociationMetadata(XmlAssociationMetadata.ID); manyAssociation = assoc.isManyMultiplicity(); - String itemTagName = manyAssociation ? resolveTagName( tagName, xmlAssociationMetadata ) : tagName; + String itemTagName = manyAssociation ? resolveTagName(tagName, xmlAssociationMetadata) : tagName; - if ( manyAssociation && xmlAssociationMetadata.isWrappedItems() ) - { - w.writeText( tagName ); - w.writeMarkup( "/" ); + if (manyAssociation && xmlAssociationMetadata.isWrappedItems()) { + w.writeText(tagName); + w.writeMarkup("/"); } - if ( isInnerAssociation( f ) ) - { - w.startElement( "a" ); - w.addAttribute( "href", "#" + getAnchorName( itemTagName, assoc.getToClass() ) ); - w.writeText( itemTagName ); + if (isInnerAssociation(f)) { + w.startElement("a"); + w.addAttribute("href", "#" + getAnchorName(itemTagName, assoc.getToClass())); + w.writeText(itemTagName); w.endElement(); - } - else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) - { - if ( xmlAssociationMetadata.isMapExplode() ) - { - w.writeText( "(key,value)" ); + } else if (ModelDefault.PROPERTIES.equals(f.getType())) { + if (xmlAssociationMetadata.isMapExplode()) { + w.writeText("(key,value)"); + } else { + w.writeMarkup("key=value"); } - else - { - w.writeMarkup( "key=value" ); - } - } - else - { - w.writeText( itemTagName ); + } else { + w.writeText(itemTagName); } - if ( manyAssociation ) - { - w.writeText( "*" ); + if (manyAssociation) { + w.writeText("*"); } - } - else - { - w.writeText( tagName ); + } else { + w.writeText(tagName); } w.endElement(); // code @@ -407,31 +366,24 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) // Type column - w.startElement( "td" ); + w.startElement("td"); - w.startElement( "code" ); + w.startElement("code"); - if ( f instanceof ModelAssociation ) - { + if (f instanceof ModelAssociation) { ModelAssociation assoc = (ModelAssociation) f; - if ( assoc.isOneMultiplicity() ) - { - w.writeText( assoc.getTo() ); - } - else - { - w.writeText( assoc.getType().substring( "java.util.".length() ) ); + if (assoc.isOneMultiplicity()) { + w.writeText(assoc.getTo()); + } else { + w.writeText(assoc.getType().substring("java.util.".length())); - if ( assoc.isGenericType() ) - { - w.writeText( "<" + assoc.getTo() + ">" ); + if (assoc.isGenericType()) { + w.writeText("<" + assoc.getTo() + ">"); } } - } - else - { - w.writeText( f.getType() ); + } else { + w.writeText(f.getType()); } w.endElement(); // code @@ -440,16 +392,13 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) // Since column - if ( showSinceColumn ) - { - w.startElement( "td" ); + if (showSinceColumn) { + w.startElement("td"); - if ( f.getVersionRange() != null ) - { + if (f.getVersionRange() != null) { Version fromVersion = f.getVersionRange().getFromVersion(); - if ( fromVersion != null && fromVersion.greaterThan( firstVersion ) ) - { - w.writeMarkup( fromVersion.toString() ); + if (fromVersion != null && fromVersion.greaterThan(firstVersion)) { + w.writeMarkup(fromVersion.toString()); } } @@ -458,26 +407,24 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) // Description column - w.startElement( "td" ); + w.startElement("td"); - if ( manyAssociation ) - { - w.writeMarkup( "(Many) " ); + if (manyAssociation) { + w.writeMarkup("(Many) "); } - w.writeMarkup( getDescription( f ) ); + w.writeMarkup(getDescription(f)); // Write the default value, if it exists. // But only for fields that are not a ModelAssociation - if ( f.getDefaultValue() != null && !( f instanceof ModelAssociation ) ) - { - w.writeMarkup( "

Default value is: " ); + if (f.getDefaultValue() != null && !(f instanceof ModelAssociation)) { + w.writeMarkup("

Default value is: "); - writeTextElement( w, "code", f.getDefaultValue() ); + writeTextElement(w, "code", f.getDefaultValue()); - w.writeMarkup( "

"); + w.writeMarkup("

"); - w.writeText( "." ); + w.writeText("."); } w.endElement(); // td @@ -486,7 +433,6 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) } w.endElement(); // table - } /** @@ -495,9 +441,8 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) * @param rootModelClass the model root class * @return the String representing the tree model */ - private String getModelXmlDescriptor( ModelClass rootModelClass ) - { - return getElementXmlDescriptor( rootModelClass, null, new Stack() ); + private String getModelXmlDescriptor(ModelClass rootModelClass) { + return getElementXmlDescriptor(rootModelClass, null, new Stack()); } /** @@ -509,181 +454,154 @@ private String getModelXmlDescriptor( ModelClass rootModelClass ) * @return the String representing the tree model * @throws ModelloRuntimeException */ - private String getElementXmlDescriptor( ModelClass modelClass, ModelAssociation association, Stack stack ) - throws ModelloRuntimeException - { + private String getElementXmlDescriptor(ModelClass modelClass, ModelAssociation association, Stack stack) + throws ModelloRuntimeException { StringBuilder sb = new StringBuilder(); - appendSpacer( sb, stack.size() ); + appendSpacer(sb, stack.size()); - String tagName = resolveTagName( modelClass, association ); + String tagName = resolveTagName(modelClass, association); // " ); - sb.append( tagName ).append( "" ); + sb.append("<"); + sb.append(tagName).append(""); boolean addNewline = false; - if ( stack.size() == 0 ) - { + if (stack.size() == 0) { // try to add XML Schema reference - try - { - String targetNamespace = XsdModelHelper.getTargetNamespace( modelClass.getModel(), getGeneratedVersion() ); + try { + String targetNamespace = + XsdModelHelper.getTargetNamespace(modelClass.getModel(), getGeneratedVersion()); - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID ); + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) modelClass.getModel().getMetadata(XmlModelMetadata.ID); - if ( StringUtils.isNotBlank( targetNamespace ) && ( xmlModelMetadata.getSchemaLocation() != null ) ) - { - String schemaLocation = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); + if (StringUtils.isNotBlank(targetNamespace) && (xmlModelMetadata.getSchemaLocation() != null)) { + String schemaLocation = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); - sb.append( " xmlns=\"" + targetNamespace + "\"" ); - sb.append( " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" ); - sb.append( " xsi:schemaLocation=\"" + targetNamespace ); - sb.append( " " + schemaLocation + "\"" ); + sb.append(" xmlns=\"" + targetNamespace + "\""); + sb.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); + sb.append(" xsi:schemaLocation=\"" + targetNamespace); + sb.append(" " + schemaLocation + "\""); addNewline = true; } - } - catch ( ModelloException me ) - { + } catch (ModelloException me) { // ignore unavailable XML Schema configuration } } String id = tagName + '/' + modelClass.getPackageName() + '.' + modelClass.getName(); - if ( stack.contains( id ) ) - { + if (stack.contains(id)) { // recursion detected - sb.append( ">...recursion...<" ).append( tagName ).append( ">\n" ); + sb.append(">...recursion...<").append(tagName).append(">\n"); return sb.toString(); } - List fields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List fields = getFieldsForXml(modelClass, getGeneratedVersion()); - List attributeFields = getXmlAttributeFields( fields ); + List attributeFields = getXmlAttributeFields(fields); - if ( attributeFields.size() > 0 ) - { + if (attributeFields.size() > 0) { - for ( ModelField f : attributeFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID ); + for (ModelField f : attributeFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata(XmlFieldMetadata.ID); - if ( addNewline ) - { + if (addNewline) { addNewline = false; - sb.append( "\n " ); - } - else - { - sb.append( ' ' ); + sb.append("\n "); + } else { + sb.append(' '); } - sb.append( resolveTagName( f, xmlFieldMetadata ) ).append( "=.." ); + sb.append(resolveTagName(f, xmlFieldMetadata)).append("=.."); } - sb.append( ' ' ); - + sb.append(' '); } - fields.removeAll( attributeFields ); + fields.removeAll(attributeFields); - if ( ( fields.size() == 0 ) || ( ( fields.size() == 1 ) && hasContentField( fields ) ) ) - { - sb.append( "/>\n" ); - } - else - { - sb.append( ">\n" ); + if ((fields.size() == 0) || ((fields.size() == 1) && hasContentField(fields))) { + sb.append("/>\n"); + } else { + sb.append(">\n"); - stack.push( id ); + stack.push(id); - for ( ModelField f : fields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata( XmlFieldMetadata.ID ); + for (ModelField f : fields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) f.getMetadata(XmlFieldMetadata.ID); - XdocFieldMetadata xdocFieldMetadata = (XdocFieldMetadata) f.getMetadata( XdocFieldMetadata.ID ); + XdocFieldMetadata xdocFieldMetadata = (XdocFieldMetadata) f.getMetadata(XdocFieldMetadata.ID); - if ( XdocFieldMetadata.BLANK.equals( xdocFieldMetadata.getSeparator() ) ) - { - sb.append( '\n' ); + if (XdocFieldMetadata.BLANK.equals(xdocFieldMetadata.getSeparator())) { + sb.append('\n'); } - String fieldTagName = resolveTagName( f, xmlFieldMetadata ); + String fieldTagName = resolveTagName(f, xmlFieldMetadata); - if ( isInnerAssociation( f ) ) - { + if (isInnerAssociation(f)) { ModelAssociation assoc = (ModelAssociation) f; boolean wrappedItems = false; - if ( assoc.isManyMultiplicity() ) - { + if (assoc.isManyMultiplicity()) { XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) assoc.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) assoc.getAssociationMetadata(XmlAssociationMetadata.ID); wrappedItems = xmlAssociationMetadata.isWrappedItems(); } - if ( wrappedItems ) - { - appendSpacer( sb, stack.size() ); + if (wrappedItems) { + appendSpacer(sb, stack.size()); - sb.append( "<" ).append( fieldTagName ).append( ">\n" ); + sb.append("<").append(fieldTagName).append(">\n"); - stack.push( fieldTagName ); + stack.push(fieldTagName); } - ModelClass fieldModelClass = getModel().getClass( assoc.getTo(), getGeneratedVersion() ); + ModelClass fieldModelClass = getModel().getClass(assoc.getTo(), getGeneratedVersion()); - sb.append( getElementXmlDescriptor( fieldModelClass, assoc, stack ) ); + sb.append(getElementXmlDescriptor(fieldModelClass, assoc, stack)); - if ( wrappedItems ) - { + if (wrappedItems) { stack.pop(); - appendSpacer( sb, stack.size() ); + appendSpacer(sb, stack.size()); - sb.append( "</" ).append( fieldTagName ).append( ">\n" ); + sb.append("</").append(fieldTagName).append(">\n"); } - } - else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) - { + } else if (ModelDefault.PROPERTIES.equals(f.getType())) { ModelAssociation assoc = (ModelAssociation) f; XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) assoc.getAssociationMetadata( XmlAssociationMetadata.ID ); - - appendSpacer( sb, stack.size() ); - sb.append( "<" ).append( fieldTagName ).append( ">\n" ); - - if ( xmlAssociationMetadata.isMapExplode() ) - { - appendSpacer( sb, stack.size() + 1 ); - sb.append( "<key/>\n" ); - appendSpacer( sb, stack.size() + 1 ); - sb.append( "<value/>\n" ); - } - else - { - appendSpacer( sb, stack.size() + 1 ); - sb.append( "<key>value</key>\n" ); + (XmlAssociationMetadata) assoc.getAssociationMetadata(XmlAssociationMetadata.ID); + + appendSpacer(sb, stack.size()); + sb.append("<").append(fieldTagName).append(">\n"); + + if (xmlAssociationMetadata.isMapExplode()) { + appendSpacer(sb, stack.size() + 1); + sb.append("<key/>\n"); + appendSpacer(sb, stack.size() + 1); + sb.append("<value/>\n"); + } else { + appendSpacer(sb, stack.size() + 1); + sb.append("<key>value</key>\n"); } - appendSpacer( sb, stack.size() ); - sb.append( "</" ).append( fieldTagName ).append( ">\n" ); - } - else - { - appendSpacer( sb, stack.size() ); + appendSpacer(sb, stack.size()); + sb.append("</").append(fieldTagName).append(">\n"); + } else { + appendSpacer(sb, stack.size()); - sb.append( "<" ).append( fieldTagName ).append( "/>\n" ); + sb.append("<").append(fieldTagName).append("/>\n"); } } stack.pop(); - appendSpacer( sb, stack.size() ); + appendSpacer(sb, stack.size()); - sb.append( "</" ).append( tagName ).append( ">\n" ); + sb.append("</").append(tagName).append(">\n"); } return sb.toString(); @@ -696,52 +614,38 @@ else if ( ModelDefault.PROPERTIES.equals( f.getType() ) ) * @return the tag name to use * @todo refactor to use XmlModelHelpers.resolveTagName helpers instead */ - private String resolveTagName( ModelClass modelClass, ModelAssociation association ) - { - XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata( XmlClassMetadata.ID ); + private String resolveTagName(ModelClass modelClass, ModelAssociation association) { + XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata(XmlClassMetadata.ID); String tagName; - if ( xmlClassMetadata == null || xmlClassMetadata.getTagName() == null ) - { - if ( association == null ) - { - tagName = uncapitalise( modelClass.getName() ); - } - else - { + if (xmlClassMetadata == null || xmlClassMetadata.getTagName() == null) { + if (association == null) { + tagName = uncapitalise(modelClass.getName()); + } else { tagName = association.getName(); - if ( association.isManyMultiplicity() ) - { - tagName = singular( tagName ); + if (association.isManyMultiplicity()) { + tagName = singular(tagName); } } - } - else - { + } else { tagName = xmlClassMetadata.getTagName(); } - if ( association != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) association.getMetadata( XmlFieldMetadata.ID ); + if (association != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) association.getMetadata(XmlFieldMetadata.ID); XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - if ( xmlFieldMetadata != null ) - { - if ( xmlAssociationMetadata.getTagName() != null ) - { + if (xmlFieldMetadata != null) { + if (xmlAssociationMetadata.getTagName() != null) { tagName = xmlAssociationMetadata.getTagName(); - } - else if ( xmlFieldMetadata.getTagName() != null ) - { + } else if (xmlFieldMetadata.getTagName() != null) { tagName = xmlFieldMetadata.getTagName(); - if ( association.isManyMultiplicity() ) - { - tagName = singular( tagName ); + if (association.isManyMultiplicity()) { + tagName = singular(tagName); } } } @@ -755,43 +659,37 @@ else if ( xmlFieldMetadata.getTagName() != null ) * @param sb where to append the spacers * @param depth the depth of spacers to generate */ - private static void appendSpacer( StringBuilder sb, int depth ) - { - for ( int i = 0; i < depth; i++ ) - { - sb.append( " " ); + private static void appendSpacer(StringBuilder sb, int depth) { + for (int i = 0; i < depth; i++) { + sb.append(" "); } } - private static String getDescription( BaseElement element ) - { - return ( element.getDescription() == null ) ? "No description." : rewrite( element.getDescription() ); + private static String getDescription(BaseElement element) { + return (element.getDescription() == null) ? "No description." : rewrite(element.getDescription()); } - private static void writeTextElement( XMLWriter w, String name, String text ) - { - w.startElement( name ); - w.writeText( text ); + private static void writeTextElement(XMLWriter w, String name, String text) { + w.startElement(name); + w.writeText(text); w.endElement(); } - private static void writeMarkupElement( XMLWriter w, String name, String markup ) - { - w.startElement( name ); - w.writeMarkup( markup ); + private static void writeMarkupElement(XMLWriter w, String name, String markup) { + w.startElement(name); + w.writeMarkup(markup); w.endElement(); } - + /** * Ensures that text will have balanced tags - * + * * @param text xml or html based content * @return valid XML string */ - private static String rewrite( String text ) - { - Document document = Jsoup.parseBodyFragment( text ); - document.outputSettings().syntax( Document.OutputSettings.Syntax.xml ); + private static String rewrite(String text) { + Document document = Jsoup.parseBodyFragment(text); + document.outputSettings().syntax(Document.OutputSettings.Syntax.xml); return document.body().html(); } } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocAssociationMetadata.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocAssociationMetadata.java index 192e9c6db..bfe2f4950 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocAssociationMetadata.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocAssociationMetadata.java @@ -27,8 +27,6 @@ /** * @author Hervé Boutemy */ -public class XdocAssociationMetadata - implements AssociationMetadata -{ +public class XdocAssociationMetadata implements AssociationMetadata { public static final String ID = XdocAssociationMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocClassMetadata.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocClassMetadata.java index 2b4ab5d7e..f73bd31cd 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocClassMetadata.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocClassMetadata.java @@ -27,20 +27,16 @@ /** * @author Hervé Boutemy */ -public class XdocClassMetadata - implements ClassMetadata -{ +public class XdocClassMetadata implements ClassMetadata { public static final String ID = XdocClassMetadata.class.getName(); private String anchorName; - public String getAnchorName() - { + public String getAnchorName() { return anchorName; } - public void setAnchorName( String anchorName ) - { + public void setAnchorName(String anchorName) { this.anchorName = anchorName; } } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocFieldMetadata.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocFieldMetadata.java index b66f0313e..65085174e 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocFieldMetadata.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocFieldMetadata.java @@ -27,9 +27,7 @@ /** * @author Hervé Boutemy */ -public class XdocFieldMetadata - implements FieldMetadata -{ +public class XdocFieldMetadata implements FieldMetadata { public static final String ID = XdocFieldMetadata.class.getName(); public static final String NONE = "none"; @@ -38,13 +36,11 @@ public class XdocFieldMetadata private String separator; - public String getSeparator() - { + public String getSeparator() { return separator; } - public void setSeparator( String separator ) - { + public void setSeparator(String separator) { this.separator = separator; } } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocInterfaceMetadata.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocInterfaceMetadata.java index db940ac9a..13ade9acc 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocInterfaceMetadata.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocInterfaceMetadata.java @@ -27,8 +27,6 @@ /** * @author Hervé Boutemy */ -public class XdocInterfaceMetadata - implements InterfaceMetadata -{ +public class XdocInterfaceMetadata implements InterfaceMetadata { public static final String ID = XdocInterfaceMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocMetadataPlugin.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocMetadataPlugin.java index 93672fea0..3db1e3d60 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocMetadataPlugin.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocMetadataPlugin.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.Map; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.metadata.AbstractMetadataPlugin; import org.codehaus.modello.metadata.AssociationMetadata; @@ -37,52 +39,40 @@ import org.codehaus.modello.model.ModelInterface; import org.codehaus.plexus.component.annotations.Component; -import java.util.Map; - /** * @author Hervé Boutemy */ -@Component( role = MetadataPlugin.class, hint = "stax-writer" ) -public class XdocMetadataPlugin - extends AbstractMetadataPlugin - implements MetadataPlugin -{ +@Component(role = MetadataPlugin.class, hint = "stax-writer") +public class XdocMetadataPlugin extends AbstractMetadataPlugin implements MetadataPlugin { public static final String XDOC_SEPARATOR = "xdoc.separator"; public static final String XDOC_ANCHORNAME = "xdoc.anchorName"; - public ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - { + public ClassMetadata getClassMetadata(ModelClass clazz, Map data) { XdocClassMetadata metadata = new XdocClassMetadata(); - metadata.setAnchorName( getString( data, XDOC_ANCHORNAME ) ); + metadata.setAnchorName(getString(data, XDOC_ANCHORNAME)); return metadata; } - public InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - { + public InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) { return new XdocInterfaceMetadata(); } - public AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - throws ModelloException - { + public AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) + throws ModelloException { return new XdocAssociationMetadata(); } - public FieldMetadata getFieldMetadata( ModelField field, Map data ) - throws ModelloException - { + public FieldMetadata getFieldMetadata(ModelField field, Map data) throws ModelloException { XdocFieldMetadata metadata = new XdocFieldMetadata(); - metadata.setSeparator( getString( data, XDOC_SEPARATOR ) ); + metadata.setSeparator(getString(data, XDOC_SEPARATOR)); return metadata; } - public ModelMetadata getModelMetadata( Model model, Map data ) - throws ModelloException - { + public ModelMetadata getModelMetadata(Model model, Map data) throws ModelloException { return new XdocModelMetadata(); } } diff --git a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocModelMetadata.java b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocModelMetadata.java index ddcd21a25..557dec323 100644 --- a/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocModelMetadata.java +++ b/modello-plugins/modello-plugin-xdoc/src/main/java/org/codehaus/modello/plugin/xdoc/metadata/XdocModelMetadata.java @@ -27,8 +27,6 @@ /** * @author Hervé Boutemy */ -public class XdocModelMetadata - implements ModelMetadata -{ +public class XdocModelMetadata implements ModelMetadata { public static final String ID = XdocModelMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xdoc/src/test/java/org/codehaus/modello/plugin/xdoc/XdocGeneratorTest.java b/modello-plugins/modello-plugin-xdoc/src/test/java/org/codehaus/modello/plugin/xdoc/XdocGeneratorTest.java index a662c9c6f..2a0bc8dc5 100644 --- a/modello-plugins/modello-plugin-xdoc/src/test/java/org/codehaus/modello/plugin/xdoc/XdocGeneratorTest.java +++ b/modello-plugins/modello-plugin-xdoc/src/test/java/org/codehaus/modello/plugin/xdoc/XdocGeneratorTest.java @@ -1,13 +1,5 @@ package org.codehaus.modello.plugin.xdoc; -import java.io.File; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /* * Copyright (c) 2004, Codehaus.org * @@ -30,6 +22,15 @@ * SOFTWARE. */ +import java.io.File; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import junit.framework.Assert; import org.codehaus.modello.AbstractModelloGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; @@ -43,131 +44,117 @@ import org.xmlunit.builder.Input; import org.xmlunit.diff.Diff; -import junit.framework.Assert; - /** * @author Trygve Laugstøl */ -public class XdocGeneratorTest - extends AbstractModelloGeneratorTest +public class XdocGeneratorTest extends AbstractModelloGeneratorTest { -{ - public XdocGeneratorTest() - { - super( "xdoc" ); + public XdocGeneratorTest() { + super("xdoc"); } - protected File getOutputDirectory() - { - return getTestFile( "target/generated-site/xdoc" ); + protected File getOutputDirectory() { + return getTestFile("target/generated-site/xdoc"); } - public void testXdocGenerator() - throws Exception - { + public void testXdocGenerator() throws Exception { checkMavenXdocGenerator(); checkFeaturesXdocGenerator(); checkSettingsXdocGenerator(); } - public void testHtmlToXml() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testHtmlToXml() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/html4.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/html4.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "xdoc", parameters ); + modello.generate(model, "xdoc", parameters); - Diff diff = DiffBuilder.compare( Input.fromStream( XdocGeneratorTest.class.getResourceAsStream( "/html4.expected.xml" ) ) ) - .withTest( Input.fromFile( new File( getOutputDirectory(), "html4.xml" ) ) ).build(); + Diff diff = DiffBuilder.compare( + Input.fromStream(XdocGeneratorTest.class.getResourceAsStream("/html4.expected.xml"))) + .withTest(Input.fromFile(new File(getOutputDirectory(), "html4.xml"))) + .build(); - assertFalse( diff.toString(), diff.hasDifferences() ); + assertFalse(diff.toString(), diff.hasDifferences()); } - private void checkMavenXdocGenerator() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + private void checkMavenXdocGenerator() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 26, classesList.size() ); + assertEquals(26, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "xdoc", parameters ); + modello.generate(model, "xdoc", parameters); - //addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); + // addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); - //verify( "org.codehaus.modello.generator.xml.cdoc.XdocVerifier", "xdoc" ); - checkInternalLinks( "maven.xml" ); + // verify( "org.codehaus.modello.generator.xml.cdoc.XdocVerifier", "xdoc" ); + checkInternalLinks("maven.xml"); } - public void checkFeaturesXdocGenerator() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void checkFeaturesXdocGenerator() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.5.0" ); + Properties parameters = getModelloParameters("1.5.0"); - modello.generate( model, "xdoc", parameters ); + modello.generate(model, "xdoc", parameters); - checkInternalLinks( "features.xml" ); + checkInternalLinks("features.xml"); - String content = FileUtils.fileRead( new File( getOutputDirectory(), "features.xml" ), "UTF-8" ); + String content = FileUtils.fileRead(new File(getOutputDirectory(), "features.xml"), "UTF-8"); - assertTrue( "Transient fields were erroneously documented", !content.contains( "transientString" ) ); + assertTrue("Transient fields were erroneously documented", !content.contains("transientString")); } - public void checkSettingsXdocGenerator() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void checkSettingsXdocGenerator() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/settings.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/settings.mdo")); - Properties parameters = getModelloParameters( "1.5.0" ); + Properties parameters = getModelloParameters("1.5.0"); - modello.generate( model, "xdoc", parameters ); + modello.generate(model, "xdoc", parameters); - checkInternalLinks( "settings.xml" ); + checkInternalLinks("settings.xml"); - String content = FileUtils.fileRead( new File( getOutputDirectory(), "settings.xml" ), "UTF-8" ); + String content = FileUtils.fileRead(new File(getOutputDirectory(), "settings.xml"), "UTF-8"); - assertTrue( "Properties field was erroneously documented", !content.contains("<properties/>") ); + assertTrue("Properties field was erroneously documented", !content.contains("<properties/>")); } /** @@ -177,33 +164,28 @@ public void checkSettingsXdocGenerator() * @param xdoc * @throws Exception */ - private void checkInternalLinks( String filename ) - throws Exception - { - String content = FileUtils.fileRead( new File( getOutputDirectory(), filename ), "UTF-8" ); + private void checkInternalLinks(String filename) throws Exception { + String content = FileUtils.fileRead(new File(getOutputDirectory(), filename), "UTF-8"); Set hrefs = new HashSet(); - Pattern p = Pattern.compile( "Trygve Laugstøl */ -public class XmlAssociationMetadata - implements AssociationMetadata -{ +public class XmlAssociationMetadata implements AssociationMetadata { public static final String ID = XmlAssociationMetadata.class.getName(); public static final String EXPLODE_MODE = "explode"; @@ -48,84 +46,66 @@ public class XmlAssociationMetadata private boolean reference; - public String getTagName() - { + public String getTagName() { return tagName; } - public void setTagName( String tagName ) - { + public void setTagName(String tagName) { this.tagName = tagName; } - public String getItemsStyle() - { + public String getItemsStyle() { return itemsStyle; } - public void setItemsStyle( String itemsStyle ) - { - if ( ITEMS_STYLE_FLAT.equals( itemsStyle ) || ITEMS_STYLE_WRAPPED.equals( itemsStyle ) ) - { + public void setItemsStyle(String itemsStyle) { + if (ITEMS_STYLE_FLAT.equals(itemsStyle) || ITEMS_STYLE_WRAPPED.equals(itemsStyle)) { this.itemsStyle = itemsStyle; - } - else - { + } else { // default this.itemsStyle = ITEMS_STYLE_WRAPPED; } } - public boolean isFlatItems() - { - return ITEMS_STYLE_FLAT.equals( itemsStyle ); + public boolean isFlatItems() { + return ITEMS_STYLE_FLAT.equals(itemsStyle); } - public boolean isWrappedItems() - { - return ITEMS_STYLE_WRAPPED.equals( itemsStyle ); + public boolean isWrappedItems() { + return ITEMS_STYLE_WRAPPED.equals(itemsStyle); } /** * @return Returns the map style. */ - public String getMapStyle() - { + public String getMapStyle() { return mapStyle; } /** * @param mapStyle The map style (inline or explode). */ - public void setMapStyle( String mapStyle ) - { - if ( mapStyle == null ) - { + public void setMapStyle(String mapStyle) { + if (mapStyle == null) { this.mapStyle = INLINE_MODE; - } - else - { + } else { this.mapStyle = mapStyle; } } - public boolean isMapInline() - { - return INLINE_MODE.equals( mapStyle ); + public boolean isMapInline() { + return INLINE_MODE.equals(mapStyle); } - public boolean isMapExplode() - { - return EXPLODE_MODE.equals( mapStyle ); + public boolean isMapExplode() { + return EXPLODE_MODE.equals(mapStyle); } - public boolean isReference() - { + public boolean isReference() { return reference; } - public void setReference( boolean reference ) - { + public void setReference(boolean reference) { this.reference = reference; } } diff --git a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlClassMetadata.java b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlClassMetadata.java index 87cd8178c..df304df79 100644 --- a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlClassMetadata.java +++ b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlClassMetadata.java @@ -27,32 +27,26 @@ /** * @author Trygve Laugstøl */ -public class XmlClassMetadata - implements ClassMetadata -{ +public class XmlClassMetadata implements ClassMetadata { public static final String ID = XmlClassMetadata.class.getName(); private String tagName; private boolean standaloneRead; - public String getTagName() - { + public String getTagName() { return tagName; } - public void setTagName( String tagName ) - { + public void setTagName(String tagName) { this.tagName = tagName; } - public boolean isStandaloneRead() - { + public boolean isStandaloneRead() { return standaloneRead; } - public void setStandaloneRead( boolean standaloneRead ) - { + public void setStandaloneRead(boolean standaloneRead) { this.standaloneRead = standaloneRead; } } diff --git a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlFieldMetadata.java b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlFieldMetadata.java index 1bc3a3a6a..21e0eb46a 100644 --- a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlFieldMetadata.java +++ b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlFieldMetadata.java @@ -27,9 +27,7 @@ /** * @author Trygve Laugstøl */ -public class XmlFieldMetadata - implements FieldMetadata -{ +public class XmlFieldMetadata implements FieldMetadata { public static final String ID = XmlFieldMetadata.class.getName(); private boolean attribute; @@ -46,85 +44,71 @@ public class XmlFieldMetadata private String insertParentFieldsUpTo; - public String getFormat() - { + public String getFormat() { return format; } - public void setFormat( String format ) - { + public void setFormat(String format) { this.format = format; } - public boolean isTrim() - { + public boolean isTrim() { return trim; } - public void setTrim( boolean trim ) - { + public void setTrim(boolean trim) { this.trim = trim; } /** * @return Returns the attribute. */ - public boolean isAttribute() - { + public boolean isAttribute() { return attribute; } /** * @param attribute The attribute to set. */ - public void setAttribute( boolean attribute ) - { + public void setAttribute(boolean attribute) { this.attribute = attribute; } - public boolean isContent() - { + public boolean isContent() { return content; } - public void setContent( boolean content ) - { + public void setContent(boolean content) { this.content = content; } /** * @return Returns the tag name or the attribute name if it's an attribute. */ - public String getTagName() - { + public String getTagName() { return tagName; } /** * @param tagName The tag or attribute name to set. */ - public void setTagName( String tagName ) - { + public void setTagName(String tagName) { this.tagName = tagName; } - public boolean isTransient() - { + public boolean isTransient() { return transientField; } - public void setTransient( boolean transientField ) - { + public void setTransient(boolean transientField) { this.transientField = transientField; } - public String getInsertParentFieldsUpTo() - { + public String getInsertParentFieldsUpTo() { return insertParentFieldsUpTo; } - public void setInsertParentFieldsUpTo( String insertParentFieldsUpTo ) - { + public void setInsertParentFieldsUpTo(String insertParentFieldsUpTo) { this.insertParentFieldsUpTo = insertParentFieldsUpTo; } } diff --git a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlInterfaceMetadata.java b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlInterfaceMetadata.java index f70248ca0..5c2fa8343 100644 --- a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlInterfaceMetadata.java +++ b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlInterfaceMetadata.java @@ -27,8 +27,6 @@ /** * @author Trygve Laugstøl */ -public class XmlInterfaceMetadata - implements InterfaceMetadata -{ +public class XmlInterfaceMetadata implements InterfaceMetadata { public static final String ID = XmlInterfaceMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlMetadataPlugin.java b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlMetadataPlugin.java index 2c54b4e07..109648b0c 100644 --- a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlMetadataPlugin.java +++ b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlMetadataPlugin.java @@ -42,11 +42,8 @@ * @author Trygve Laugstøl * @author Emmanuel Venisse */ -@Component( role = MetadataPlugin.class, hint = "xml" ) -public class XmlMetadataPlugin - extends AbstractMetadataPlugin - implements MetadataPlugin -{ +@Component(role = MetadataPlugin.class, hint = "xml") +public class XmlMetadataPlugin extends AbstractMetadataPlugin implements MetadataPlugin { public static final String XML_ATTRIBUTE = "xml.attribute"; public static final String XML_CONTENT = "xml.content"; @@ -77,65 +74,60 @@ public class XmlMetadataPlugin // Map to Metadata // ---------------------------------------------------------------------- - public ModelMetadata getModelMetadata( Model model, Map data ) - { + public ModelMetadata getModelMetadata(Model model, Map data) { XmlModelMetadata metadata = new XmlModelMetadata(); - metadata.setNamespace( getString( data, XML_NAMESPACE ) ); + metadata.setNamespace(getString(data, XML_NAMESPACE)); - metadata.setSchemaLocation( getString( data, XML_SCHEMA_LOCATION ) ); + metadata.setSchemaLocation(getString(data, XML_SCHEMA_LOCATION)); return metadata; } - public ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - { + public ClassMetadata getClassMetadata(ModelClass clazz, Map data) { XmlClassMetadata metadata = new XmlClassMetadata(); - metadata.setTagName( getString( data, XML_TAG_NAME ) ); + metadata.setTagName(getString(data, XML_TAG_NAME)); - metadata.setStandaloneRead( getBoolean( data, XML_STANDALONE_READ, false ) ); + metadata.setStandaloneRead(getBoolean(data, XML_STANDALONE_READ, false)); return metadata; } - public InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - { + public InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) { return new XmlInterfaceMetadata(); } - public FieldMetadata getFieldMetadata( ModelField field, Map data ) - { + public FieldMetadata getFieldMetadata(ModelField field, Map data) { XmlFieldMetadata metadata = new XmlFieldMetadata(); - metadata.setAttribute( getBoolean( data, XML_ATTRIBUTE, false ) ); + metadata.setAttribute(getBoolean(data, XML_ATTRIBUTE, false)); - metadata.setContent( getBoolean( data, XML_CONTENT, false ) ); + metadata.setContent(getBoolean(data, XML_CONTENT, false)); - metadata.setTrim( getBoolean( data, XML_TRIM, true ) ); + metadata.setTrim(getBoolean(data, XML_TRIM, true)); - metadata.setTagName( getString( data, XML_TAG_NAME ) ); + metadata.setTagName(getString(data, XML_TAG_NAME)); - metadata.setFormat( getString( data, XML_FORMAT ) ); + metadata.setFormat(getString(data, XML_FORMAT)); - metadata.setTransient( getBoolean( data, XML_TRANSIENT, false ) ); + metadata.setTransient(getBoolean(data, XML_TRANSIENT, false)); - metadata.setInsertParentFieldsUpTo( getString( data, XML_INSERT_PARENT_FIELDS_UP_TO ) ); + metadata.setInsertParentFieldsUpTo(getString(data, XML_INSERT_PARENT_FIELDS_UP_TO)); return metadata; } - public AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - { + public AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) { XmlAssociationMetadata metadata = new XmlAssociationMetadata(); - metadata.setTagName( getString( data, XML_TAG_NAME ) ); + metadata.setTagName(getString(data, XML_TAG_NAME)); - metadata.setItemsStyle( getString( data, XML_ITEMS_STYLE ) ); + metadata.setItemsStyle(getString(data, XML_ITEMS_STYLE)); - metadata.setMapStyle( getString( data, XML_MAP_STYLE ) ); + metadata.setMapStyle(getString(data, XML_MAP_STYLE)); - metadata.setReference( getBoolean( data, XML_REFERENCE, false ) ); + metadata.setReference(getBoolean(data, XML_REFERENCE, false)); return metadata; } diff --git a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlModelMetadata.java b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlModelMetadata.java index 5be38bab0..e29c268c1 100644 --- a/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlModelMetadata.java +++ b/modello-plugins/modello-plugin-xml/src/main/java/org/codehaus/modello/plugins/xml/metadata/XmlModelMetadata.java @@ -29,54 +29,44 @@ /** * @author Trygve Laugstøl */ -public class XmlModelMetadata - implements ModelMetadata -{ +public class XmlModelMetadata implements ModelMetadata { public static final String ID = XmlModelMetadata.class.getName(); private String namespace; private String schemaLocation; - public String getNamespace() - { + public String getNamespace() { return namespace; } - public void setNamespace( String namespace ) - { + public void setNamespace(String namespace) { this.namespace = namespace; } - public String getSchemaLocation() - { + public String getSchemaLocation() { return schemaLocation; } - public void setSchemaLocation( String schemaLocation ) - { + public void setSchemaLocation(String schemaLocation) { this.schemaLocation = schemaLocation; } - public String getNamespace( Version version ) - { + public String getNamespace(Version version) { String namespace = this.namespace; - if ( version != null ) - { - namespace = StringUtils.replace( namespace, "${version}", version.toString() ); + if (version != null) { + namespace = StringUtils.replace(namespace, "${version}", version.toString()); } return namespace; } - public String getSchemaLocation( Version version ) - { + public String getSchemaLocation(Version version) { String schemaLocation = this.schemaLocation; - if ( version != null ) - { - schemaLocation = StringUtils.replace( schemaLocation, "${version}", version.toString() ); + if (version != null) { + schemaLocation = StringUtils.replace(schemaLocation, "${version}", version.toString()); } return schemaLocation; diff --git a/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelHelpersTest.java b/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelHelpersTest.java index 321e3e29b..acc219100 100644 --- a/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelHelpersTest.java +++ b/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelHelpersTest.java @@ -1,8 +1,5 @@ package org.codehaus.modello.plugins.xml; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - import java.util.List; import org.codehaus.modello.model.Model; @@ -12,78 +9,78 @@ import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata; import org.junit.Test; -public class XmlModelHelpersTest -{ +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class XmlModelHelpersTest { @Test - public void getFieldsForXml_defaultOrder() - { + public void getFieldsForXml_defaultOrder() { Model model = new Model(); - - ModelClass entityClass = new ModelClass( model, "Entity" ); - ModelField id = new ModelField( new ModelClass( null, "String" ), "id" ); - id.addMetadata( new XmlFieldMetadata() ); - entityClass.addField( id ); - model.addClass( entityClass ); - - ModelClass vehicleClass = new ModelClass( model, "Vehicle" ); - vehicleClass.setSuperClass( "Entity" ); - ModelField brand = new ModelField( new ModelClass( null, "String" ), "brand" ); + + ModelClass entityClass = new ModelClass(model, "Entity"); + ModelField id = new ModelField(new ModelClass(null, "String"), "id"); + id.addMetadata(new XmlFieldMetadata()); + entityClass.addField(id); + model.addClass(entityClass); + + ModelClass vehicleClass = new ModelClass(model, "Vehicle"); + vehicleClass.setSuperClass("Entity"); + ModelField brand = new ModelField(new ModelClass(null, "String"), "brand"); XmlFieldMetadata brandMetadata = new XmlFieldMetadata(); - brandMetadata.setInsertParentFieldsUpTo( "id" ); - brand.addMetadata( brandMetadata ); - vehicleClass.addField( brand ); - model.addClass( vehicleClass ); + brandMetadata.setInsertParentFieldsUpTo("id"); + brand.addMetadata(brandMetadata); + vehicleClass.addField(brand); + model.addClass(vehicleClass); - ModelClass carClass = new ModelClass( model, "Car" ); - carClass.setSuperClass( "Vehicle" ); - ModelField modelName = new ModelField( new ModelClass( null, "String" ), "modelName" ); + ModelClass carClass = new ModelClass(model, "Car"); + carClass.setSuperClass("Vehicle"); + ModelField modelName = new ModelField(new ModelClass(null, "String"), "modelName"); XmlFieldMetadata modeNameMetaData = new XmlFieldMetadata(); - modeNameMetaData.setInsertParentFieldsUpTo( "brand" ); - modelName.addMetadata( modeNameMetaData ); - - carClass.addField( modelName ); - model.addClass( carClass ); - - List orderedFields = XmlModelHelpers.getFieldsForXml( carClass, new Version("0") ); + modeNameMetaData.setInsertParentFieldsUpTo("brand"); + modelName.addMetadata(modeNameMetaData); + + carClass.addField(modelName); + model.addClass(carClass); + + List orderedFields = XmlModelHelpers.getFieldsForXml(carClass, new Version("0")); // unexpected order... - assertThat( orderedFields.get( 2 ).getName(), is( "modelName" ) ); - assertThat( orderedFields.get( 1 ).getName(), is( "brand" ) ); - assertThat( orderedFields.get( 0 ).getName(), is( "id" ) ); + assertThat(orderedFields.get(2).getName(), is("modelName")); + assertThat(orderedFields.get(1).getName(), is("brand")); + assertThat(orderedFields.get(0).getName(), is("id")); } @Test - public void getFieldsForXml_insertParentFieldsUpTo() - { + public void getFieldsForXml_insertParentFieldsUpTo() { Model model = new Model(); - - ModelClass entityClass = new ModelClass( model, "Entity" ); - ModelField id = new ModelField( new ModelClass( null, "String" ), "id" ); - id.addMetadata( new XmlFieldMetadata() ); - entityClass.addField( id ); - model.addClass( entityClass ); - - ModelClass vehicleClass = new ModelClass( model, "Vehicle" ); - vehicleClass.setSuperClass( "Entity" ); - ModelField brand = new ModelField( new ModelClass( null, "String" ), "brand" ); + + ModelClass entityClass = new ModelClass(model, "Entity"); + ModelField id = new ModelField(new ModelClass(null, "String"), "id"); + id.addMetadata(new XmlFieldMetadata()); + entityClass.addField(id); + model.addClass(entityClass); + + ModelClass vehicleClass = new ModelClass(model, "Vehicle"); + vehicleClass.setSuperClass("Entity"); + ModelField brand = new ModelField(new ModelClass(null, "String"), "brand"); XmlFieldMetadata brandMetadata = new XmlFieldMetadata(); - brandMetadata.setInsertParentFieldsUpTo( "id" ); - brand.addMetadata( brandMetadata ); - vehicleClass.addField( brand ); - model.addClass( vehicleClass ); + brandMetadata.setInsertParentFieldsUpTo("id"); + brand.addMetadata(brandMetadata); + vehicleClass.addField(brand); + model.addClass(vehicleClass); - ModelClass carClass = new ModelClass( model, "Car" ); - carClass.setSuperClass( "Vehicle" ); - ModelField modelName = new ModelField( new ModelClass( null, "String" ), "modelName" ); + ModelClass carClass = new ModelClass(model, "Car"); + carClass.setSuperClass("Vehicle"); + ModelField modelName = new ModelField(new ModelClass(null, "String"), "modelName"); XmlFieldMetadata modeNameMetaData = new XmlFieldMetadata(); - modeNameMetaData.setInsertParentFieldsUpTo( "brand" ); - modelName.addMetadata( modeNameMetaData ); - - carClass.addField( modelName ); - model.addClass( carClass ); - - List orderedFields = XmlModelHelpers.getFieldsForXml( carClass, new Version("0") ); - assertThat( orderedFields.get( 0 ).getName(), is( "id" ) ); - assertThat( orderedFields.get( 1 ).getName(), is( "brand" ) ); - assertThat( orderedFields.get( 2 ).getName(), is( "modelName" ) ); + modeNameMetaData.setInsertParentFieldsUpTo("brand"); + modelName.addMetadata(modeNameMetaData); + + carClass.addField(modelName); + model.addClass(carClass); + + List orderedFields = XmlModelHelpers.getFieldsForXml(carClass, new Version("0")); + assertThat(orderedFields.get(0).getName(), is("id")); + assertThat(orderedFields.get(1).getName(), is("brand")); + assertThat(orderedFields.get(2).getName(), is("modelName")); } } diff --git a/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelloPluginTest.java b/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelloPluginTest.java index c84d18b46..723175b73 100644 --- a/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelloPluginTest.java +++ b/modello-plugins/modello-plugin-xml/src/test/java/org/codehaus/modello/plugins/xml/XmlModelloPluginTest.java @@ -22,6 +22,8 @@ * SOFTWARE. */ +import java.util.List; + import org.codehaus.modello.ModelloRuntimeException; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.metadata.MetadataPlugin; @@ -33,84 +35,73 @@ import org.codehaus.modello.plugins.xml.metadata.XmlMetadataPlugin; import org.codehaus.plexus.PlexusTestCase; -import java.util.List; - /** * @author Trygve Laugstøl */ -public class XmlModelloPluginTest - extends PlexusTestCase -{ - public void testConfiguration() - throws Exception - { - Object object = lookup( MetadataPlugin.ROLE, "xml" ); +public class XmlModelloPluginTest extends PlexusTestCase { + public void testConfiguration() throws Exception { + Object object = lookup(MetadataPlugin.ROLE, "xml"); - assertNotNull( object ); + assertNotNull(object); - assertTrue( object instanceof XmlMetadataPlugin ); + assertTrue(object instanceof XmlMetadataPlugin); } - public void testXmlPlugin() - throws Exception - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXmlPlugin() throws Exception { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getTestFile( "src/test/resources/model.mdo" ) ); + Model model = modello.loadModel(getTestFile("src/test/resources/model.mdo")); - List classes = model.getClasses( new Version( "4.0.0" ) ); + List classes = model.getClasses(new Version("4.0.0")); - assertEquals( 2, classes.size() ); + assertEquals(2, classes.size()); - ModelClass clazz = (ModelClass) classes.get( 0 ); + ModelClass clazz = (ModelClass) classes.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - assertEquals( 3, clazz.getFields( new Version( "4.0.0" ) ).size() ); + assertEquals(3, clazz.getFields(new Version("4.0.0")).size()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertFalse( xml.isAttribute() ); + assertFalse(xml.isAttribute()); - extend = clazz.getField( "extend", new Version( "4.1.0" ) ); + extend = clazz.getField("extend", new Version("4.1.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - ModelField parent = clazz.getField( "parent", new Version( "4.0.0" ) ); + ModelField parent = clazz.getField("parent", new Version("4.0.0")); - try - { - parent.getMetadata( "foo" ); + try { + parent.getMetadata("foo"); - fail( "Expected ModelloException" ); - } - catch( ModelloRuntimeException ex ) - { + fail("Expected ModelloException"); + } catch (ModelloRuntimeException ex) { // expected } - ModelField builder = clazz.getField( "builder", new Version( "4.0.0" ) ); + ModelField builder = clazz.getField("builder", new Version("4.0.0")); - assertTrue( builder.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(builder.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) builder.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) builder.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "build", xml.getTagName() ); + assertEquals("build", xml.getTagName()); - assertTrue( xml.isTrim() ); + assertTrue(xml.isTrim()); } } diff --git a/modello-plugins/modello-plugin-xpp3/pom.xml b/modello-plugins/modello-plugin-xpp3/pom.xml index 0e087f4fd..bbac0f17a 100644 --- a/modello-plugins/modello-plugin-xpp3/pom.xml +++ b/modello-plugins/modello-plugin-xpp3/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-xpp3 Modello XPP3 Plugin - - Modello XPP3 Plugin generates XML readers and writers based on XPP3 API (XML Pull Parser). - + Modello XPP3 Plugin generates XML readers and writers based on XPP3 API (XML Pull Parser). diff --git a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/AbstractXpp3Generator.java b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/AbstractXpp3Generator.java index f5112aab3..d1c7f22b9 100644 --- a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/AbstractXpp3Generator.java +++ b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/AbstractXpp3Generator.java @@ -32,39 +32,32 @@ /** * @author Trygve Laugstøl */ -public abstract class AbstractXpp3Generator - extends AbstractXmlJavaGenerator -{ +public abstract class AbstractXpp3Generator extends AbstractXmlJavaGenerator { protected boolean requiresDomSupport; protected ModelClass locationTracker; protected ModelClass sourceTracker; - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return false; } @Override - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { - super.initialize( model, parameters ); + protected void initialize(Model model, Properties parameters) throws ModelloException { + super.initialize(model, parameters); requiresDomSupport = false; locationTracker = sourceTracker = null; - if ( isLocationTracking() ) - { - locationTracker = model.getLocationTracker( getGeneratedVersion() ); - if ( locationTracker == null ) - { - throw new ModelloException( "No model class has been marked as location tracker" - + " via the attribute locationTracker=\"locations\", cannot generate extended reader." ); + if (isLocationTracking()) { + locationTracker = model.getLocationTracker(getGeneratedVersion()); + if (locationTracker == null) { + throw new ModelloException("No model class has been marked as location tracker" + + " via the attribute locationTracker=\"locations\", cannot generate extended reader."); } - sourceTracker = model.getSourceTracker( getGeneratedVersion() ); + sourceTracker = model.getSourceTracker(getGeneratedVersion()); } } } diff --git a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedReaderGenerator.java b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedReaderGenerator.java index a6cf1778a..262200d8d 100644 --- a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedReaderGenerator.java +++ b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedReaderGenerator.java @@ -28,24 +28,19 @@ /** * The generator for XPP3-based parsers that support input location tracking. - * + * * @author Benjamin Bentmann */ -@Component( role = ModelloGenerator.class, hint = "xpp3-extended-reader" ) -public class Xpp3ExtendedReaderGenerator - extends Xpp3ReaderGenerator -{ +@Component(role = ModelloGenerator.class, hint = "xpp3-extended-reader") +public class Xpp3ExtendedReaderGenerator extends Xpp3ReaderGenerator { @Override - protected boolean isRelevant( ModelClass modelClass ) - { - return isJavaEnabled( modelClass ); + protected boolean isRelevant(ModelClass modelClass) { + return isJavaEnabled(modelClass); } @Override - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return true; } - } diff --git a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedWriterGenerator.java b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedWriterGenerator.java index 9906cabea..07c2d9a78 100644 --- a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedWriterGenerator.java +++ b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ExtendedWriterGenerator.java @@ -1,7 +1,5 @@ package org.codehaus.modello.plugin.xpp3; -import org.codehaus.modello.plugin.ModelloGenerator; - /* * Copyright (c) 2004, Codehaus.org * @@ -24,6 +22,7 @@ * SOFTWARE. */ +import org.codehaus.modello.plugin.ModelloGenerator; import org.codehaus.modello.plugin.java.javasource.JClass; import org.codehaus.modello.plugin.java.javasource.JField; import org.codehaus.modello.plugin.java.javasource.JMethod; @@ -34,120 +33,115 @@ /** * The generator for XPP3-based writers that support input location tracking. - * + * * @author Hervé Boutemy * @since 1.10 */ -@Component( role = ModelloGenerator.class, hint = "xpp3-extended-writer" ) -public class Xpp3ExtendedWriterGenerator - extends Xpp3WriterGenerator -{ +@Component(role = ModelloGenerator.class, hint = "xpp3-extended-writer") +public class Xpp3ExtendedWriterGenerator extends Xpp3WriterGenerator { @Override - protected boolean isLocationTracking() - { + protected boolean isLocationTracking() { return true; } @Override - protected void prepareLocationTracking( JClass jClass ) - { - String packageName = locationTracker.getPackageName( isPackageWithVersion(), getGeneratedVersion() ); + protected void prepareLocationTracking(JClass jClass) { + String packageName = locationTracker.getPackageName(isPackageWithVersion(), getGeneratedVersion()); - jClass.addImport( packageName + '.' + locationTracker.getName() + "Tracker" ); - addModelImport( jClass, locationTracker, null ); + jClass.addImport(packageName + '.' + locationTracker.getName() + "Tracker"); + addModelImport(jClass, locationTracker, null); - createLocationTrackingMethod( jClass ); + createLocationTrackingMethod(jClass); - if ( requiresDomSupport && domAsXpp3 ) - { - createXpp3DomToSerializerMethod( jClass ); + if (requiresDomSupport && domAsXpp3) { + createXpp3DomToSerializerMethod(jClass); } } - private void createLocationTrackingMethod( JClass jClass ) - { - JMethod method = new JMethod( "writeLocationTracking" ); + private void createLocationTrackingMethod(JClass jClass) { + JMethod method = new JMethod("writeLocationTracking"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( locationTracker.getName() + "Tracker" ), "locationTracker" ) ); - method.addParameter( new JParameter( new JClass( "Object" ), "key" ) ); - method.addParameter( new JParameter( new JClass( "XmlSerializer" ), "serializer" ) ); + method.addParameter(new JParameter(new JType(locationTracker.getName() + "Tracker"), "locationTracker")); + method.addParameter(new JParameter(new JClass("Object"), "key")); + method.addParameter(new JParameter(new JClass("XmlSerializer"), "serializer")); - method.addException( new JClass( "java.io.IOException" ) ); + method.addException(new JClass("java.io.IOException")); JSourceCode sc = method.getSourceCode(); - sc.add( locationTracker.getName() + " location = ( locationTracker == null ) ? null : locationTracker.getLocation( key );" ); - sc.add( "if ( location != null )" ); - sc.add( "{" ); - sc.addIndented( "serializer.comment( toString( location ) );" ); - sc.add( "}" ); + sc.add(locationTracker.getName() + + " location = ( locationTracker == null ) ? null : locationTracker.getLocation( key );"); + sc.add("if ( location != null )"); + sc.add("{"); + sc.addIndented("serializer.comment( toString( location ) );"); + sc.add("}"); - jClass.addMethod( method ); + jClass.addMethod(method); - JField field = new JField( new JType( locationTracker.getName() + ".StringFormatter" ), "stringFormatter" ); + JField field = new JField(new JType(locationTracker.getName() + ".StringFormatter"), "stringFormatter"); field.getModifiers().makeProtected(); - jClass.addField( field ); + jClass.addField(field); - method = new JMethod( "setStringFormatter", null, null ); - method.addParameter( new JParameter( new JType( locationTracker.getName() + ".StringFormatter" ), "stringFormatter" ) ); + method = new JMethod("setStringFormatter", null, null); + method.addParameter( + new JParameter(new JType(locationTracker.getName() + ".StringFormatter"), "stringFormatter")); sc = method.getSourceCode(); - sc.add( "this.stringFormatter = stringFormatter;" ); - jClass.addMethod( method ); + sc.add("this.stringFormatter = stringFormatter;"); + jClass.addMethod(method); - method = new JMethod( "toString", new JType( "String" ), null ); + method = new JMethod("toString", new JType("String"), null); method.getModifiers().makeProtected(); - method.addParameter( new JParameter( new JType( locationTracker.getName() ), "location" ) ); + method.addParameter(new JParameter(new JType(locationTracker.getName()), "location")); sc = method.getSourceCode(); - sc.add( "if ( stringFormatter != null )" ); - sc.add( "{" ); - sc.addIndented( "return stringFormatter.toString( location );" ); - sc.add( "}" ); - sc.add( "return ' ' + " + ( ( sourceTracker == null ) ? "" : "location.getSource().toString() + ':' + " ) - + "location.getLineNumber() + ' ';" ); - - jClass.addMethod( method ); + sc.add("if ( stringFormatter != null )"); + sc.add("{"); + sc.addIndented("return stringFormatter.toString( location );"); + sc.add("}"); + sc.add("return ' ' + " + ((sourceTracker == null) ? "" : "location.getSource().toString() + ':' + ") + + "location.getLineNumber() + ' ';"); + + jClass.addMethod(method); } - private void createXpp3DomToSerializerMethod( JClass jClass ) - { - JMethod method = new JMethod( "writeXpp3DomToSerializer" ); + private void createXpp3DomToSerializerMethod(JClass jClass) { + JMethod method = new JMethod("writeXpp3DomToSerializer"); method.getModifiers().makeProtected(); - method.addParameter( new JParameter( new JClass( "Xpp3Dom" ), "dom" ) ); - method.addParameter( new JParameter( new JClass( "XmlSerializer" ), "serializer" ) ); + method.addParameter(new JParameter(new JClass("Xpp3Dom"), "dom")); + method.addParameter(new JParameter(new JClass("XmlSerializer"), "serializer")); - method.addException( new JClass( "java.io.IOException" ) ); + method.addException(new JClass("java.io.IOException")); JSourceCode sc = method.getSourceCode(); - sc.add( "serializer.startTag( NAMESPACE, dom.getName() );" ); - sc.add( "" ); - sc.add( "String[] attributeNames = dom.getAttributeNames();" ); - sc.add( "for ( String attributeName : attributeNames )" ); - sc.add( "{" ); - sc.addIndented( "serializer.attribute( NAMESPACE, attributeName, dom.getAttribute( attributeName ) );" ); - sc.add( "}" ); - sc.add( "for ( Xpp3Dom aChild : dom.getChildren() )" ); - sc.add( "{" ); - sc.addIndented( "writeXpp3DomToSerializer( aChild, serializer );" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( "String value = dom.getValue();" ); - sc.add( "if ( value != null )" ); - sc.add( "{" ); - sc.addIndented( "serializer.text( value );" ); - sc.add( "}" ); - sc.add( "" ); - sc.add( "serializer.endTag( NAMESPACE, dom.getName() );" ); - sc.add( "" ); - sc.add( "if ( dom.getInputLocation() != null && dom.getChildCount() == 0 )" ); - sc.add( "{" ); - sc.addIndented( "serializer.comment( toString( (InputLocation) dom.getInputLocation() ) );" ); - sc.add( "}" ); - - jClass.addMethod( method ); + sc.add("serializer.startTag( NAMESPACE, dom.getName() );"); + sc.add(""); + sc.add("String[] attributeNames = dom.getAttributeNames();"); + sc.add("for ( String attributeName : attributeNames )"); + sc.add("{"); + sc.addIndented("serializer.attribute( NAMESPACE, attributeName, dom.getAttribute( attributeName ) );"); + sc.add("}"); + sc.add("for ( Xpp3Dom aChild : dom.getChildren() )"); + sc.add("{"); + sc.addIndented("writeXpp3DomToSerializer( aChild, serializer );"); + sc.add("}"); + sc.add(""); + sc.add("String value = dom.getValue();"); + sc.add("if ( value != null )"); + sc.add("{"); + sc.addIndented("serializer.text( value );"); + sc.add("}"); + sc.add(""); + sc.add("serializer.endTag( NAMESPACE, dom.getName() );"); + sc.add(""); + sc.add("if ( dom.getInputLocation() != null && dom.getChildCount() == 0 )"); + sc.add("{"); + sc.addIndented("serializer.comment( toString( (InputLocation) dom.getInputLocation() ) );"); + sc.add("}"); + + jClass.addMethod(method); } } diff --git a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ReaderGenerator.java b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ReaderGenerator.java index dc7149d3e..41ed52ad1 100644 --- a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ReaderGenerator.java +++ b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3ReaderGenerator.java @@ -55,10 +55,8 @@ * @author Jason van Zyl * @author Emmanuel Venisse */ -@Component( role = ModelloGenerator.class, hint = "xpp3-reader" ) -public class Xpp3ReaderGenerator - extends AbstractXpp3Generator -{ +@Component(role = ModelloGenerator.class, hint = "xpp3-reader") +public class Xpp3ReaderGenerator extends AbstractXpp3Generator { private static final String SOURCE_PARAM = "source"; @@ -69,80 +67,63 @@ public class Xpp3ReaderGenerator private String trackingArgs; @Override - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { - super.initialize( model, parameters ); + protected void initialize(Model model, Properties parameters) throws ModelloException { + super.initialize(model, parameters); trackingArgs = locationField = ""; - if ( isLocationTracking() ) - { + if (isLocationTracking()) { locationField = - ( (ModelClassMetadata) locationTracker.getMetadata( ModelClassMetadata.ID ) ).getLocationTracker(); + ((ModelClassMetadata) locationTracker.getMetadata(ModelClassMetadata.ID)).getLocationTracker(); - if ( sourceTracker != null ) - { + if (sourceTracker != null) { trackingArgs += ", " + SOURCE_PARAM; } } - } - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); - try - { + try { generateXpp3Reader(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating XPP3 Reader.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating XPP3 Reader.", ex); } } - private void writeAllClassesReaders( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesReaders(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassReaders( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassReaders(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassReaders(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } - XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata( XmlClassMetadata.ID ); - if ( !rootElement && !xmlClassMetadata.isStandaloneRead() ) - { + XmlClassMetadata xmlClassMetadata = (XmlClassMetadata) modelClass.getMetadata(XmlClassMetadata.ID); + if (!rootElement && !xmlClassMetadata.isStandaloneRead()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); String readerMethodName = "read"; - if ( !rootElement ) - { + if (!rootElement) { readerMethodName += capClassName; } @@ -150,300 +131,293 @@ private void writeClassReaders( ModelClass modelClass, JClass jClass, boolean ro // Write the read(XmlPullParser,boolean) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + JMethod unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); JSourceCode sc = unmarshall.getSourceCode(); - String tagName = resolveTagName( modelClass ); - String variableName = uncapitalise( className ); + String tagName = resolveTagName(modelClass); + String variableName = uncapitalise(className); - if ( requiresDomSupport && !domAsXpp3 ) - { - sc.add( "if ( _doc_ == null )" ); - sc.add( "{" ); + if (requiresDomSupport && !domAsXpp3) { + sc.add("if ( _doc_ == null )"); + sc.add("{"); sc.indent(); - sc.add( "try" ); - sc.add( "{" ); - sc.addIndented( "initDoc();" ); - sc.add( "}" ); - sc.add( "catch ( javax.xml.parsers.ParserConfigurationException pce )" ); - sc.add( "{" ); + sc.add("try"); + sc.add("{"); + sc.addIndented("initDoc();"); + sc.add("}"); + sc.add("catch ( javax.xml.parsers.ParserConfigurationException pce )"); + sc.add("{"); sc.addIndented( - "throw new XmlPullParserException( \"Unable to create DOM document: \" + pce.getMessage(), parser, pce );" ); - sc.add( "}" ); + "throw new XmlPullParserException( \"Unable to create DOM document: \" + pce.getMessage(), parser, pce );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - - sc.add( className + ' ' + variableName + " = null;" ); - sc.add( "int eventType = parser.getEventType();" ); - - sc.add( "boolean parsed = false;" ); + sc.add(className + ' ' + variableName + " = null;"); + + sc.add("int eventType = parser.getEventType();"); - sc.add( "while ( eventType != XmlPullParser.END_DOCUMENT )" ); + sc.add("boolean parsed = false;"); - sc.add( "{" ); + sc.add("while ( eventType != XmlPullParser.END_DOCUMENT )"); + + sc.add("{"); sc.indent(); - sc.add( "if ( eventType == XmlPullParser.START_TAG )" ); + sc.add("if ( eventType == XmlPullParser.START_TAG )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict && ! \"" + tagName + "\".equals( parser.getName() ) )" ); + sc.add("if ( strict && ! \"" + tagName + "\".equals( parser.getName() ) )"); - sc.add( "{" ); - sc.addIndented( "throw new XmlPullParserException( \"Expected root element '" + tagName + "' but " - + "found '\" + parser.getName() + \"'\", parser, null );" ); - sc.add( "}" ); - - sc.add( "else if ( parsed )" ); + sc.add("{"); + sc.addIndented("throw new XmlPullParserException( \"Expected root element '" + tagName + "' but " + + "found '\" + parser.getName() + \"'\", parser, null );"); + sc.add("}"); - sc.add( "{" ); - sc.addIndented( "// fallback, already expected a XmlPullParserException due to invalid XML" ); - sc.addIndented( "throw new XmlPullParserException( \"Duplicated tag: '" + tagName + "'\", parser, null );" ); - sc.add( "}" ); + sc.add("else if ( parsed )"); + + sc.add("{"); + sc.addIndented("// fallback, already expected a XmlPullParserException due to invalid XML"); + sc.addIndented("throw new XmlPullParserException( \"Duplicated tag: '" + tagName + "'\", parser, null );"); + sc.add("}"); - sc.add( variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );" ); + sc.add(variableName + " = parse" + capClassName + "( parser, strict" + trackingArgs + " );"); - if ( rootElement ) - { - sc.add( variableName + ".setModelEncoding( parser.getInputEncoding() );" ); + if (rootElement) { + sc.add(variableName + ".setModelEncoding( parser.getInputEncoding() );"); } - sc.add( "parsed = true;" ); + sc.add("parsed = true;"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "eventType = parser.next();" ); + sc.add("eventType = parser.next();"); sc.unindent(); - sc.add( "}" ); - - sc.add( "if ( parsed )" ); - sc.add( "{" ); - sc.addIndented( "return " + variableName + ';' ); - sc.add( "}" ); + sc.add("}"); + + sc.add("if ( parsed )"); + sc.add("{"); + sc.addIndented("return " + variableName + ';'); + sc.add("}"); - sc.add( "throw new XmlPullParserException( \"Expected root element '" + tagName + "' but " - + "found no element at all: invalid XML document\", parser, null );" ); + sc.add("throw new XmlPullParserException( \"Expected root element '" + tagName + "' but " + + "found no element at all: invalid XML document\", parser, null );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- // Write the read(Reader[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); - unmarshall.setComment( "@see ReaderFactory#newXmlReader" ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); + unmarshall.setComment("@see ReaderFactory#newXmlReader"); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); sc = unmarshall.getSourceCode(); - sc.add("XmlPullParser parser = addDefaultEntities ? new MXParser(EntityReplacementMap.defaultEntityReplacementMap) : new MXParser( );"); + sc.add( + "XmlPullParser parser = addDefaultEntities ? new MXParser(EntityReplacementMap.defaultEntityReplacementMap) : new MXParser( );"); - sc.add( "" ); + sc.add(""); - sc.add( "parser.setInput( reader );" ); + sc.add("parser.setInput( reader );"); - sc.add( "" ); + sc.add(""); - sc.add( "" ); + sc.add(""); - sc.add( "return " + readerMethodName + "( parser, strict" + trackingArgs + " );" ); + sc.add("return " + readerMethodName + "( parser, strict" + trackingArgs + " );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // ---------------------------------------------------------------------- - if ( locationTracker == null ) - { - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); - unmarshall.setComment( "@see ReaderFactory#newXmlReader" ); + if (locationTracker == null) { + unmarshall = new JMethod(readerMethodName, new JClass(className), null); + unmarshall.setComment("@see ReaderFactory#newXmlReader"); - unmarshall.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) ); + unmarshall.addParameter(new JParameter(new JClass("Reader"), "reader")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( reader, true );" ); + sc.add("return " + readerMethodName + "( reader, true );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } // ---------------------------------------------------------------------- // Write the read(InputStream[,boolean]) methods which will do the unmarshalling. // ---------------------------------------------------------------------- - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( ReaderFactory.newXmlReader( in ), strict" + trackingArgs + " );" ); + sc.add("return " + readerMethodName + "( ReaderFactory.newXmlReader( in ), strict" + trackingArgs + " );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); // -------------------------------------------------------------------- - if ( locationTracker == null ) - { - unmarshall = new JMethod( readerMethodName, new JClass( className ), null ); + if (locationTracker == null) { + unmarshall = new JMethod(readerMethodName, new JClass(className), null); - unmarshall.addParameter( new JParameter( new JClass( "InputStream" ), "in" ) ); + unmarshall.addParameter(new JParameter(new JClass("InputStream"), "in")); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); sc = unmarshall.getSourceCode(); - sc.add( "return " + readerMethodName + "( ReaderFactory.newXmlReader( in ) );" ); + sc.add("return " + readerMethodName + "( ReaderFactory.newXmlReader( in ) );"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } } - private void generateXpp3Reader() - throws ModelloException, IOException - { + private void generateXpp3Reader() throws ModelloException, IOException { Model objectModel = getModel(); String packageName = - objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) + ".io.xpp3"; + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.xpp3"; - String unmarshallerName = getFileName( "Xpp3Reader" + ( isLocationTracking() ? "Ex" : "" ) ); + String unmarshallerName = getFileName("Xpp3Reader" + (isLocationTracking() ? "Ex" : "")); - JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, unmarshallerName); - JClass jClass = new JClass( packageName + '.' + unmarshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + unmarshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "org.codehaus.plexus.util.ReaderFactory" ); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.MXParser" ); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.EntityReplacementMap" ); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.XmlPullParser" ); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.XmlPullParserException" ); - jClass.addImport( "java.io.InputStream" ); - jClass.addImport( "java.io.IOException" ); - jClass.addImport( "java.io.Reader" ); - jClass.addImport( "java.text.DateFormat" ); + jClass.addImport("org.codehaus.plexus.util.ReaderFactory"); + jClass.addImport("org.codehaus.plexus.util.xml.pull.MXParser"); + jClass.addImport("org.codehaus.plexus.util.xml.pull.EntityReplacementMap"); + jClass.addImport("org.codehaus.plexus.util.xml.pull.XmlPullParser"); + jClass.addImport("org.codehaus.plexus.util.xml.pull.XmlPullParserException"); + jClass.addImport("java.io.InputStream"); + jClass.addImport("java.io.IOException"); + jClass.addImport("java.io.Reader"); + jClass.addImport("java.text.DateFormat"); - addModelImports( jClass, null ); + addModelImports(jClass, null); // ---------------------------------------------------------------------- // Write option setters // ---------------------------------------------------------------------- JConstructor constructor2 = new JConstructor(jClass); - constructor2.getSourceCode().add( "this( new ContentTransformer()\n" + " {\n" - + " public String transform( String source, String fieldName )\n" - + " {\n" + " return source;\n" - + " }\n" + " } );" ); - jClass.addConstructor( constructor2 ); - + constructor2 + .getSourceCode() + .add("this( new ContentTransformer()\n" + " {\n" + + " public String transform( String source, String fieldName )\n" + + " {\n" + " return source;\n" + + " }\n" + " } );"); + jClass.addConstructor(constructor2); JConstructor constructor = new JConstructor(jClass); - constructor.addParameter( new JParameter( new JType("ContentTransformer"), "contentTransformer" ) ); - constructor.getSourceCode().add( "this.contentTransformer = contentTransformer;" ); - jClass.addConstructor( constructor ); - - jClass.addSourceCode( "public static interface ContentTransformer\n" + "{\n" + " /**\n" - + " * Interpolate the value read from the xpp3 document\n" - + " * @param source The source value\n" - + " * @param fieldName A description of the field being interpolated. The implementation may use this to\n" - + " * log stuff.\n" - + " * @return The interpolated value.\n" + " */\n" - + " String transform( String source, String fieldName );\n" + "}\n"); + constructor.addParameter(new JParameter(new JType("ContentTransformer"), "contentTransformer")); + constructor.getSourceCode().add("this.contentTransformer = contentTransformer;"); + jClass.addConstructor(constructor); + + jClass.addSourceCode("public static interface ContentTransformer\n" + "{\n" + " /**\n" + + " * Interpolate the value read from the xpp3 document\n" + + " * @param source The source value\n" + + " * @param fieldName A description of the field being interpolated. The implementation may use this to\n" + + " * log stuff.\n" + + " * @return The interpolated value.\n" + " */\n" + + " String transform( String source, String fieldName );\n" + "}\n"); // The Field - JField addDefaultEntities = new JField( JType.BOOLEAN, "addDefaultEntities" ); + JField addDefaultEntities = new JField(JType.BOOLEAN, "addDefaultEntities"); addDefaultEntities.setComment( - "If set the parser will be loaded with all single characters from the XHTML specification.\n" - + "The entities used:\n" + "
    \n" + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent
  • \n" - + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent
  • \n" - + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent
  • \n" + "
\n" ); + "If set the parser will be loaded with all single characters from the XHTML specification.\n" + + "The entities used:\n" + "
    \n" + + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent
  • \n" + + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent
  • \n" + + "
  • http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent
  • \n" + "
\n"); - addDefaultEntities.setInitString( "true" ); + addDefaultEntities.setInitString("true"); + jClass.addField(addDefaultEntities); - jClass.addField( addDefaultEntities ); - - JField contentTransformer = new JField( new JType("ContentTransformer"), "contentTransformer" ); + JField contentTransformer = new JField(new JType("ContentTransformer"), "contentTransformer"); JModifiers jModifiers = new JModifiers(); - jModifiers.setFinal( true ); - contentTransformer.setModifiers( jModifiers ); - - jClass.addField( contentTransformer ); + jModifiers.setFinal(true); + contentTransformer.setModifiers(jModifiers); + jClass.addField(contentTransformer); // The setter - JMethod addDefaultEntitiesSetter = new JMethod( "setAddDefaultEntities" ); + JMethod addDefaultEntitiesSetter = new JMethod("setAddDefaultEntities"); - addDefaultEntitiesSetter.addParameter( new JParameter( JType.BOOLEAN, "addDefaultEntities" ) ); + addDefaultEntitiesSetter.addParameter(new JParameter(JType.BOOLEAN, "addDefaultEntities")); - addDefaultEntitiesSetter.setSourceCode( "this.addDefaultEntities = addDefaultEntities;" ); + addDefaultEntitiesSetter.setSourceCode("this.addDefaultEntities = addDefaultEntities;"); - addDefaultEntitiesSetter.setComment( "Sets the state of the \"add default entities\" flag." ); + addDefaultEntitiesSetter.setComment("Sets the state of the \"add default entities\" flag."); - jClass.addMethod( addDefaultEntitiesSetter ); + jClass.addMethod(addDefaultEntitiesSetter); // The getter - JMethod addDefaultEntitiesGetter = new JMethod( "getAddDefaultEntities", JType.BOOLEAN, null ); + JMethod addDefaultEntitiesGetter = new JMethod("getAddDefaultEntities", JType.BOOLEAN, null); - addDefaultEntitiesGetter.setComment( "Returns the state of the \"add default entities\" flag." ); + addDefaultEntitiesGetter.setComment("Returns the state of the \"add default entities\" flag."); - addDefaultEntitiesGetter.setSourceCode( "return addDefaultEntities;" ); + addDefaultEntitiesGetter.setSourceCode("return addDefaultEntities;"); - jClass.addMethod( addDefaultEntitiesGetter ); + jClass.addMethod(addDefaultEntitiesGetter); // ---------------------------------------------------------------------- // Write the class parsers // ---------------------------------------------------------------------- - writeAllClassesParser( objectModel, jClass ); + writeAllClassesParser(objectModel, jClass); // ---------------------------------------------------------------------- // Write the class readers // ---------------------------------------------------------------------- - writeAllClassesReaders( objectModel, jClass ); + writeAllClassesReaders(objectModel, jClass); // ---------------------------------------------------------------------- // Write helpers // ---------------------------------------------------------------------- - writeHelpers( jClass ); + writeHelpers(jClass); - if ( requiresDomSupport ) - { - writeBuildDomMethod( jClass ); + if (requiresDomSupport) { + writeBuildDomMethod(jClass); - if ( isLocationTracking() ) - { - writeBuildDomLocationTrackingMethod( jClass ); + if (isLocationTracking()) { + writeBuildDomLocationTrackingMethod(jClass); } } @@ -451,183 +425,177 @@ private void generateXpp3Reader() // // ---------------------------------------------------------------------- - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClassesParser( Model objectModel, JClass jClass ) - { - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() ); + private void writeAllClassesParser(Model objectModel, JClass jClass) { + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - for ( ModelClass clazz : getClasses( objectModel ) ) - { - if ( isTrackingSupport( clazz ) ) - { + for (ModelClass clazz : getClasses(objectModel)) { + if (isTrackingSupport(clazz)) { continue; } - writeClassParser( clazz, jClass, root.getName().equals( clazz.getName() ) ); + writeClassParser(clazz, jClass, root.getName().equals(clazz.getName())); } } - private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement ) - { + private void writeClassParser(ModelClass modelClass, JClass jClass, boolean rootElement) { JavaClassMetadata javaClassMetadata = - (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.class.getName() ); + (JavaClassMetadata) modelClass.getMetadata(JavaClassMetadata.class.getName()); // Skip abstract classes, no way to parse them out into objects - if ( javaClassMetadata.isAbstract() ) - { + if (javaClassMetadata.isAbstract()) { return; } String className = modelClass.getName(); - String capClassName = capitalise( className ); + String capClassName = capitalise(className); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null ); + JMethod unmarshall = new JMethod("parse" + capClassName, new JClass(className), null); unmarshall.getModifiers().makePrivate(); - unmarshall.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - unmarshall.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); - addTrackingParameters( unmarshall ); + unmarshall.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + unmarshall.addParameter(new JParameter(JClass.BOOLEAN, "strict")); + addTrackingParameters(unmarshall); - unmarshall.addException( new JClass( "IOException" ) ); - unmarshall.addException( new JClass( "XmlPullParserException" ) ); + unmarshall.addException(new JClass("IOException")); + unmarshall.addException(new JClass("XmlPullParserException")); JSourceCode sc = unmarshall.getSourceCode(); - sc.add( "String tagName = parser.getName();" ); - sc.add( className + " " + uncapClassName + " = new " + className + "();" ); + sc.add("String tagName = parser.getName();"); + sc.add(className + " " + uncapClassName + " = new " + className + "();"); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + ";" ); - writeNewSetLocation( "\"\"", uncapClassName, null, sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + ";"); + writeNewSetLocation("\"\"", uncapClassName, null, sc); } ModelField contentField = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // read all XML attributes first - contentField = writeClassAttributesParser( modelFields, uncapClassName, rootElement, sc, jClass ); + contentField = writeClassAttributesParser(modelFields, uncapClassName, rootElement, sc, jClass); // then read content, either content field or elements - if ( contentField != null ) - { - writePrimitiveField( contentField, contentField.getType(), uncapClassName, uncapClassName, "\"\"", - "set" + capitalise( contentField.getName() ), sc ); - } - else - { - //Write other fields - - sc.add( "java.util.Set parsed = new java.util.HashSet();" ); - - sc.add( "while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG )" ); - - sc.add( "{" ); + if (contentField != null) { + writePrimitiveField( + contentField, + contentField.getType(), + uncapClassName, + uncapClassName, + "\"\"", + "set" + capitalise(contentField.getName()), + sc); + } else { + // Write other fields + + sc.add("java.util.Set parsed = new java.util.HashSet();"); + + sc.add("while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG )"); + + sc.add("{"); sc.indent(); boolean addElse = false; - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( !xmlFieldMetadata.isAttribute() ) - { - processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass ); + if (!xmlFieldMetadata.isAttribute()) { + processField(field, xmlFieldMetadata, addElse, sc, uncapClassName, jClass); addElse = true; } } - if ( addElse ) - { - sc.add( "else" ); + if (addElse) { + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.indent(); } - sc.add( "checkUnknownElement( parser, strict );" ); + sc.add("checkUnknownElement( parser, strict );"); - if ( addElse ) - { + if (addElse) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - sc.add( "return " + uncapClassName + ";" ); + sc.add("return " + uncapClassName + ";"); - jClass.addMethod( unmarshall ); + jClass.addMethod(unmarshall); } - private ModelField writeClassAttributesParser( List modelFields, String objectName, boolean rootElement, - JSourceCode sc, JClass jClass ) - { + private ModelField writeClassAttributesParser( + List modelFields, String objectName, boolean rootElement, JSourceCode sc, JClass jClass) { ModelField contentField = null; - sc.add( "for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- )" ); - sc.add( "{" ); + sc.add("for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- )"); + sc.add("{"); sc.indent(); - sc.add( "String name = parser.getAttributeName( i );" ); - sc.add( "String value = parser.getAttributeValue( i );" ); - sc.add( "" ); + sc.add("String name = parser.getAttributeName( i );"); + sc.add("String value = parser.getAttributeValue( i );"); + sc.add(""); sc.add("if ( name.indexOf( ':' ) >= 0 )"); sc.add("{"); sc.addIndented("// just ignore attributes with non-default namespace (for example: xmlns:xsi)"); sc.add("}"); - if ( rootElement ) - { - sc.add( "else if ( \"xmlns\".equals( name ) )" ); - sc.add( "{" ); - sc.addIndented( "// ignore xmlns attribute in root class, which is a reserved attribute name" ); - sc.add( "}" ); + if (rootElement) { + sc.add("else if ( \"xmlns\".equals( name ) )"); + sc.add("{"); + sc.addIndented("// ignore xmlns attribute in root class, which is a reserved attribute name"); + sc.add("}"); } - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isAttribute() ) - { - String tagName = resolveTagName( field, xmlFieldMetadata ); + if (xmlFieldMetadata.isAttribute()) { + String tagName = resolveTagName(field, xmlFieldMetadata); - sc.add( "else if ( \"" + tagName + "\".equals( name ) )" ); - sc.add( "{" ); + sc.add("else if ( \"" + tagName + "\".equals( name ) )"); + sc.add("{"); sc.indent(); - writePrimitiveField( field, field.getType(), objectName, objectName, "\"" + field.getName() + "\"", - "set" + capitalise( field.getName() ), sc ); + writePrimitiveField( + field, + field.getType(), + objectName, + objectName, + "\"" + field.getName() + "\"", + "set" + capitalise(field.getName()), + sc); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } // TODO check if we have already one with this type and throws Exception - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; } } - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); + sc.add("{"); sc.addIndented("checkUnknownAttribute( parser, name, tagName, strict );"); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); return contentField; } @@ -642,688 +610,622 @@ private ModelField writeClassAttributesParser( List modelFields, Str * @param objectName the object name in the source * @param jClass the generated class source file */ - private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc, - String objectName, JClass jClass ) - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void processField( + ModelField field, + XmlFieldMetadata xmlFieldMetadata, + boolean addElse, + JSourceCode sc, + String objectName, + JClass jClass) { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String capFieldName = capitalise( field.getName() ); + String capFieldName = capitalise(field.getName()); - String singularName = singular( field.getName() ); + String singularName = singular(field.getName()); String alias; - if ( StringUtils.isEmpty( field.getAlias() ) ) - { + if (StringUtils.isEmpty(field.getAlias())) { alias = "null"; - } - else - { + } else { alias = "\"" + field.getAlias() + "\""; } - String tagComparison = - ( addElse ? "else " : "" ) + "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + "\", " + alias - + ", parsed ) )"; + String tagComparison = (addElse ? "else " : "") + "if ( checkFieldWithDuplicate( parser, \"" + fieldTagName + + "\", " + alias + ", parsed ) )"; - if ( !( field instanceof ModelAssociation ) ) - { // model field - sc.add( tagComparison ); + if (!(field instanceof ModelAssociation)) { // model field + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writePrimitiveField( field, field.getType(), objectName, objectName, "\"" + field.getName() + "\"", - "set" + capFieldName, sc ); + writePrimitiveField( + field, + field.getType(), + objectName, + objectName, + "\"" + field.getName() + "\"", + "set" + capFieldName, + sc); sc.unindent(); - sc.add( "}" ); - } - else - { // model association + sc.add("}"); + } else { // model association ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( tagComparison ); + if (association.isOneMultiplicity()) { + sc.add(tagComparison); - sc.add( "{" ); - sc.addIndented( - objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict" - + trackingArgs + " ) );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented(objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( parser, strict" + + trackingArgs + " ) );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); String type = association.getType(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - boolean inModel = isClassInModel( association.getTo(), field.getModelClass().getModel() ); + boolean inModel = isClassInModel( + association.getTo(), field.getModelClass().getModel()); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) association.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = + (JavaFieldMetadata) association.getMetadata(JavaFieldMetadata.ID); - final boolean useJava5 = hasJavaSourceSupport( 5 ); + final boolean useJava5 = hasJavaSourceSupport(5); String adder; boolean requireSetter = false; - if ( wrappedItems ) - { - sc.add( tagComparison ); + if (wrappedItems) { + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( javaFieldMetadata.isSetter() ) - { - String associationType = type; - String defaultValue = association.getDefaultValue(); - if( useJava5 ) - { - // defaultValue looks like java.util.ArrayList/**/() - defaultValue = defaultValue.replace("/*", "").replace("*/", ""); - - associationType = type + '<' + association.getTo() + '>'; + if (javaFieldMetadata.isSetter()) { + String associationType = type; + String defaultValue = association.getDefaultValue(); + if (useJava5) { + // defaultValue looks like java.util.ArrayList/**/() + defaultValue = defaultValue.replace("/*", "").replace("*/", ""); + + associationType = type + '<' + association.getTo() + '>'; } - sc.add( associationType + " " + associationName + " = " + defaultValue + ";" ); + sc.add(associationType + " " + associationName + " = " + defaultValue + ";"); requireSetter = true; adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } - if ( !inModel && locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s;" ); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + if (!inModel && locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s;"); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); } - sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" ); + sc.add("while ( parser.nextTag() == XmlPullParser.START_TAG )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"" + valuesTagName + "\".equals( parser.getName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( parser.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - } - else - { - sc.add( ( addElse ? "else " : "" ) + "if ( \"" + valuesTagName - + "\".equals( parser.getName() ) )" ); + } else { + sc.add((addElse ? "else " : "") + "if ( \"" + valuesTagName + + "\".equals( parser.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter() ) - { - String associationType = type; + if (javaFieldMetadata.isGetter() && javaFieldMetadata.isSetter()) { + String associationType = type; String defaultValue = association.getDefaultValue(); - if( useJava5 ) - { - // defaultValue looks like java.util.ArrayList/**/() - defaultValue = defaultValue.replace("/*", "").replace("*/", ""); - - associationType = type + '<' + association.getTo() + '>'; + if (useJava5) { + // defaultValue looks like java.util.ArrayList/**/() + defaultValue = defaultValue.replace("/*", "").replace("*/", ""); + + associationType = type + '<' + association.getTo() + '>'; } - - sc.add( associationType + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" ); - sc.add( "if ( " + associationName + " == null )" ); + sc.add(associationType + " " + associationName + " = " + objectName + ".get" + capFieldName + + "();"); - sc.add( "{" ); + sc.add("if ( " + associationName + " == null )"); + + sc.add("{"); sc.indent(); - - sc.add( associationName + " = " + defaultValue + ";" ); + + sc.add(associationName + " = " + defaultValue + ";"); requireSetter = true; - + sc.unindent(); - sc.add( "}" ); + sc.add("}"); adder = associationName + ".add"; - } - else - { + } else { adder = objectName + ".add" + association.getTo(); } - if ( !inModel && locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" - + capitalise( singular( locationField ) ) + "( \"" + field.getName() - + "\" );" ); - sc.add( "if ( " + LOCATION_VAR + "s == null )" ); - sc.add( "{" ); + if (!inModel && locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s = " + objectName + ".get" + + capitalise(singular(locationField)) + "( \"" + field.getName() + + "\" );"); + sc.add("if ( " + LOCATION_VAR + "s == null )"); + sc.add("{"); sc.indent(); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - if ( inModel ) - { - sc.add( adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );" ); - } - else - { + if (inModel) { + sc.add(adder + "( parse" + association.getTo() + "( parser, strict" + trackingArgs + " ) );"); + } else { String key; - if ( ModelDefault.SET.equals( type ) ) - { + if (ModelDefault.SET.equals(type)) { key = "?"; + } else { + key = (useJava5 ? "Integer.valueOf" : "new java.lang.Integer") + "( " + associationName + + ".size() )"; } - else - { - key = ( useJava5 ? "Integer.valueOf" : "new java.lang.Integer" ) + "( " + associationName - + ".size() )"; - } - writePrimitiveField( association, association.getTo(), associationName, LOCATION_VAR + "s", key, - "add", sc ); + writePrimitiveField( + association, association.getTo(), associationName, LOCATION_VAR + "s", key, "add", sc); } - if ( wrappedItems ) - { + if (wrappedItems) { sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.addIndented( "checkUnknownElement( parser, strict );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("checkUnknownElement( parser, strict );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } - if (requireSetter) - { - sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" ); + if (requireSetter) { + sc.add(objectName + ".set" + capFieldName + "( " + associationName + " );"); } sc.unindent(); - sc.add( "}" ); - - } - else - { - //Map or Properties + sc.add("}"); + + } else { + // Map or Properties - sc.add( tagComparison ); + sc.add(tagComparison); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( locationTracker != null ) - { - sc.add( locationTracker.getName() + " " + LOCATION_VAR + "s;" ); - writeNewSetLocation( field, objectName, LOCATION_VAR + "s", sc ); + if (locationTracker != null) { + sc.add(locationTracker.getName() + " " + LOCATION_VAR + "s;"); + writeNewSetLocation(field, objectName, LOCATION_VAR + "s", sc); } - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("while ( parser.nextTag() == XmlPullParser.START_TAG )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"" + valuesTagName + "\".equals( parser.getName() ) )" ); + sc.add("if ( \"" + valuesTagName + "\".equals( parser.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = null;" ); + sc.add("String key = null;"); - sc.add( "String value = null;" ); + sc.add("String value = null;"); - writeNewLocation( LOCATION_VAR, sc ); + writeNewLocation(LOCATION_VAR, sc); - sc.add( "// " + xmlAssociationMetadata.getMapStyle() + " mode." ); + sc.add("// " + xmlAssociationMetadata.getMapStyle() + " mode."); - sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" ); + sc.add("while ( parser.nextTag() == XmlPullParser.START_TAG )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( \"key\".equals( parser.getName() ) )" ); + sc.add("if ( \"key\".equals( parser.getName() ) )"); - sc.add( "{" ); - sc.addIndented( "key = parser.nextText();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("key = parser.nextText();"); + sc.add("}"); - sc.add( "else if ( \"value\".equals( parser.getName() ) )" ); + sc.add("else if ( \"value\".equals( parser.getName() ) )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - writeNewLocation( LOCATION_VAR, sc ); - sc.add( "value = parser.nextText()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + writeNewLocation(LOCATION_VAR, sc); + sc.add("value = parser.nextText()" + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "else" ); + sc.add("else"); - sc.add( "{" ); - sc.addIndented( "parser.nextText();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("parser.nextText();"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); - writeSetLocation( "key", LOCATION_VAR + "s", LOCATION_VAR, sc ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); + writeSetLocation("key", LOCATION_VAR + "s", LOCATION_VAR, sc); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "parser.next();" ); + sc.add("parser.next();"); sc.unindent(); - sc.add( "}" ); - } - else - { - //INLINE Mode + sc.add("}"); + } else { + // INLINE Mode - sc.add( "while ( parser.nextTag() == XmlPullParser.START_TAG )" ); + sc.add("while ( parser.nextTag() == XmlPullParser.START_TAG )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = parser.getName();" ); + sc.add("String key = parser.getName();"); - writeNewSetLocation( "key", LOCATION_VAR + "s", null, sc ); + writeNewSetLocation("key", LOCATION_VAR + "s", null, sc); - sc.add( - "String value = parser.nextText()" + ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" ); + sc.add("String value = parser.nextText()" + (xmlFieldMetadata.isTrim() ? ".trim()" : "") + ";"); - sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" ); + sc.add(objectName + ".add" + capitalise(singularName) + "( key, value );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } } } - private void writePrimitiveField( ModelField field, String type, String objectName, String locatorName, - String locationKey, String setterName, JSourceCode sc ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + private void writePrimitiveField( + ModelField field, + String type, + String objectName, + String locatorName, + String locationKey, + String setterName, + JSourceCode sc) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); String tagName = resolveTagName(field, xmlFieldMetadata); String parserGetter; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { parserGetter = "value"; // local variable created in the parsing block - } - else - { + } else { parserGetter = "parser.nextText()"; } -/* TODO: this and a default - if ( xmlFieldMetadata.isRequired() ) - { - parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; - } -*/ + /* TODO: this and a default + if ( xmlFieldMetadata.isRequired() ) + { + parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict )"; + } + */ - if ( xmlFieldMetadata.isTrim() ) - { + if (xmlFieldMetadata.isTrim()) { parserGetter = "interpolatedTrimmed( " + parserGetter + ", \"" + tagName + "\" )"; } String keyCapture = ""; - writeNewLocation( null, sc ); - if ( locationTracker != null && "?".equals( locationKey ) ) - { - if ( hasJavaSourceSupport( 5 ) ) - { - sc.add( type + " _key;" ); - } - else - { - sc.add( "Object _key;" ); - } + writeNewLocation(null, sc); + if (locationTracker != null && "?".equals(locationKey)) { + if (hasJavaSourceSupport(5)) { + sc.add(type + " _key;"); + } else { + sc.add("Object _key;"); + } locationKey = "_key"; keyCapture = "_key = "; - } - else - { - writeSetLocation( locationKey, locatorName, null, sc ); + } else { + writeSetLocation(locationKey, locatorName, null, sc); } - if ( "boolean".equals( type ) || "Boolean".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( " + keyCapture + "getBooleanValue( " + parserGetter + ", \"" - + tagName + "\", parser, \"" + field.getDefaultValue() + "\" ) );" ); - } - else if ( "char".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( " + keyCapture + "getCharacterValue( " + parserGetter + ", \"" - + tagName + "\", parser ) );" ); - } - else if ( "double".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getDoubleValue( " + parserGetter + ", \"" + tagName - + "\", parser, strict ) );" ); - } - else if ( "float".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getFloatValue( " + parserGetter + ", \"" + tagName - + "\", parser, strict ) );" ); - } - else if ( "int".equals( type ) ) - { - sc.add( objectName + "." + setterName + "( " + keyCapture + "getIntegerValue( " + parserGetter + ", \"" - + tagName + "\", parser, strict ) );" ); - } - else if ( "long".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getLongValue( " + parserGetter + ", \"" + tagName - + "\", parser, strict ) );" ); - } - else if ( "short".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getShortValue( " + parserGetter + ", \"" + tagName - + "\", parser, strict ) );" ); - } - else if ( "byte".equals( type ) ) - { - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getByteValue( " + parserGetter + ", \"" + tagName - + "\", parser, strict ) );" ); - } - else if ( "String".equals( type ) ) - { + if ("boolean".equals(type) || "Boolean".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getBooleanValue( " + parserGetter + ", \"" + + tagName + "\", parser, \"" + field.getDefaultValue() + "\" ) );"); + } else if ("char".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getCharacterValue( " + parserGetter + ", \"" + + tagName + "\", parser ) );"); + } else if ("double".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getDoubleValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("float".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getFloatValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("int".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getIntegerValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("long".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getLongValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("short".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getShortValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("byte".equals(type)) { + sc.add(objectName + "." + setterName + "( " + keyCapture + "getByteValue( " + parserGetter + ", \"" + + tagName + "\", parser, strict ) );"); + } else if ("String".equals(type)) { // TODO: other Primitive types - sc.add( objectName + "." + setterName + "( " + keyCapture + parserGetter + " );" ); - } - else if ( "Date".equals( type ) ) - { + sc.add(objectName + "." + setterName + "( " + keyCapture + parserGetter + " );"); + } else if ("Date".equals(type)) { String format = xmlFieldMetadata.getFormat(); - sc.add( "String dateFormat = " + ( format != null ? "\"" + format + "\"" : "null" ) + ";" ); - sc.add( - objectName + "." + setterName + "( " + keyCapture + "getDateValue( " + parserGetter + ", \"" + tagName - + "\", dateFormat, parser ) );" ); - } - else if ( "DOM".equals( type ) ) - { + sc.add("String dateFormat = " + (format != null ? "\"" + format + "\"" : "null") + ";"); + sc.add(objectName + "." + setterName + "( " + keyCapture + "getDateValue( " + parserGetter + ", \"" + + tagName + "\", dateFormat, parser ) );"); + } else if ("DOM".equals(type)) { String locationBuilderParam = ""; - if ( isLocationTracking() && domAsXpp3 ) - { + if (isLocationTracking() && domAsXpp3) { locationBuilderParam = ", new Xpp3DomBuilderInputLocationBuilder( " + LOCATION_VAR + " )"; } - sc.add( objectName + "." + setterName + "( " + keyCapture - + ( domAsXpp3 ? "org.codehaus.plexus.util.xml.Xpp3DomBuilder.build" : "buildDom" ) - + "( parser, " + xmlFieldMetadata.isTrim() + locationBuilderParam + " ) );" ); + sc.add(objectName + "." + setterName + "( " + keyCapture + + (domAsXpp3 ? "org.codehaus.plexus.util.xml.Xpp3DomBuilder.build" : "buildDom") + + "( parser, " + xmlFieldMetadata.isTrim() + locationBuilderParam + " ) );"); requiresDomSupport = true; - } - else - { - throw new IllegalArgumentException( "Unknown type: " + type ); + } else { + throw new IllegalArgumentException("Unknown type: " + type); } - if ( keyCapture.length() > 0 ) - { - writeSetLocation( locationKey, locatorName, null, sc ); + if (keyCapture.length() > 0) { + writeSetLocation(locationKey, locatorName, null, sc); } } - private void writeBuildDomMethod( JClass jClass ) - { - if ( domAsXpp3 ) - { + private void writeBuildDomMethod(JClass jClass) { + if (domAsXpp3) { // no need, Xpp3DomBuilder provided by plexus-utils return; } - jClass.addField( new JField( new JClass( "org.w3c.dom.Document" ), "_doc_" ) ); - JMethod method = new JMethod( "initDoc", null, null ); + jClass.addField(new JField(new JClass("org.w3c.dom.Document"), "_doc_")); + JMethod method = new JMethod("initDoc", null, null); method.getModifiers().makePrivate(); - method.addException( new JClass( "javax.xml.parsers.ParserConfigurationException" ) ); + method.addException(new JClass("javax.xml.parsers.ParserConfigurationException")); JSourceCode sc = method.getSourceCode(); sc.add( - "javax.xml.parsers.DocumentBuilderFactory dbfac = javax.xml.parsers.DocumentBuilderFactory.newInstance();" ); - sc.add( "javax.xml.parsers.DocumentBuilder docBuilder = dbfac.newDocumentBuilder();" ); - sc.add( "_doc_ = docBuilder.newDocument();" ); - jClass.addMethod( method ); + "javax.xml.parsers.DocumentBuilderFactory dbfac = javax.xml.parsers.DocumentBuilderFactory.newInstance();"); + sc.add("javax.xml.parsers.DocumentBuilder docBuilder = dbfac.newDocumentBuilder();"); + sc.add("_doc_ = docBuilder.newDocument();"); + jClass.addMethod(method); String type = "org.w3c.dom.Element"; - method = new JMethod( "buildDom", new JType( type ), null ); + method = new JMethod("buildDom", new JType(type), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "trim" ) ); - method.addException( new JClass( "XmlPullParserException" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JType("XmlPullParser"), "parser")); + method.addParameter(new JParameter(JType.BOOLEAN, "trim")); + method.addException(new JClass("XmlPullParserException")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "java.util.Stack elements = new java.util.Stack();" ); + sc.add("java.util.Stack elements = new java.util.Stack();"); - sc.add( "java.util.Stack values = new java.util.Stack();" ); + sc.add("java.util.Stack values = new java.util.Stack();"); - sc.add( "int eventType = parser.getEventType();" ); + sc.add("int eventType = parser.getEventType();"); - sc.add( "boolean spacePreserve = false;" ); + sc.add("boolean spacePreserve = false;"); - sc.add( "while ( eventType != XmlPullParser.END_DOCUMENT )" ); - sc.add( "{" ); + sc.add("while ( eventType != XmlPullParser.END_DOCUMENT )"); + sc.add("{"); sc.indent(); - sc.add( "if ( eventType == XmlPullParser.START_TAG )" ); - sc.add( "{" ); + sc.add("if ( eventType == XmlPullParser.START_TAG )"); + sc.add("{"); sc.indent(); - sc.add( "spacePreserve = false;" ); - sc.add( "String rawName = parser.getName();" ); + sc.add("spacePreserve = false;"); + sc.add("String rawName = parser.getName();"); - sc.add( "org.w3c.dom.Element element = _doc_.createElement( rawName );" ); + sc.add("org.w3c.dom.Element element = _doc_.createElement( rawName );"); - sc.add( "if ( !elements.empty() )" ); - sc.add( "{" ); + sc.add("if ( !elements.empty() )"); + sc.add("{"); sc.indent(); - sc.add( type + " parent = (" + type + ") elements.peek();" ); + sc.add(type + " parent = (" + type + ") elements.peek();"); - sc.add( "parent.appendChild( element );" ); + sc.add("parent.appendChild( element );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "elements.push( element );" ); + sc.add("elements.push( element );"); - sc.add( "if ( parser.isEmptyElementTag() )" ); - sc.add( "{" ); - sc.addIndented( "values.push( null );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "values.push( new StringBuilder() );" ); - sc.add( "}" ); + sc.add("if ( parser.isEmptyElementTag() )"); + sc.add("{"); + sc.addIndented("values.push( null );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("values.push( new StringBuilder() );"); + sc.add("}"); - sc.add( "int attributesSize = parser.getAttributeCount();" ); + sc.add("int attributesSize = parser.getAttributeCount();"); - sc.add( "for ( int i = 0; i < attributesSize; i++ )" ); - sc.add( "{" ); + sc.add("for ( int i = 0; i < attributesSize; i++ )"); + sc.add("{"); sc.indent(); - sc.add( "String name = parser.getAttributeName( i );" ); + sc.add("String name = parser.getAttributeName( i );"); - sc.add( "String value = parser.getAttributeValue( i );" ); + sc.add("String value = parser.getAttributeValue( i );"); - sc.add( "element.setAttribute( name, value );" ); - sc.add( "spacePreserve = spacePreserve || ( \"xml:space\".equals( name ) && \"preserve\".equals( value ) );" ); + sc.add("element.setAttribute( name, value );"); + sc.add("spacePreserve = spacePreserve || ( \"xml:space\".equals( name ) && \"preserve\".equals( value ) );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); - sc.add( "else if ( eventType == XmlPullParser.TEXT )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("else if ( eventType == XmlPullParser.TEXT )"); + sc.add("{"); sc.indent(); - sc.add( "StringBuilder valueBuffer = (StringBuilder) values.peek();" ); + sc.add("StringBuilder valueBuffer = (StringBuilder) values.peek();"); - sc.add( "String text = parser.getText();" ); + sc.add("String text = parser.getText();"); - sc.add( "if ( trim && !spacePreserve )" ); - sc.add( "{" ); - sc.addIndented( "text = text.trim();" ); - sc.add( "}" ); + sc.add("if ( trim && !spacePreserve )"); + sc.add("{"); + sc.addIndented("text = text.trim();"); + sc.add("}"); - sc.add( "valueBuffer.append( text );" ); + sc.add("valueBuffer.append( text );"); sc.unindent(); - sc.add( "}" ); - sc.add( "else if ( eventType == XmlPullParser.END_TAG )" ); - sc.add( "{" ); + sc.add("}"); + sc.add("else if ( eventType == XmlPullParser.END_TAG )"); + sc.add("{"); sc.indent(); - sc.add( type + " element = (" + type + ") elements.pop();" ); + sc.add(type + " element = (" + type + ") elements.pop();"); - sc.add( "// this Object could be null if it is a singleton tag" ); - sc.add( "Object accumulatedValue = values.pop();" ); + sc.add("// this Object could be null if it is a singleton tag"); + sc.add("Object accumulatedValue = values.pop();"); - sc.add( "if ( !element.hasChildNodes() )" ); - sc.add( "{" ); - sc.addIndented( - "element.setTextContent( ( accumulatedValue == null ) ? null : accumulatedValue.toString() );" ); - sc.add( "}" ); + sc.add("if ( !element.hasChildNodes() )"); + sc.add("{"); + sc.addIndented("element.setTextContent( ( accumulatedValue == null ) ? null : accumulatedValue.toString() );"); + sc.add("}"); - sc.add( "if ( values.empty() )" ); - sc.add( "{" ); - sc.addIndented( "return element;" ); - sc.add( "}" ); + sc.add("if ( values.empty() )"); + sc.add("{"); + sc.addIndented("return element;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "eventType = parser.next();" ); + sc.add("eventType = parser.next();"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "throw new IllegalStateException( \"End of document found before returning to 0 depth\" );" ); + sc.add("throw new IllegalStateException( \"End of document found before returning to 0 depth\" );"); - jClass.addMethod( method ); + jClass.addMethod(method); } - private void writeBuildDomLocationTrackingMethod( JClass jClass ) - { - if ( !domAsXpp3 ) - { + private void writeBuildDomLocationTrackingMethod(JClass jClass) { + if (!domAsXpp3) { // no need, input location tracking available only for Xpp3 return; } - JClass builderClass = jClass.createInnerClass( "Xpp3DomBuilderInputLocationBuilder" ); + JClass builderClass = jClass.createInnerClass("Xpp3DomBuilderInputLocationBuilder"); builderClass.getModifiers().makePrivate(); - builderClass.getModifiers().setStatic( true ); - builderClass.addInterface( "org.codehaus.plexus.util.xml.Xpp3DomBuilder.InputLocationBuilder" ); - - JField field = new JField( new JType( locationTracker.getName() ), "rootLocation" ); - field.getModifiers().setFinal( true ); - builderClass.addField( field ); - - JConstructor constructor = new JConstructor( builderClass ); - constructor.addParameter( new JParameter( new JType( locationTracker.getName() ), "rootLocation" ) ); - constructor.getSourceCode().add( "this.rootLocation = rootLocation;" ); - builderClass.addConstructor( constructor ); - - JMethod method = new JMethod( "toInputLocation", new JType( "Object" ), null ); - method.addParameter( new JParameter( new JType( "XmlPullParser" ), "parser" ) ); - method.getSourceCode().add( "return " + buildNewLocation( "rootLocation.getSource()" ) + ";" ); - builderClass.addMethod( method ); + builderClass.getModifiers().setStatic(true); + builderClass.addInterface("org.codehaus.plexus.util.xml.Xpp3DomBuilder.InputLocationBuilder"); + + JField field = new JField(new JType(locationTracker.getName()), "rootLocation"); + field.getModifiers().setFinal(true); + builderClass.addField(field); + + JConstructor constructor = new JConstructor(builderClass); + constructor.addParameter(new JParameter(new JType(locationTracker.getName()), "rootLocation")); + constructor.getSourceCode().add("this.rootLocation = rootLocation;"); + builderClass.addConstructor(constructor); + + JMethod method = new JMethod("toInputLocation", new JType("Object"), null); + method.addParameter(new JParameter(new JType("XmlPullParser"), "parser")); + method.getSourceCode().add("return " + buildNewLocation("rootLocation.getSource()") + ";"); + builderClass.addMethod(method); } - private void writeHelpers( JClass jClass ) - { + private void writeHelpers(JClass jClass) { jClass.addMethod(getTrimmedValueMethod()); jClass.addMethod(getInterpolatedTrimmed()); jClass.addMethod(getRequiredAttributeValueMethod()); jClass.addMethod(getBooleanValueMethod()); jClass.addMethod(getBooleanValue2Method()); - jClass.addMethod( getCharacterValueMethod() ); - jClass.addMethod(convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" )); - jClass.addMethod(convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", "a short integer" )); - jClass.addMethod(convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" )); - jClass.addMethod(convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" )); - jClass.addMethod(convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", - "a floating point number" )); - jClass.addMethod(convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", - "a floating point number" )); - jClass.addMethod( getDateValueMethod() ); - jClass.addMethod( getDateValue2Method() ); - jClass.addMethod( getCheckFieldWithDuplicateMethod() ); - jClass.addMethod( getCheckUnknonwElement2Method() ); - jClass.addMethod( getCheckUnknownAttributeMethod() ); - jClass.addMethod( getNextTagMethod() ); + jClass.addMethod(getCharacterValueMethod()); + jClass.addMethod( + convertNumericalType("getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer")); + jClass.addMethod(convertNumericalType( + "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()", "a short integer")); + jClass.addMethod(convertNumericalType("getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte")); + jClass.addMethod( + convertNumericalType("getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer")); + jClass.addMethod(convertNumericalType( + "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()", "a floating point number")); + jClass.addMethod(convertNumericalType( + "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()", "a floating point number")); + jClass.addMethod(getDateValueMethod()); + jClass.addMethod(getDateValue2Method()); + jClass.addMethod(getCheckFieldWithDuplicateMethod()); + jClass.addMethod(getCheckUnknonwElement2Method()); + jClass.addMethod(getCheckUnknownAttributeMethod()); + jClass.addMethod(getNextTagMethod()); } private JMethod getCheckUnknonwElement2Method() { JMethod method; JSourceCode sc; - method = new JMethod( "checkUnknownElement", null, null ); + method = new JMethod("checkUnknownElement", null, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); - method.addException( new JClass( "XmlPullParserException" ) ); - method.addException( new JClass( "IOException" ) ); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); + method.addException(new JClass("XmlPullParserException")); + method.addException(new JClass("IOException")); sc = method.getSourceCode(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new XmlPullParserException( \"Unrecognised tag: '\" + parser.getName() + \"'\", parser, null );" ); - sc.add( "}" ); + "throw new XmlPullParserException( \"Unrecognised tag: '\" + parser.getName() + \"'\", parser, null );"); + sc.add("}"); - sc.add( "" ); + sc.add(""); - sc.add( "for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )" ); - sc.add( "{" ); + sc.add("for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; )"); + sc.add("{"); sc.indent(); - sc.add( "int eventType = parser.next();" ); - sc.add( "if ( eventType == XmlPullParser.START_TAG )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount++;" ); - sc.add( "}" ); - sc.add( "else if ( eventType == XmlPullParser.END_TAG )" ); - sc.add( "{" ); - sc.addIndented( "unrecognizedTagCount--;" ); - sc.add( "}" ); + sc.add("int eventType = parser.next();"); + sc.add("if ( eventType == XmlPullParser.START_TAG )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount++;"); + sc.add("}"); + sc.add("else if ( eventType == XmlPullParser.END_TAG )"); + sc.add("{"); + sc.addIndented("unrecognizedTagCount--;"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); return method; } private JMethod getNextTagMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "nextTag", JType.INT, null ); + method = new JMethod("nextTag", JType.INT, null); method.addException(new JClass("IOException")); method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); @@ -1332,50 +1234,47 @@ private JMethod getNextTagMethod() { sc = method.getSourceCode(); - sc.add( "int eventType = parser.next();" ); - sc.add( "if ( eventType == XmlPullParser.TEXT )" ); + sc.add("int eventType = parser.next();"); + sc.add("if ( eventType == XmlPullParser.TEXT )"); sc.add("{"); sc.addIndented("eventType = parser.next();"); - sc.add( "}" ); - sc.add( "if ( eventType != XmlPullParser.START_TAG && eventType != XmlPullParser.END_TAG )" ); + sc.add("}"); + sc.add("if ( eventType != XmlPullParser.START_TAG && eventType != XmlPullParser.END_TAG )"); sc.add("{"); sc.addIndented( "throw new XmlPullParserException( \"expected START_TAG or END_TAG not \" + XmlPullParser.TYPES[eventType], parser, null );"); sc.add("}"); - sc.add( "return eventType;" ); + sc.add("return eventType;"); return method; } private JMethod getCheckUnknownAttributeMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "checkUnknownAttribute", null, null ); + method = new JMethod("checkUnknownAttribute", null, null); method.getModifiers().makePrivate(); method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); method.addParameter(new JParameter(new JClass("String"), "attribute")); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(JType.BOOLEAN, "strict")); method.addException(new JClass("XmlPullParserException")); method.addException(new JClass("IOException")); sc = method.getSourceCode(); - if ( strictXmlAttributes ) - { + if (strictXmlAttributes) { sc.add( - "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too" ); - sc.add( "if ( strict )" ); + "// strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too"); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new XmlPullParserException( \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser, null );" ); - sc.add( "}" ); - } - else - { + "throw new XmlPullParserException( \"Unknown attribute '\" + attribute + \"' for tag '\" + tagName + \"'\", parser, null );"); + sc.add("}"); + } else { sc.add( - "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true" ); + "// strictXmlAttributes = false for model: always ignore unknown XML attribute, even if strict == true"); } return method; } @@ -1383,41 +1282,41 @@ private JMethod getCheckUnknownAttributeMethod() { private JMethod getCheckFieldWithDuplicateMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null ); + method = new JMethod("checkFieldWithDuplicate", JType.BOOLEAN, null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "alias" ) ); - method.addParameter( new JParameter( new JClass( "java.util.Set" ), "parsed" ) ); - method.addException( new JClass( "XmlPullParserException" ) ); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addParameter(new JParameter(new JClass("String"), "tagName")); + method.addParameter(new JParameter(new JClass("String"), "alias")); + method.addParameter(new JParameter(new JClass("java.util.Set"), "parsed")); + method.addException(new JClass("XmlPullParserException")); sc = method.getSourceCode(); - sc.add( "if ( !( parser.getName().equals( tagName ) || parser.getName().equals( alias ) ) )" ); + sc.add("if ( !( parser.getName().equals( tagName ) || parser.getName().equals( alias ) ) )"); - sc.add( "{" ); - sc.addIndented( "return false;" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return false;"); + sc.add("}"); - sc.add( "if ( !parsed.add( tagName ) )" ); + sc.add("if ( !parsed.add( tagName ) )"); - sc.add( "{" ); - sc.addIndented( "throw new XmlPullParserException( \"Duplicated tag: '\" + tagName + \"'\", parser, null );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XmlPullParserException( \"Duplicated tag: '\" + tagName + \"'\", parser, null );"); + sc.add("}"); - sc.add( "return true;" ); + sc.add("return true;"); return method; } private JMethod getDateValue2Method() { JMethod method; - method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null ); - method.addException( new JClass( "XmlPullParserException" ) ); + method = new JMethod("getDateValue", new JClass("java.util.Date"), null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); method.addParameter(new JParameter(new JClass("String"), "dateFormat")); method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); method.addException(new JClass("XmlPullParserException")); @@ -1429,14 +1328,14 @@ private JMethod getDateValue2Method() { private JMethod getDateValueMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null ); + method = new JMethod("getDateValue", new JClass("java.util.Date"), null); method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addException( new JClass( "XmlPullParserException" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addException(new JClass("XmlPullParserException")); sc = method.getSourceCode(); @@ -1447,232 +1346,219 @@ private JMethod getDateValueMethod() { private JMethod getCharacterValueMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "getCharacterValue", JType.CHAR, null ); - method.addException( new JClass( "XmlPullParserException" ) ); + method = new JMethod("getCharacterValue", JType.CHAR, null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "return s.charAt( 0 );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return s.charAt( 0 );"); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); return method; } private JMethod getBooleanValue2Method() { JMethod method; JSourceCode sc; - method = new JMethod( "getBooleanValue", JType.BOOLEAN, null ); - method.addException( new JClass( "XmlPullParserException" ) ); + method = new JMethod("getBooleanValue", JType.BOOLEAN, null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "defaultValue" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addParameter(new JParameter(new JClass("String"), "defaultValue")); sc = method.getSourceCode(); - sc.add( "if ( s != null && s.length() != 0 )" ); + sc.add("if ( s != null && s.length() != 0 )"); - sc.add( "{" ); - sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return Boolean.valueOf( s ).booleanValue();"); + sc.add("}"); - sc.add( "if ( defaultValue != null )" ); + sc.add("if ( defaultValue != null )"); - sc.add( "{" ); - sc.addIndented( "return Boolean.valueOf( defaultValue ).booleanValue();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return Boolean.valueOf( defaultValue ).booleanValue();"); + sc.add("}"); - sc.add( "return false;" ); + sc.add("return false;"); return method; } private JMethod getBooleanValueMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "getBooleanValue", JType.BOOLEAN, null ); - method.addException( new JClass( "XmlPullParserException" ) ); + method = new JMethod("getBooleanValue", JType.BOOLEAN, null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); sc = method.getSourceCode(); - sc.add( "return getBooleanValue( s, attribute, parser, null );" ); + sc.add("return getBooleanValue( s, attribute, parser, null );"); return method; } private JMethod getRequiredAttributeValueMethod() { JMethod method; JSourceCode sc; - method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null ); - method.addException( new JClass( "XmlPullParserException" ) ); + method = new JMethod("getRequiredAttributeValue", new JClass("String"), null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addParameter(new JParameter(JClass.BOOLEAN, "strict")); sc = method.getSourceCode(); - sc.add( "if ( s == null )" ); + sc.add("if ( s == null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); + sc.add("{"); sc.addIndented( - "throw new XmlPullParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser, null );" ); - sc.add( "}" ); + "throw new XmlPullParserException( \"Missing required value for attribute '\" + attribute + \"'\", parser, null );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); return method; } private JMethod getTrimmedValueMethod() { - JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null ); + JMethod method = new JMethod("getTrimmedValue", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); - sc.addIndented( "s = s.trim();" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("s = s.trim();"); + sc.add("}"); - sc.add( "return s;" ); + sc.add("return s;"); return method; } private JMethod getInterpolatedTrimmed() { - JMethod method = new JMethod( "interpolatedTrimmed", new JClass( "String" ), null ); + JMethod method = new JMethod("interpolatedTrimmed", new JClass("String"), null); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "value" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "context" ) ); + method.addParameter(new JParameter(new JClass("String"), "value")); + method.addParameter(new JParameter(new JClass("String"), "context")); JSourceCode sc = method.getSourceCode(); - sc.add( "return getTrimmedValue( contentTransformer.transform( value, context ) );" ); + sc.add("return getTrimmedValue( contentTransformer.transform( value, context ) );"); return method; } - - private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc ) - { - JMethod method = new JMethod( methodName, returnType, null ); - method.addException( new JClass( "XmlPullParserException" ) ); + private JMethod convertNumericalType(String methodName, JType returnType, String expression, String typeDesc) { + JMethod method = new JMethod(methodName, returnType, null); + method.addException(new JClass("XmlPullParserException")); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JClass( "String" ), "s" ) ); - method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) ); - method.addParameter( new JParameter( new JClass( "XmlPullParser" ), "parser" ) ); - method.addParameter( new JParameter( JClass.BOOLEAN, "strict" ) ); + method.addParameter(new JParameter(new JClass("String"), "s")); + method.addParameter(new JParameter(new JClass("String"), "attribute")); + method.addParameter(new JParameter(new JClass("XmlPullParser"), "parser")); + method.addParameter(new JParameter(JClass.BOOLEAN, "strict")); JSourceCode sc = method.getSourceCode(); - sc.add( "if ( s != null )" ); + sc.add("if ( s != null )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "try" ); + sc.add("try"); - sc.add( "{" ); - sc.addIndented( "return " + expression + ";" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("return " + expression + ";"); + sc.add("}"); - sc.add( "catch ( NumberFormatException nfe )" ); + sc.add("catch ( NumberFormatException nfe )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "if ( strict )" ); + sc.add("if ( strict )"); - sc.add( "{" ); - sc.addIndented( - "throw new XmlPullParserException( \"Unable to parse element '\" + attribute + \"', must be " + typeDesc - + "\", parser, nfe );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("throw new XmlPullParserException( \"Unable to parse element '\" + attribute + \"', must be " + + typeDesc + "\", parser, nfe );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "return 0;" ); + sc.add("return 0;"); return method; } - private void addTrackingParameters( JMethod method ) - { - if ( sourceTracker != null ) - { - method.addParameter( new JParameter( new JClass( sourceTracker.getName() ), SOURCE_PARAM ) ); + private void addTrackingParameters(JMethod method) { + if (sourceTracker != null) { + method.addParameter(new JParameter(new JClass(sourceTracker.getName()), SOURCE_PARAM)); } } - private void writeNewSetLocation( ModelField field, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewSetLocation( "\"" + field.getName() + "\"", objectName, trackerVariable, sc ); + private void writeNewSetLocation(ModelField field, String objectName, String trackerVariable, JSourceCode sc) { + writeNewSetLocation("\"" + field.getName() + "\"", objectName, trackerVariable, sc); } - private void writeNewSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - writeNewLocation( trackerVariable, sc ); - writeSetLocation( key, objectName, trackerVariable, sc ); + private void writeNewSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + writeNewLocation(trackerVariable, sc); + writeSetLocation(key, objectName, trackerVariable, sc); } - private void writeNewLocation( String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeNewLocation(String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } - sc.add( ( ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR ) + " = " - + buildNewLocation( SOURCE_PARAM ) + ";" ); + sc.add(((trackerVariable != null) ? trackerVariable : LOCATION_VAR) + " = " + buildNewLocation(SOURCE_PARAM) + + ";"); } - private String buildNewLocation( String source ) - { + private String buildNewLocation(String source) { return "new " + locationTracker.getName() + "( parser.getLineNumber(), parser.getColumnNumber()" - + ( ( sourceTracker != null ) ? ", " + source : "" ) + " )"; + + ((sourceTracker != null) ? ", " + source : "") + " )"; } - private void writeSetLocation( String key, String objectName, String trackerVariable, JSourceCode sc ) - { - if ( locationTracker == null ) - { + private void writeSetLocation(String key, String objectName, String trackerVariable, JSourceCode sc) { + if (locationTracker == null) { return; } - String variable = ( trackerVariable != null ) ? trackerVariable : LOCATION_VAR; + String variable = (trackerVariable != null) ? trackerVariable : LOCATION_VAR; - sc.add( objectName + ".set" + capitalise( singular( locationField ) ) + "( " + key + ", " + variable + " );" ); + sc.add(objectName + ".set" + capitalise(singular(locationField)) + "( " + key + ", " + variable + " );"); } - } diff --git a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3WriterGenerator.java b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3WriterGenerator.java index 627e8e410..cc99ef5ea 100644 --- a/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3WriterGenerator.java +++ b/modello-plugins/modello-plugin-xpp3/src/main/java/org/codehaus/modello/plugin/xpp3/Xpp3WriterGenerator.java @@ -22,6 +22,10 @@ * SOFTWARE. */ +import java.io.IOException; +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.model.Model; @@ -44,557 +48,488 @@ import org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata; import org.codehaus.plexus.component.annotations.Component; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - /** * @author Jason van Zyl * @author Emmanuel Venisse */ -@Component( role = ModelloGenerator.class, hint = "xpp3-writer" ) -public class Xpp3WriterGenerator - extends AbstractXpp3Generator -{ +@Component(role = ModelloGenerator.class, hint = "xpp3-writer") +public class Xpp3WriterGenerator extends AbstractXpp3Generator { private String extendedClassnameSuffix; - protected void prepareLocationTracking( JClass jClass ) - { + protected void prepareLocationTracking(JClass jClass) { // NO OP } - protected void writeLocationTracking( JSourceCode sc, String name, String key ) - { - if ( isLocationTracking() ) - { - sc.add( "writeLocationTracking( " + name + ", " + key + ", serializer );" ); + protected void writeLocationTracking(JSourceCode sc, String name, String key) { + if (isLocationTracking()) { + sc.add("writeLocationTracking( " + name + ", " + key + ", serializer );"); } } @Override - protected void initialize( Model model, Properties parameters ) - throws ModelloException - { - super.initialize( model, parameters ); + protected void initialize(Model model, Properties parameters) throws ModelloException { + super.initialize(model, parameters); extendedClassnameSuffix = "Ex"; - if ( isLocationTracking() ) - { - extendedClassnameSuffix = parameters.getProperty( ModelloParameterConstants.EXTENDED_CLASSNAME_SUFFIX ); + if (isLocationTracking()) { + extendedClassnameSuffix = parameters.getProperty(ModelloParameterConstants.EXTENDED_CLASSNAME_SUFFIX); } } - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); - try - { + try { generateXpp3Writer(); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating XPP3 Writer.", ex ); + } catch (IOException ex) { + throw new ModelloException("Exception while generating XPP3 Writer.", ex); } } - private void generateXpp3Writer() - throws ModelloException, IOException - { + private void generateXpp3Writer() throws ModelloException, IOException { Model objectModel = getModel(); - String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() ) - + ".io.xpp3"; + String packageName = + objectModel.getDefaultPackageName(isPackageWithVersion(), getGeneratedVersion()) + ".io.xpp3"; - String marshallerName = getFileName( "Xpp3Writer" + ( isLocationTracking() ? extendedClassnameSuffix : "" ) ); + String marshallerName = getFileName("Xpp3Writer" + (isLocationTracking() ? extendedClassnameSuffix : "")); - JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName ); + JSourceWriter sourceWriter = newJSourceWriter(packageName, marshallerName); - JClass jClass = new JClass( packageName + '.' + marshallerName ); - initHeader( jClass ); - suppressAllWarnings( objectModel, jClass ); + JClass jClass = new JClass(packageName + '.' + marshallerName); + initHeader(jClass); + suppressAllWarnings(objectModel, jClass); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.XmlSerializer" ); - jClass.addImport( "org.codehaus.plexus.util.xml.pull.MXSerializer" ); - jClass.addImport( "java.io.OutputStream" ); - jClass.addImport( "java.io.Writer" ); - jClass.addImport( "java.util.Iterator" ); + jClass.addImport("org.codehaus.plexus.util.xml.pull.XmlSerializer"); + jClass.addImport("org.codehaus.plexus.util.xml.pull.MXSerializer"); + jClass.addImport("java.io.OutputStream"); + jClass.addImport("java.io.Writer"); + jClass.addImport("java.util.Iterator"); - JField namespaceField = new JField( new JClass( "String" ), "NAMESPACE" ); - namespaceField.getModifiers().setFinal( true ); - namespaceField.getModifiers().setStatic( true ); - namespaceField.setInitString( "null" ); - jClass.addField( namespaceField ); + JField namespaceField = new JField(new JClass("String"), "NAMESPACE"); + namespaceField.getModifiers().setFinal(true); + namespaceField.getModifiers().setStatic(true); + namespaceField.setInitString("null"); + jClass.addField(namespaceField); - JField commentField = new JField( new JClass( "String" ), "fileComment" ); - commentField.setInitString( "null" ); - jClass.addField( commentField ); + JField commentField = new JField(new JClass("String"), "fileComment"); + commentField.setInitString("null"); + jClass.addField(commentField); // Add setComment method - JMethod setComment = new JMethod( "setFileComment" ); + JMethod setComment = new JMethod("setFileComment"); - setComment.addParameter( new JParameter( new JClass( "String" ), "fileComment" ) ); + setComment.addParameter(new JParameter(new JClass("String"), "fileComment")); JSourceCode setCommentSourceCode = setComment.getSourceCode(); - setCommentSourceCode.add( "this.fileComment = fileComment;" ); - jClass.addMethod( setComment ); + setCommentSourceCode.add("this.fileComment = fileComment;"); + jClass.addMethod(setComment); - addModelImports( jClass, null ); + addModelImports(jClass, null); - String root = objectModel.getRoot( getGeneratedVersion() ); + String root = objectModel.getRoot(getGeneratedVersion()); - ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() ); + ModelClass rootClass = objectModel.getClass(root, getGeneratedVersion()); - String rootElement = resolveTagName( rootClass ); + String rootElement = resolveTagName(rootClass); // ---------------------------------------------------------------------- // Write the write( Writer, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - JMethod marshall = new JMethod( "write" ); + JMethod marshall = new JMethod("write"); - String rootElementParameterName = uncapitalise( root ); - marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + String rootElementParameterName = uncapitalise(root); + marshall.addParameter(new JParameter(new JClass("Writer"), "writer")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); JSourceCode sc = marshall.getSourceCode(); - sc.add( "XmlSerializer serializer = new MXSerializer();" ); + sc.add("XmlSerializer serializer = new MXSerializer();"); sc.add( - "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-indentation\", \" \" );" ); + "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-indentation\", \" \" );"); sc.add( - "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-line-separator\", \"\\n\" );" ); + "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-line-separator\", \"\\n\" );"); - sc.add( "serializer.setOutput( writer );" ); + sc.add("serializer.setOutput( writer );"); - sc.add( "serializer.startDocument( " + rootElementParameterName + ".getModelEncoding(), null );" ); + sc.add("serializer.startDocument( " + rootElementParameterName + ".getModelEncoding(), null );"); - sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );"); - sc.add( "serializer.endDocument();" ); + sc.add("serializer.endDocument();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); // ---------------------------------------------------------------------- // Write the write( OutputStream, Model ) method which will do the unmarshalling. // ---------------------------------------------------------------------- - marshall = new JMethod( "write" ); + marshall = new JMethod("write"); - marshall.addParameter( new JParameter( new JClass( "OutputStream" ), "stream" ) ); - marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) ); + marshall.addParameter(new JParameter(new JClass("OutputStream"), "stream")); + marshall.addParameter(new JParameter(new JClass(root), rootElementParameterName)); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); sc = marshall.getSourceCode(); - sc.add( "XmlSerializer serializer = new MXSerializer();" ); + sc.add("XmlSerializer serializer = new MXSerializer();"); sc.add( - "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-indentation\", \" \" );" ); + "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-indentation\", \" \" );"); sc.add( - "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-line-separator\", \"\\n\" );" ); + "serializer.setProperty( \"http://xmlpull.org/v1/doc/properties.html#serializer-line-separator\", \"\\n\" );"); - sc.add( "serializer.setOutput( stream, " + rootElementParameterName + ".getModelEncoding() );" ); + sc.add("serializer.setOutput( stream, " + rootElementParameterName + ".getModelEncoding() );"); - sc.add( "serializer.startDocument( " + rootElementParameterName + ".getModelEncoding(), null );" ); + sc.add("serializer.startDocument( " + rootElementParameterName + ".getModelEncoding(), null );"); - sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );" ); + sc.add("write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );"); - sc.add( "serializer.endDocument();" ); + sc.add("serializer.endDocument();"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); - writeAllClasses( objectModel, jClass ); + writeAllClasses(objectModel, jClass); - if ( isLocationTracking() ) - { - prepareLocationTracking( jClass ); + if (isLocationTracking()) { + prepareLocationTracking(jClass); } - if ( requiresDomSupport ) - { - createWriteDomMethod( jClass ); + if (requiresDomSupport) { + createWriteDomMethod(jClass); } - jClass.print( sourceWriter ); + jClass.print(sourceWriter); sourceWriter.close(); } - private void writeAllClasses( Model objectModel, JClass jClass ) - throws ModelloException - { - for ( ModelClass clazz : getClasses( objectModel ) ) - { - writeClass( clazz, jClass ); + private void writeAllClasses(Model objectModel, JClass jClass) throws ModelloException { + for (ModelClass clazz : getClasses(objectModel)) { + writeClass(clazz, jClass); } } - private void writeClass( ModelClass modelClass, JClass jClass ) - throws ModelloException - { + private void writeClass(ModelClass modelClass, JClass jClass) throws ModelloException { String className = modelClass.getName(); - String uncapClassName = uncapitalise( className ); + String uncapClassName = uncapitalise(className); - JMethod marshall = new JMethod( "write" + className ); + JMethod marshall = new JMethod("write" + className); - marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) ); - marshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) ); - marshall.addParameter( new JParameter( new JClass( "XmlSerializer" ), "serializer" ) ); + marshall.addParameter(new JParameter(new JClass(className), uncapClassName)); + marshall.addParameter(new JParameter(new JClass("String"), "tagName")); + marshall.addParameter(new JParameter(new JClass("XmlSerializer"), "serializer")); - marshall.addException( new JClass( "java.io.IOException" ) ); + marshall.addException(new JClass("java.io.IOException")); marshall.getModifiers().makePrivate(); JSourceCode sc = marshall.getSourceCode(); - ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID ); + ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata(ModelClassMetadata.ID); String namespace = null; - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID ); + XmlModelMetadata xmlModelMetadata = + (XmlModelMetadata) modelClass.getModel().getMetadata(XmlModelMetadata.ID); // add namespace information for root element only - if ( classMetadata.isRootElement() && ( xmlModelMetadata.getNamespace() != null ) ) - { - sc.add( "if ( this.fileComment != null )" ); - sc.add( "{" ); - sc.add( "serializer.comment(this.fileComment);" ); - sc.add( "}" ); - - namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() ); - sc.add( "serializer.setPrefix( \"\", \"" + namespace + "\" );" ); + if (classMetadata.isRootElement() && (xmlModelMetadata.getNamespace() != null)) { + sc.add("if ( this.fileComment != null )"); + sc.add("{"); + sc.add("serializer.comment(this.fileComment);"); + sc.add("}"); + + namespace = xmlModelMetadata.getNamespace(getGeneratedVersion()); + sc.add("serializer.setPrefix( \"\", \"" + namespace + "\" );"); } - if ( ( namespace != null ) && ( xmlModelMetadata.getSchemaLocation() != null ) ) - { - String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() ); + if ((namespace != null) && (xmlModelMetadata.getSchemaLocation() != null)) { + String url = xmlModelMetadata.getSchemaLocation(getGeneratedVersion()); - sc.add( "serializer.setPrefix( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" ); + sc.add("serializer.setPrefix( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );"); - sc.add( "serializer.startTag( NAMESPACE, tagName );" ); + sc.add("serializer.startTag( NAMESPACE, tagName );"); - sc.add( "serializer.attribute( \"\", \"xsi:schemaLocation\", \"" + namespace + " " + url + "\" );" ); - } - else - { - sc.add( "serializer.startTag( NAMESPACE, tagName );" ); + sc.add("serializer.attribute( \"\", \"xsi:schemaLocation\", \"" + namespace + " " + url + "\" );"); + } else { + sc.add("serializer.startTag( NAMESPACE, tagName );"); } ModelField contentField = null; String contentValue = null; - List modelFields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List modelFields = getFieldsForXml(modelClass, getGeneratedVersion()); // XML attributes - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { contentField = field; contentValue = value; continue; } - if ( xmlFieldMetadata.isAttribute() ) - { - sc.add( getValueChecker( type, value, field ) ); + if (xmlFieldMetadata.isAttribute()) { + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); - sc.addIndented( "serializer.attribute( NAMESPACE, \"" + fieldTagName + "\", " - + getValue( field.getType(), value, xmlFieldMetadata ) + " );" ); - sc.add( "}" ); + sc.add("{"); + sc.addIndented("serializer.attribute( NAMESPACE, \"" + fieldTagName + "\", " + + getValue(field.getType(), value, xmlFieldMetadata) + " );"); + sc.add("}"); } - } - if ( contentField != null ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID ); - sc.add( "serializer.text( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + " );" ); + if (contentField != null) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata(XmlFieldMetadata.ID); + sc.add("serializer.text( " + getValue(contentField.getType(), contentValue, xmlFieldMetadata) + " );"); } // XML tags - for ( ModelField field : modelFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : modelFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // skip field with type Content continue; } - JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID ); + JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata(JavaFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); String type = field.getType(); - String value = uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()"; + String value = uncapClassName + "." + getPrefix(javaFieldMetadata) + capitalise(field.getName()) + "()"; - if ( xmlFieldMetadata.isAttribute() ) - { + if (xmlFieldMetadata.isAttribute()) { continue; } - if ( field instanceof ModelAssociation ) - { + if (field instanceof ModelAssociation) { ModelAssociation association = (ModelAssociation) field; String associationName = association.getName(); - if ( association.isOneMultiplicity() ) - { - sc.add( getValueChecker( type, value, association ) ); + if (association.isOneMultiplicity()) { + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); - sc.addIndented( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" - + fieldTagName + "\", serializer );" ); - sc.add( "}" ); - } - else - { - //MANY_MULTIPLICITY + sc.add("{"); + sc.addIndented("write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" + + fieldTagName + "\", serializer );"); + sc.add("}"); + } else { + // MANY_MULTIPLICITY XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + (XmlAssociationMetadata) association.getAssociationMetadata(XmlAssociationMetadata.ID); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); type = association.getType(); String toType = association.getTo(); boolean wrappedItems = xmlAssociationMetadata.isWrappedItems(); - if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) ) - { - boolean isList = ModelDefault.LIST.equals( type ); + if (ModelDefault.LIST.equals(type) || ModelDefault.SET.equals(type)) { + boolean isList = ModelDefault.LIST.equals(type); - sc.add( getValueChecker( type, value, association ) ); + sc.add(getValueChecker(type, value, association)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "serializer.startTag( NAMESPACE, " + "\"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.startTag( NAMESPACE, " + "\"" + fieldTagName + "\" );"); } - if ( isLocationTracking() && !isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( locationTracker.getName() + " location = " + uncapClassName + ".getLocation( \"" + fieldTagName + "\" );" ); - if ( isList ) - { - sc.add( "int n = 0;" ); + if (isLocationTracking() && !isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add(locationTracker.getName() + " location = " + uncapClassName + ".getLocation( \"" + + fieldTagName + "\" );"); + if (isList) { + sc.add("int n = 0;"); } } - sc.add( "for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( isClassInModel( association.getTo(), modelClass.getModel() ) ) - { - sc.add( toType + " o = (" + toType + ") iter.next();" ); + if (isClassInModel(association.getTo(), modelClass.getModel())) { + sc.add(toType + " o = (" + toType + ") iter.next();"); - sc.add( "write" + toType + "( o, \"" + valuesTagName + "\", serializer );" ); - } - else - { - String variable = singular( uncapitalise( field.getName() ) ); + sc.add("write" + toType + "( o, \"" + valuesTagName + "\", serializer );"); + } else { + String variable = singular(uncapitalise(field.getName())); - sc.add( toType + " " + variable + " = (" + toType + ") iter.next();" ); + sc.add(toType + " " + variable + " = (" + toType + ") iter.next();"); - sc.add( "serializer.startTag( NAMESPACE, \"" + valuesTagName + "\" ).text( " + variable - + " ).endTag( NAMESPACE, \"" + valuesTagName + "\" );" ); + sc.add("serializer.startTag( NAMESPACE, \"" + valuesTagName + "\" ).text( " + variable + + " ).endTag( NAMESPACE, \"" + valuesTagName + "\" );"); - writeLocationTracking( sc, "location", isList ? "Integer.valueOf( n++ )" : variable ); + writeLocationTracking(sc, "location", isList ? "Integer.valueOf( n++ )" : variable); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "serializer.endTag( NAMESPACE, \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.endTag( NAMESPACE, \"" + fieldTagName + "\" );"); } sc.unindent(); - sc.add( "}" ); - } - else - { - //Map or Properties + sc.add("}"); + } else { + // Map or Properties - sc.add( getValueChecker( type, value, field ) ); + sc.add(getValueChecker(type, value, field)); - sc.add( "{" ); + sc.add("{"); sc.indent(); - if ( wrappedItems ) - { - sc.add( "serializer.startTag( NAMESPACE, \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.startTag( NAMESPACE, \"" + fieldTagName + "\" );"); } - if ( isLocationTracking() ) - { - sc.add( locationTracker.getName() + " location = " + uncapClassName + ".getLocation( \"" + fieldTagName + "\" );" ); + if (isLocationTracking()) { + sc.add(locationTracker.getName() + " location = " + uncapClassName + ".getLocation( \"" + + fieldTagName + "\" );"); } - sc.add( "for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )" ); + sc.add("for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )"); - sc.add( "{" ); + sc.add("{"); sc.indent(); - sc.add( "String key = (String) iter.next();" ); + sc.add("String key = (String) iter.next();"); - sc.add( "String value = (String) " + value + ".get( key );" ); + sc.add("String value = (String) " + value + ".get( key );"); - if ( xmlAssociationMetadata.isMapExplode() ) - { - sc.add( "serializer.startTag( NAMESPACE, \"" + singular( associationName ) + "\" );" ); - sc.add( - "serializer.startTag( NAMESPACE, \"key\" ).text( key ).endTag( NAMESPACE, \"key\" );" ); + if (xmlAssociationMetadata.isMapExplode()) { + sc.add("serializer.startTag( NAMESPACE, \"" + singular(associationName) + "\" );"); sc.add( - "serializer.startTag( NAMESPACE, \"value\" ).text( value ).endTag( NAMESPACE, \"value\" );" ); - sc.add( "serializer.endTag( NAMESPACE, \"" + singular( associationName ) + "\" );" ); - } - else - { + "serializer.startTag( NAMESPACE, \"key\" ).text( key ).endTag( NAMESPACE, \"key\" );"); sc.add( - "serializer.startTag( NAMESPACE, key ).text( value ).endTag( NAMESPACE, key );" ); + "serializer.startTag( NAMESPACE, \"value\" ).text( value ).endTag( NAMESPACE, \"value\" );"); + sc.add("serializer.endTag( NAMESPACE, \"" + singular(associationName) + "\" );"); + } else { + sc.add("serializer.startTag( NAMESPACE, key ).text( value ).endTag( NAMESPACE, key );"); } - writeLocationTracking( sc, "location", "key" ); + writeLocationTracking(sc, "location", "key"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - if ( wrappedItems ) - { - sc.add( "serializer.endTag( NAMESPACE, \"" + fieldTagName + "\" );" ); + if (wrappedItems) { + sc.add("serializer.endTag( NAMESPACE, \"" + fieldTagName + "\" );"); } sc.unindent(); - sc.add( "}" ); + sc.add("}"); } } - } - else - { - sc.add( getValueChecker( type, value, field ) ); - - sc.add( "{" ); - if ( "DOM".equals( field.getType() ) ) - { - if ( domAsXpp3 ) - { - jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" ); - - if ( isLocationTracking() ) - { - sc.addIndented( "writeXpp3DomToSerializer( (Xpp3Dom) " + value + ", serializer );" ); - } - else - { - sc.addIndented( "((Xpp3Dom) " + value + ").writeToSerializer( NAMESPACE, serializer );" ); + } else { + sc.add(getValueChecker(type, value, field)); + + sc.add("{"); + if ("DOM".equals(field.getType())) { + if (domAsXpp3) { + jClass.addImport("org.codehaus.plexus.util.xml.Xpp3Dom"); + + if (isLocationTracking()) { + sc.addIndented("writeXpp3DomToSerializer( (Xpp3Dom) " + value + ", serializer );"); + } else { + sc.addIndented("((Xpp3Dom) " + value + ").writeToSerializer( NAMESPACE, serializer );"); } - } - else - { - sc.addIndented( "writeDom( (org.w3c.dom.Element) " + value + ", serializer );" ); + } else { + sc.addIndented("writeDom( (org.w3c.dom.Element) " + value + ", serializer );"); } requiresDomSupport = true; - } - else - { - sc.addIndented( "serializer.startTag( NAMESPACE, " + "\"" + fieldTagName + "\" ).text( " - + getValue( field.getType(), value, xmlFieldMetadata ) + " ).endTag( NAMESPACE, " + "\"" - + fieldTagName + "\" );" ); + } else { + sc.addIndented("serializer.startTag( NAMESPACE, " + "\"" + fieldTagName + "\" ).text( " + + getValue(field.getType(), value, xmlFieldMetadata) + " ).endTag( NAMESPACE, " + "\"" + + fieldTagName + "\" );"); sc.indent(); - writeLocationTracking( sc, uncapClassName, '"' + fieldTagName + '"' ); + writeLocationTracking(sc, uncapClassName, '"' + fieldTagName + '"'); sc.unindent(); } - sc.add( "}" ); + sc.add("}"); } } - sc.add( "serializer.endTag( NAMESPACE, tagName );" ); + sc.add("serializer.endTag( NAMESPACE, tagName );"); - jClass.addMethod( marshall ); + jClass.addMethod(marshall); } - private void createWriteDomMethod( JClass jClass ) - { - if ( domAsXpp3 ) - { + private void createWriteDomMethod(JClass jClass) { + if (domAsXpp3) { return; } String type = "org.w3c.dom.Element"; - JMethod method = new JMethod( "writeDom" ); + JMethod method = new JMethod("writeDom"); method.getModifiers().makePrivate(); - method.addParameter( new JParameter( new JType( type ), "dom" ) ); - method.addParameter( new JParameter( new JClass( "XmlSerializer" ), "serializer" ) ); + method.addParameter(new JParameter(new JType(type), "dom")); + method.addParameter(new JParameter(new JClass("XmlSerializer"), "serializer")); - method.addException( new JClass( "java.io.IOException" ) ); + method.addException(new JClass("java.io.IOException")); JSourceCode sc = method.getSourceCode(); // start element - sc.add( "serializer.startTag( NAMESPACE, dom.getTagName() );" ); + sc.add("serializer.startTag( NAMESPACE, dom.getTagName() );"); // attributes - sc.add( "org.w3c.dom.NamedNodeMap attributes = dom.getAttributes();" ); - sc.add( "for ( int i = 0; i < attributes.getLength(); i++ )" ); - sc.add( "{" ); + sc.add("org.w3c.dom.NamedNodeMap attributes = dom.getAttributes();"); + sc.add("for ( int i = 0; i < attributes.getLength(); i++ )"); + sc.add("{"); sc.indent(); - sc.add( "org.w3c.dom.Node attribute = attributes.item( i );" ); - sc.add( "serializer.attribute( NAMESPACE, attribute.getNodeName(), attribute.getNodeValue() );" ); + sc.add("org.w3c.dom.Node attribute = attributes.item( i );"); + sc.add("serializer.attribute( NAMESPACE, attribute.getNodeName(), attribute.getNodeValue() );"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); // child nodes & text - sc.add( "org.w3c.dom.NodeList children = dom.getChildNodes();" ); - sc.add( "for ( int i = 0; i < children.getLength(); i++ )" ); - sc.add( "{" ); + sc.add("org.w3c.dom.NodeList children = dom.getChildNodes();"); + sc.add("for ( int i = 0; i < children.getLength(); i++ )"); + sc.add("{"); sc.indent(); - sc.add( "org.w3c.dom.Node node = children.item( i );" ); - sc.add( "if ( node instanceof org.w3c.dom.Element)" ); - sc.add( "{" ); - sc.addIndented( "writeDom( (org.w3c.dom.Element) children.item( i ), serializer );" ); - sc.add( "}" ); - sc.add( "else" ); - sc.add( "{" ); - sc.addIndented( "serializer.text( node.getTextContent() );" ); - sc.add( "}" ); + sc.add("org.w3c.dom.Node node = children.item( i );"); + sc.add("if ( node instanceof org.w3c.dom.Element)"); + sc.add("{"); + sc.addIndented("writeDom( (org.w3c.dom.Element) children.item( i ), serializer );"); + sc.add("}"); + sc.add("else"); + sc.add("{"); + sc.addIndented("serializer.text( node.getTextContent() );"); + sc.add("}"); sc.unindent(); - sc.add( "}" ); + sc.add("}"); - sc.add( "serializer.endTag( NAMESPACE, dom.getTagName() );" ); + sc.add("serializer.endTag( NAMESPACE, dom.getTagName() );"); - jClass.addMethod( method ); + jClass.addMethod(method); } } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/AbstractElementTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/AbstractElementTest.java index a8e810f05..b2836c994 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/AbstractElementTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/AbstractElementTest.java @@ -22,38 +22,33 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class AbstractElementTest - extends AbstractModelloJavaGeneratorTest -{ - public AbstractElementTest() - { - super( "abstracto" ); +public class AbstractElementTest extends AbstractModelloJavaGeneratorTest { + public AbstractElementTest() { + super("abstracto"); } - public void testAbstract() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testAbstract() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/abstract.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/abstract.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-writer", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-writer", parameters); + modello.generate(model, "xpp3-reader", parameters); - //addDependency( "org.codehaus.modello", "modello-core", getModelloVersion() ); + // addDependency( "org.codehaus.modello", "modello-core", getModelloVersion() ); // compile( generatedSources, classes ); } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/BooleanTypeXpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/BooleanTypeXpp3GeneratorTest.java index cc660feff..91b6285a3 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/BooleanTypeXpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/BooleanTypeXpp3GeneratorTest.java @@ -25,26 +25,21 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -public class BooleanTypeXpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public BooleanTypeXpp3GeneratorTest() - { - super( "testBooleanType" ); +public class BooleanTypeXpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { + public BooleanTypeXpp3GeneratorTest() { + super("testBooleanType"); } - public void testBooleanType() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testBooleanType() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/boolean.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/boolean.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); // autoboxing + Properties parameters = getModelloParameters("1.0.0", 5); // autoboxing - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-reader", parameters); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); } } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3DomGeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3DomGeneratorTest.java index 6abe2d2fa..0af3f5265 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3DomGeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3DomGeneratorTest.java @@ -22,40 +22,35 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesXpp3DomGeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesXpp3DomGeneratorTest() - { - super( "features-dom" ); +public class FeaturesXpp3DomGeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesXpp3DomGeneratorTest() { + super("features-dom"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); - parameters.put( "modello.dom.xpp3", "false" ); + Properties parameters = getModelloParameters("1.0.0"); + parameters.put("modello.dom.xpp3", "false"); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-writer", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-writer", parameters); + modello.generate(model, "xpp3-reader", parameters); - addDependency( "org.xmlunit", "xmlunit-core" ); - compileGeneratedSources( 5 ); + addDependency("org.xmlunit", "xmlunit-core"); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3FeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3FeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3GeneratorTest.java index 89847ef08..7babc12a8 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/FeaturesXpp3GeneratorTest.java @@ -22,39 +22,34 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Hervé Boutemy */ -public class FeaturesXpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public FeaturesXpp3GeneratorTest() - { - super( "features" ); +public class FeaturesXpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { + public FeaturesXpp3GeneratorTest() { + super("features"); } - public void testJavaGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testJavaGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-writer", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-writer", parameters); + modello.generate(model, "xpp3-reader", parameters); - addDependency( "org.xmlunit", "xmlunit-core" ); - compileGeneratedSources( 5 ); + addDependency("org.xmlunit", "xmlunit-core"); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3FeaturesVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3FeaturesVerifier"); } } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsSourceXpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsSourceXpp3GeneratorTest.java index 1584fa575..591e5128f 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsSourceXpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsSourceXpp3GeneratorTest.java @@ -22,40 +22,34 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Benjamin Bentmann */ -public class LocationsSourceXpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ +public class LocationsSourceXpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { - public LocationsSourceXpp3GeneratorTest() - { - super( "locations+src" ); + public LocationsSourceXpp3GeneratorTest() { + super("locations+src"); } - public void testLocationsWithSource() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testLocationsWithSource() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/locations+source.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/locations+source.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); + Properties parameters = getModelloParameters("1.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-reader", parameters ); - modello.generate( model, "xpp3-extended-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-reader", parameters); + modello.generate(model, "xpp3-extended-reader", parameters); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3LocationsSourceVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3LocationsSourceVerifier"); } - } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsXpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsXpp3GeneratorTest.java index 3b596912f..8c53db3c3 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsXpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/LocationsXpp3GeneratorTest.java @@ -22,40 +22,34 @@ * SOFTWARE. */ +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -import java.util.Properties; - /** * @author Benjamin Bentmann */ -public class LocationsXpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ +public class LocationsXpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { - public LocationsXpp3GeneratorTest() - { - super( "locations" ); + public LocationsXpp3GeneratorTest() { + super("locations"); } - public void testLocationsOnly() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testLocationsOnly() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/locations.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/locations.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); + Properties parameters = getModelloParameters("1.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-reader", parameters ); - modello.generate( model, "xpp3-extended-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-reader", parameters); + modello.generate(model, "xpp3-extended-reader", parameters); - compileGeneratedSources( 5 ); + compileGeneratedSources(5); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3LocationsVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3LocationsVerifier"); } - } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/StandaloneReadXpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/StandaloneReadXpp3GeneratorTest.java index f2c9ddfb9..5853a3512 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/StandaloneReadXpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/StandaloneReadXpp3GeneratorTest.java @@ -28,46 +28,38 @@ import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; -public class StandaloneReadXpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public StandaloneReadXpp3GeneratorTest() - { - super( "testStandaloneRead" ); +public class StandaloneReadXpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { + public StandaloneReadXpp3GeneratorTest() { + super("testStandaloneRead"); } - public void testStandaloneRead() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testStandaloneRead() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/standaloneRead.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/standaloneRead.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-reader", parameters); - compileGeneratedSources( 5 ); // enhanced for loops in Xpp3StandaloneReadVerifier + compileGeneratedSources(5); // enhanced for loops in Xpp3StandaloneReadVerifier - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3StandaloneReadVerifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3StandaloneReadVerifier"); } - public void testStandaloneReadJava5() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testStandaloneReadJava5() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/standaloneRead.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/standaloneRead.mdo")); - Properties parameters = getModelloParameters( "1.0.0", 5 ); + Properties parameters = getModelloParameters("1.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-reader", parameters); - compileGeneratedSources( 5 ); - - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3StandaloneReadVerifier" ); - } + compileGeneratedSources(5); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3StandaloneReadVerifier"); + } } diff --git a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/Xpp3GeneratorTest.java b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/Xpp3GeneratorTest.java index feaeee3b0..db6138120 100644 --- a/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/Xpp3GeneratorTest.java +++ b/modello-plugins/modello-plugin-xpp3/src/test/java/org/codehaus/modello/generator/xml/xpp3/Xpp3GeneratorTest.java @@ -22,6 +22,9 @@ * SOFTWARE. */ +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloJavaGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; @@ -30,72 +33,64 @@ import org.codehaus.modello.model.Version; import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata; -import java.util.List; -import java.util.Properties; - /** * @author Trygve Laugstøl * @author Emmanuel Venisse */ -public class Xpp3GeneratorTest - extends AbstractModelloJavaGeneratorTest -{ - public Xpp3GeneratorTest() - { - super( "xpp3" ); +public class Xpp3GeneratorTest extends AbstractModelloJavaGeneratorTest { + public Xpp3GeneratorTest() { + super("xpp3"); } - public void testXpp3Generator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXpp3Generator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); // check some elements read from the model - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 28, classesList.size() ); + assertEquals(28, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); // now generate sources and test them - Properties parameters = getModelloParameters( "4.0.0", 5 ); + Properties parameters = getModelloParameters("4.0.0", 5); - modello.generate( model, "java", parameters ); - modello.generate( model, "xpp3-writer", parameters ); - modello.generate( model, "xpp3-reader", parameters ); + modello.generate(model, "java", parameters); + modello.generate(model, "xpp3-writer", parameters); + modello.generate(model, "xpp3-reader", parameters); - addDependency( "org.xmlunit", "xmlunit-core" ); - compileGeneratedSources( 5 ); + addDependency("org.xmlunit", "xmlunit-core"); + compileGeneratedSources(5); // TODO: see why without this, version system property is set to "2.4.1" value after verify - System.setProperty( "version", getModelloVersion() ); + System.setProperty("version", getModelloVersion()); - verifyCompiledGeneratedSources( "org.codehaus.modello.generator.xml.xpp3.Xpp3Verifier" ); + verifyCompiledGeneratedSources("org.codehaus.modello.generator.xml.xpp3.Xpp3Verifier"); } } diff --git a/modello-plugins/modello-plugin-xsd/pom.xml b/modello-plugins/modello-plugin-xsd/pom.xml index 0d75c1da5..fe19e40ce 100644 --- a/modello-plugins/modello-plugin-xsd/pom.xml +++ b/modello-plugins/modello-plugin-xsd/pom.xml @@ -1,17 +1,15 @@ + + 4.0.0 - modello-plugins org.codehaus.modello + modello-plugins 2.1.2-SNAPSHOT - - 4.0.0 modello-plugin-xsd Modello XSD Plugin - - Modello XSD Plugin generates an XML Schema from the model to be able to validate XML content. - + Modello XSD Plugin generates an XML Schema from the model to be able to validate XML content. diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java index 10643e291..754229138 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdGenerator.java @@ -22,6 +22,14 @@ * SOFTWARE. */ +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.model.Model; @@ -39,152 +47,124 @@ import org.codehaus.plexus.util.xml.PrettyPrintXMLWriter; import org.codehaus.plexus.util.xml.XMLWriter; -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - /** * @author Brett Porter */ -@Component( role = ModelloGenerator.class, hint = "xsd" ) -public class XsdGenerator - extends AbstractXmlGenerator -{ +@Component(role = ModelloGenerator.class, hint = "xsd") +public class XsdGenerator extends AbstractXmlGenerator { /** * Value standing for any element name (used on xml.tagName) */ private static final String ANY_NAME = "*"; - protected static final String LS = System.getProperty( "line.separator" ); - public void generate( Model model, Properties parameters ) - throws ModelloException - { - initialize( model, parameters ); + protected static final String LS = System.getProperty("line.separator"); - try - { - generateXsd( parameters ); - } - catch ( IOException ex ) - { - throw new ModelloException( "Exception while generating xsd.", ex ); + public void generate(Model model, Properties parameters) throws ModelloException { + initialize(model, parameters); + + try { + generateXsd(parameters); + } catch (IOException ex) { + throw new ModelloException("Exception while generating xsd.", ex); } } - private void generateXsd( Properties parameters ) - throws IOException, ModelloException - { + private void generateXsd(Properties parameters) throws IOException, ModelloException { Model objectModel = getModel(); File directory = getOutputDirectory(); - if ( isPackageWithVersion() ) - { - directory = new File( directory, getGeneratedVersion().toString() ); + if (isPackageWithVersion()) { + directory = new File(directory, getGeneratedVersion().toString()); } - if ( !directory.exists() ) - { + if (!directory.exists()) { directory.mkdirs(); } // we assume parameters not null - String xsdFileName = parameters.getProperty( ModelloParameterConstants.OUTPUT_XSD_FILE_NAME ); - boolean enforceMandatoryElements = Boolean.parseBoolean( parameters.getProperty( ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS ) ); + String xsdFileName = parameters.getProperty(ModelloParameterConstants.OUTPUT_XSD_FILE_NAME); + boolean enforceMandatoryElements = + Boolean.parseBoolean(parameters.getProperty(ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS)); - File f = new File( directory, objectModel.getId() + "-" + getGeneratedVersion() + ".xsd" ); + File f = new File(directory, objectModel.getId() + "-" + getGeneratedVersion() + ".xsd"); - if ( xsdFileName != null ) - { - f = new File( directory, xsdFileName ); + if (xsdFileName != null) { + f = new File(directory, xsdFileName); } - Writer writer = WriterFactory.newXmlWriter( f ); + Writer writer = WriterFactory.newXmlWriter(f); - try - { - XMLWriter w = new PrettyPrintXMLWriter( writer ); + try { + XMLWriter w = new PrettyPrintXMLWriter(writer); - writer.append( "" ).write( LS ); + writer.append("").write(LS); - initHeader( w ); + initHeader(w); // TODO: the writer should be knowledgeable of namespaces, but this works - w.startElement( "xs:schema" ); - w.addAttribute( "xmlns:xs", "http://www.w3.org/2001/XMLSchema" ); - w.addAttribute( "elementFormDefault", "qualified" ); + w.startElement("xs:schema"); + w.addAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema"); + w.addAttribute("elementFormDefault", "qualified"); - ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), - getGeneratedVersion() ); + ModelClass root = objectModel.getClass(objectModel.getRoot(getGeneratedVersion()), getGeneratedVersion()); - String namespace = XsdModelHelper.getNamespace( root.getModel(), getGeneratedVersion() ); + String namespace = XsdModelHelper.getNamespace(root.getModel(), getGeneratedVersion()); - w.addAttribute( "xmlns", namespace ); + w.addAttribute("xmlns", namespace); - String targetNamespace = XsdModelHelper.getTargetNamespace( root.getModel(), getGeneratedVersion(), namespace ); + String targetNamespace = + XsdModelHelper.getTargetNamespace(root.getModel(), getGeneratedVersion(), namespace); // add targetNamespace if attribute is not blank (specifically set to avoid a target namespace) - if ( StringUtils.isNotBlank( targetNamespace ) ) - { - w.addAttribute( "targetNamespace", targetNamespace ); + if (StringUtils.isNotBlank(targetNamespace)) { + w.addAttribute("targetNamespace", targetNamespace); } - w.startElement( "xs:element" ); - String tagName = resolveTagName( root ); - w.addAttribute( "name", tagName ); - w.addAttribute( "type", root.getName() ); + w.startElement("xs:element"); + String tagName = resolveTagName(root); + w.addAttribute("name", tagName); + w.addAttribute("type", root.getName()); - writeClassDocumentation( w, root ); + writeClassDocumentation(w, root); w.endElement(); // Element descriptors // Traverse from root so "abstract" models aren't included - int initialCapacity = objectModel.getClasses( getGeneratedVersion() ).size(); - writeComplexTypeDescriptor( w, objectModel, root, new HashSet( initialCapacity ), - enforceMandatoryElements ); + int initialCapacity = objectModel.getClasses(getGeneratedVersion()).size(); + writeComplexTypeDescriptor( + w, objectModel, root, new HashSet(initialCapacity), enforceMandatoryElements); w.endElement(); - } - finally - { + } finally { writer.close(); } } - private static void writeClassDocumentation( XMLWriter w, ModelClass modelClass ) - { - writeDocumentation( w, modelClass.getVersionRange().toString(), modelClass.getDescription() ); + private static void writeClassDocumentation(XMLWriter w, ModelClass modelClass) { + writeDocumentation(w, modelClass.getVersionRange().toString(), modelClass.getDescription()); } - private static void writeFieldDocumentation( XMLWriter w, ModelField field ) - { - writeDocumentation( w, field.getVersionRange().toString(), field.getDescription() ); + private static void writeFieldDocumentation(XMLWriter w, ModelField field) { + writeDocumentation(w, field.getVersionRange().toString(), field.getDescription()); } - private static void writeDocumentation( XMLWriter w, String version, String description ) - { - if ( version != null || description != null ) - { - w.startElement( "xs:annotation" ); - - if ( version != null ) - { - w.startElement( "xs:documentation" ); - w.addAttribute( "source", "version" ); - w.writeText( version ); + private static void writeDocumentation(XMLWriter w, String version, String description) { + if (version != null || description != null) { + w.startElement("xs:annotation"); + + if (version != null) { + w.startElement("xs:documentation"); + w.addAttribute("source", "version"); + w.writeText(version); w.endElement(); } - if ( description != null ) - { - w.startElement( "xs:documentation" ); - w.addAttribute( "source", "description" ); - w.writeText( description ); + if (description != null) { + w.startElement("xs:documentation"); + w.addAttribute("source", "description"); + w.writeText(description); w.endElement(); } @@ -192,279 +172,236 @@ private static void writeDocumentation( XMLWriter w, String version, String desc } } - private void writeComplexTypeDescriptor( XMLWriter w, Model objectModel, ModelClass modelClass, - Set written, boolean enforceMandatoryElements ) - { - written.add( modelClass ); + private void writeComplexTypeDescriptor( + XMLWriter w, + Model objectModel, + ModelClass modelClass, + Set written, + boolean enforceMandatoryElements) { + written.add(modelClass); - w.startElement( "xs:complexType" ); - w.addAttribute( "name", modelClass.getName() ); + w.startElement("xs:complexType"); + w.addAttribute("name", modelClass.getName()); - List fields = getFieldsForXml( modelClass, getGeneratedVersion() ); + List fields = getFieldsForXml(modelClass, getGeneratedVersion()); - ModelField contentField = getContentField( fields ); + ModelField contentField = getContentField(fields); boolean hasContentField = contentField != null; - List attributeFields = getXmlAttributeFields( fields ); + List attributeFields = getXmlAttributeFields(fields); - fields.removeAll( attributeFields ); + fields.removeAll(attributeFields); - if ( hasContentField ) - { + if (hasContentField) { // yes it's only an extension of xs:string - w.startElement( "xs:simpleContent" ); + w.startElement("xs:simpleContent"); - w.startElement( "xs:extension" ); + w.startElement("xs:extension"); - w.addAttribute( "base", getXsdType( contentField.getType() ) ); + w.addAttribute("base", getXsdType(contentField.getType())); } - writeClassDocumentation( w, modelClass ); + writeClassDocumentation(w, modelClass); Set toWrite = new HashSet(); - if ( fields.size() > 0 ) - { - XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata( XsdClassMetadata.ID ); - boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals( xsdClassMetadata.getCompositor() ); + if (fields.size() > 0) { + XsdClassMetadata xsdClassMetadata = (XsdClassMetadata) modelClass.getMetadata(XsdClassMetadata.ID); + boolean compositorAll = XsdClassMetadata.COMPOSITOR_ALL.equals(xsdClassMetadata.getCompositor()); - if ( !hasContentField ) - { - if ( compositorAll ) - { - w.startElement( "xs:all" ); - } - else - { - w.startElement( "xs:sequence" ); + if (!hasContentField) { + if (compositorAll) { + w.startElement("xs:all"); + } else { + w.startElement("xs:sequence"); } } - for ( ModelField field : fields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : fields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - if ( !hasContentField ) - { - if ( fieldTagName.equals( ANY_NAME ) ) - { - w.startElement( "xs:any" ); - w.addAttribute( "minOccurs", "0" ); - w.addAttribute( "maxOccurs", "unbounded" ); - w.addAttribute( "processContents", "skip" ); + if (!hasContentField) { + if (fieldTagName.equals(ANY_NAME)) { + w.startElement("xs:any"); + w.addAttribute("minOccurs", "0"); + w.addAttribute("maxOccurs", "unbounded"); + w.addAttribute("processContents", "skip"); w.endElement(); continue; } - w.startElement( "xs:element" ); + w.startElement("xs:element"); - if ( !enforceMandatoryElements || !field.isRequired() ) - { + if (!enforceMandatoryElements || !field.isRequired()) { // Usually, would only do this if the field is not "required", but due to inheritance, it may be // present, even if not here, so we need to let it slide - w.addAttribute( "minOccurs", "0" ); + w.addAttribute("minOccurs", "0"); } } - String xsdType = getXsdType( field.getType() ); + String xsdType = getXsdType(field.getType()); - if ( "Date".equals( field.getType() ) && "long".equals( xmlFieldMetadata.getFormat() ) ) - { - xsdType = getXsdType( "long" ); + if ("Date".equals(field.getType()) && "long".equals(xmlFieldMetadata.getFormat())) { + xsdType = getXsdType("long"); } - if ( xmlFieldMetadata.isContent() ) - { + if (xmlFieldMetadata.isContent()) { // nothing to add - } - else if ( ( xsdType != null ) || "char".equals( field.getType() ) || "Character".equals( field.getType() ) ) - { - w.addAttribute( "name", fieldTagName ); + } else if ((xsdType != null) || "char".equals(field.getType()) || "Character".equals(field.getType())) { + w.addAttribute("name", fieldTagName); - if ( xsdType != null ) - { + if (xsdType != null) { // schema built-in datatype - w.addAttribute( "type", xsdType ); + w.addAttribute("type", xsdType); } - if ( field.getDefaultValue() != null ) - { + if (field.getDefaultValue() != null) { // \0 is the implicit default value for char/Character but \0 isn't a valid XML char - if ( field.getDefaultValue() != "\0" ) - { - w.addAttribute( "default", field.getDefaultValue() ); + if (field.getDefaultValue() != "\0") { + w.addAttribute("default", field.getDefaultValue()); } } - writeFieldDocumentation( w, field ); + writeFieldDocumentation(w, field); - if ( xsdType == null ) - { - writeCharElement( w ); + if (xsdType == null) { + writeCharElement(w); } - } - else - { + } else { // TODO cleanup/split this part it's no really human readable :-) - if ( isInnerAssociation( field ) ) - { + if (isInnerAssociation(field)) { ModelAssociation association = (ModelAssociation) field; - ModelClass fieldModelClass = objectModel.getClass( association.getTo(), getGeneratedVersion() ); + ModelClass fieldModelClass = objectModel.getClass(association.getTo(), getGeneratedVersion()); - toWrite.add( fieldModelClass ); + toWrite.add(fieldModelClass); - if ( association.isManyMultiplicity() ) - { - XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); + if (association.isManyMultiplicity()) { + XmlAssociationMetadata xmlAssociationMetadata = (XmlAssociationMetadata) + association.getAssociationMetadata(XmlAssociationMetadata.ID); - if ( xmlAssociationMetadata.isWrappedItems() ) - { - w.addAttribute( "name", fieldTagName ); - writeFieldDocumentation( w, field ); + if (xmlAssociationMetadata.isWrappedItems()) { + w.addAttribute("name", fieldTagName); + writeFieldDocumentation(w, field); - writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field, - fieldModelClass.getName() ); - } - else - { - if ( compositorAll ) - { + writeListElement( + w, xmlFieldMetadata, xmlAssociationMetadata, field, fieldModelClass.getName()); + } else { + if (compositorAll) { // xs:all does not accept maxOccurs="unbounded", xs:sequence MUST be used // to be able to represent this constraint - throw new IllegalStateException( field.getName() + " field is declared as xml.listStyle=\"flat\" " - + "then class " + modelClass.getName() + " MUST be declared as xsd.compositor=\"sequence\"" ); + throw new IllegalStateException( + field.getName() + " field is declared as xml.listStyle=\"flat\" " + + "then class " + modelClass.getName() + + " MUST be declared as xsd.compositor=\"sequence\""); } - w.addAttribute( "name", resolveTagName( fieldTagName, xmlAssociationMetadata ) ); + w.addAttribute("name", resolveTagName(fieldTagName, xmlAssociationMetadata)); - w.addAttribute( "type", fieldModelClass.getName() ); - w.addAttribute( "maxOccurs", "unbounded" ); + w.addAttribute("type", fieldModelClass.getName()); + w.addAttribute("maxOccurs", "unbounded"); - writeFieldDocumentation( w, field ); + writeFieldDocumentation(w, field); } - } - else - { + } else { // not many multiplicity - w.addAttribute( "name", fieldTagName ); - w.addAttribute( "type", fieldModelClass.getName() ); - writeFieldDocumentation( w, field ); + w.addAttribute("name", fieldTagName); + w.addAttribute("type", fieldModelClass.getName()); + writeFieldDocumentation(w, field); } - } - else // not inner association + } else // not inner association { - w.addAttribute( "name", fieldTagName ); + w.addAttribute("name", fieldTagName); - writeFieldDocumentation( w, field ); + writeFieldDocumentation(w, field); - if ( List.class.getName().equals( field.getType() ) - || Set.class.getName().equals( field.getType() ) ) - { + if (List.class.getName().equals(field.getType()) + || Set.class.getName().equals(field.getType())) { ModelAssociation association = (ModelAssociation) field; - XmlAssociationMetadata xmlAssociationMetadata = - (XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID ); - - writeListElement( w, xmlFieldMetadata, xmlAssociationMetadata, field, - getXsdType( "String" ) ); - } - else if ( Properties.class.getName().equals( field.getType() ) - || "DOM".equals( field.getType() ) ) - { - writePropertiesElement( w ); - } - else - { - throw new IllegalStateException( "Non-association field of a non-primitive type '" - + field.getType() + "' for '" + field.getName() + "' in '" - + modelClass.getName() + "' model class" ); + XmlAssociationMetadata xmlAssociationMetadata = (XmlAssociationMetadata) + association.getAssociationMetadata(XmlAssociationMetadata.ID); + + writeListElement(w, xmlFieldMetadata, xmlAssociationMetadata, field, getXsdType("String")); + } else if (Properties.class.getName().equals(field.getType()) + || "DOM".equals(field.getType())) { + writePropertiesElement(w); + } else { + throw new IllegalStateException("Non-association field of a non-primitive type '" + + field.getType() + "' for '" + field.getName() + "' in '" + + modelClass.getName() + "' model class"); } } } - if ( !hasContentField ) - { + if (!hasContentField) { w.endElement(); } } // end fields iterator - if ( !hasContentField ) - { + if (!hasContentField) { w.endElement(); // xs:all or xs:sequence } } - for ( ModelField field : attributeFields ) - { - XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ); + for (ModelField field : attributeFields) { + XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata(XmlFieldMetadata.ID); - w.startElement( "xs:attribute" ); + w.startElement("xs:attribute"); - String xsdType = getXsdType( field.getType() ); + String xsdType = getXsdType(field.getType()); - String tagName = resolveTagName( field, xmlFieldMetadata ); + String tagName = resolveTagName(field, xmlFieldMetadata); - w.addAttribute( "name", tagName ); + w.addAttribute("name", tagName); - if ( xsdType != null ) - { - w.addAttribute( "type", xsdType ); + if (xsdType != null) { + w.addAttribute("type", xsdType); } - if ( field.getDefaultValue() != null ) - { - w.addAttribute( "default", field.getDefaultValue() ); + if (field.getDefaultValue() != null) { + w.addAttribute("default", field.getDefaultValue()); } - w.addAttribute( "use", field.isRequired() ? "required" : "optional" ); + w.addAttribute("use", field.isRequired() ? "required" : "optional"); - writeFieldDocumentation( w, field ); + writeFieldDocumentation(w, field); - if ( "char".equals( field.getType() ) || "Character".equals( field.getType() ) ) - { - writeCharElement( w ); - } - else if ( xsdType == null ) - { - throw new IllegalStateException( "Attribute field of a non-primitive type '" + field.getType() - + "' for '" + field.getName() + "' in '" + modelClass.getName() + "' model class" ); + if ("char".equals(field.getType()) || "Character".equals(field.getType())) { + writeCharElement(w); + } else if (xsdType == null) { + throw new IllegalStateException("Attribute field of a non-primitive type '" + field.getType() + + "' for '" + field.getName() + "' in '" + modelClass.getName() + "' model class"); } w.endElement(); } - if ( hasContentField ) - { - w.endElement(); //xs:extension + if (hasContentField) { + w.endElement(); // xs:extension - w.endElement(); //xs:simpleContent + w.endElement(); // xs:simpleContent } - w.endElement(); // xs:complexType - for ( ModelClass fieldModelClass : toWrite ) - { - if ( !written.contains( fieldModelClass ) ) - { - writeComplexTypeDescriptor( w, objectModel, fieldModelClass, written, enforceMandatoryElements ); + for (ModelClass fieldModelClass : toWrite) { + if (!written.contains(fieldModelClass)) { + writeComplexTypeDescriptor(w, objectModel, fieldModelClass, written, enforceMandatoryElements); } } } - private static void writeCharElement( XMLWriter w ) - { + private static void writeCharElement(XMLWriter w) { // a char, described as a simpleType base on string with a length restriction to 1 - w.startElement( "xs:simpleType" ); + w.startElement("xs:simpleType"); - w.startElement( "xs:restriction" ); - w.addAttribute( "base", "xs:string" ); + w.startElement("xs:restriction"); + w.addAttribute("base", "xs:string"); - w.startElement( "xs:length" ); - w.addAttribute( "value", "1" ); - w.addAttribute( "fixed", "true" ); + w.startElement("xs:length"); + w.addAttribute("value", "1"); + w.addAttribute("fixed", "true"); w.endElement(); @@ -473,16 +410,15 @@ private static void writeCharElement( XMLWriter w ) w.endElement(); } - private static void writePropertiesElement( XMLWriter w ) - { - w.startElement( "xs:complexType" ); + private static void writePropertiesElement(XMLWriter w) { + w.startElement("xs:complexType"); - w.startElement( "xs:sequence" ); + w.startElement("xs:sequence"); - w.startElement( "xs:any" ); - w.addAttribute( "minOccurs", "0" ); - w.addAttribute( "maxOccurs", "unbounded" ); - w.addAttribute( "processContents", "skip" ); + w.startElement("xs:any"); + w.addAttribute("minOccurs", "0"); + w.addAttribute("maxOccurs", "unbounded"); + w.addAttribute("processContents", "skip"); w.endElement(); @@ -491,30 +427,30 @@ private static void writePropertiesElement( XMLWriter w ) w.endElement(); } - private void writeListElement( XMLWriter w, XmlFieldMetadata xmlFieldMetadata, - XmlAssociationMetadata xmlAssociationMetadata, ModelField field, String type ) - { - String fieldTagName = resolveTagName( field, xmlFieldMetadata ); + private void writeListElement( + XMLWriter w, + XmlFieldMetadata xmlFieldMetadata, + XmlAssociationMetadata xmlAssociationMetadata, + ModelField field, + String type) { + String fieldTagName = resolveTagName(field, xmlFieldMetadata); - String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata ); + String valuesTagName = resolveTagName(fieldTagName, xmlAssociationMetadata); - w.startElement( "xs:complexType" ); + w.startElement("xs:complexType"); - w.startElement( "xs:sequence" ); + w.startElement("xs:sequence"); - if ( valuesTagName.equals( ANY_NAME ) ) - { - w.startElement( "xs:any" ); - w.addAttribute( "processContents", "skip" ); - } - else - { - w.startElement( "xs:element" ); - w.addAttribute( "type", type ); - w.addAttribute( "name", valuesTagName ); + if (valuesTagName.equals(ANY_NAME)) { + w.startElement("xs:any"); + w.addAttribute("processContents", "skip"); + } else { + w.startElement("xs:element"); + w.addAttribute("type", type); + w.addAttribute("name", valuesTagName); } - w.addAttribute( "minOccurs", "0" ); - w.addAttribute( "maxOccurs", "unbounded" ); + w.addAttribute("minOccurs", "0"); + w.addAttribute("maxOccurs", "unbounded"); w.endElement(); @@ -523,46 +459,26 @@ private void writeListElement( XMLWriter w, XmlFieldMetadata xmlFieldMetadata, w.endElement(); } - private static String getXsdType( String type ) - { - if ( "String".equals( type ) ) - { + private static String getXsdType(String type) { + if ("String".equals(type)) { return "xs:string"; - } - else if ( "boolean".equals( type ) || "Boolean".equals( type ) ) - { + } else if ("boolean".equals(type) || "Boolean".equals(type)) { return "xs:boolean"; - } - else if ( "byte".equals( type ) || "Byte".equals( type ) ) - { + } else if ("byte".equals(type) || "Byte".equals(type)) { return "xs:byte"; - } - else if ( "short".equals( type ) || "Short".equals( type ) ) - { + } else if ("short".equals(type) || "Short".equals(type)) { return "xs:short"; - } - else if ( "int".equals( type ) || "Integer".equals( type ) ) - { + } else if ("int".equals(type) || "Integer".equals(type)) { return "xs:int"; - } - else if ( "long".equals( type ) || "Long".equals( type ) ) - { + } else if ("long".equals(type) || "Long".equals(type)) { return "xs:long"; - } - else if ( "float".equals( type ) || "Float".equals( type ) ) - { + } else if ("float".equals(type) || "Float".equals(type)) { return "xs:float"; - } - else if ( "double".equals( type ) || "Double".equals( type ) ) - { + } else if ("double".equals(type) || "Double".equals(type)) { return "xs:double"; - } - else if ( "Date".equals( type ) ) - { + } else if ("Date".equals(type)) { return "xs:dateTime"; - } - else - { + } else { return null; } } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdModelHelper.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdModelHelper.java index 7a00cdd21..5f0bb8a5c 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdModelHelper.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/XsdModelHelper.java @@ -34,55 +34,42 @@ * * @author Hervé Boutemy */ -public class XsdModelHelper -{ - public static String getNamespace( Model model, Version version ) - throws ModelloException - { - XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) model.getMetadata( XmlModelMetadata.ID ); +public class XsdModelHelper { + public static String getNamespace(Model model, Version version) throws ModelloException { + XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) model.getMetadata(XmlModelMetadata.ID); - XsdModelMetadata xsdModelMetadata = (XsdModelMetadata) model.getMetadata( XsdModelMetadata.ID ); + XsdModelMetadata xsdModelMetadata = (XsdModelMetadata) model.getMetadata(XsdModelMetadata.ID); String namespace; - if ( StringUtils.isNotEmpty( xsdModelMetadata.getNamespace() ) ) - { - namespace = xsdModelMetadata.getNamespace( version ); - } - else - { + if (StringUtils.isNotEmpty(xsdModelMetadata.getNamespace())) { + namespace = xsdModelMetadata.getNamespace(version); + } else { // xsd.namespace is not set, try using xml.namespace - if ( StringUtils.isEmpty( xmlModelMetadata.getNamespace() ) ) - { - throw new ModelloException( "Cannot generate xsd without xmlns specification:" - + " or " ); + if (StringUtils.isEmpty(xmlModelMetadata.getNamespace())) { + throw new ModelloException("Cannot generate xsd without xmlns specification:" + + " or "); } - namespace = xmlModelMetadata.getNamespace( version ); + namespace = xmlModelMetadata.getNamespace(version); } return namespace; } - public static String getTargetNamespace( Model model, Version version, String namespace ) - { - XsdModelMetadata xsdModelMetadata = (XsdModelMetadata) model.getMetadata( XsdModelMetadata.ID ); + public static String getTargetNamespace(Model model, Version version, String namespace) { + XsdModelMetadata xsdModelMetadata = (XsdModelMetadata) model.getMetadata(XsdModelMetadata.ID); String targetNamespace; - if ( xsdModelMetadata.getTargetNamespace() == null ) - { + if (xsdModelMetadata.getTargetNamespace() == null) { // xsd.targetNamespace not set, using namespace targetNamespace = namespace; - } - else - { - targetNamespace = xsdModelMetadata.getTargetNamespace( version ); + } else { + targetNamespace = xsdModelMetadata.getTargetNamespace(version); } return targetNamespace; } - public static String getTargetNamespace( Model model, Version version ) - throws ModelloException - { - return getTargetNamespace( model, version, getNamespace( model, version ) ); + public static String getTargetNamespace(Model model, Version version) throws ModelloException { + return getTargetNamespace(model, version, getNamespace(model, version)); } } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdAssociationMetadata.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdAssociationMetadata.java index 708b3d47f..f9fee6010 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdAssociationMetadata.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdAssociationMetadata.java @@ -19,11 +19,10 @@ import org.codehaus.modello.metadata.AssociationMetadata; /** - * XsdAssociationMetadata + * XsdAssociationMetadata * * @author Joakim Erdfelt */ -public class XsdAssociationMetadata implements AssociationMetadata -{ +public class XsdAssociationMetadata implements AssociationMetadata { public static final String ID = XsdAssociationMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdClassMetadata.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdClassMetadata.java index 33675bcb2..4b8efa5fc 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdClassMetadata.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdClassMetadata.java @@ -23,8 +23,7 @@ * * @author Joakim Erdfelt */ -public class XsdClassMetadata implements ClassMetadata -{ +public class XsdClassMetadata implements ClassMetadata { public static final String ID = XsdClassMetadata.class.getName(); public static final String COMPOSITOR_ALL = "all"; @@ -33,22 +32,16 @@ public class XsdClassMetadata implements ClassMetadata private String compositor = COMPOSITOR_ALL; - public String getCompositor() - { + public String getCompositor() { return compositor; } - public void setCompositor( String compositor ) - { - if ( COMPOSITOR_ALL.equals( compositor ) || COMPOSITOR_SEQUENCE.equals( compositor ) ) - { + public void setCompositor(String compositor) { + if (COMPOSITOR_ALL.equals(compositor) || COMPOSITOR_SEQUENCE.equals(compositor)) { this.compositor = compositor; - } - else - { + } else { // default this.compositor = COMPOSITOR_ALL; } } - } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdFieldMetadata.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdFieldMetadata.java index 6a2a95dd2..90fc76e7e 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdFieldMetadata.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdFieldMetadata.java @@ -19,11 +19,10 @@ import org.codehaus.modello.metadata.FieldMetadata; /** - * XsdFieldMetadata + * XsdFieldMetadata * * @author Joakim Erdfelt */ -public class XsdFieldMetadata implements FieldMetadata -{ +public class XsdFieldMetadata implements FieldMetadata { public static final String ID = XsdFieldMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdInterfaceMetadata.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdInterfaceMetadata.java index 098a37c51..4136768a6 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdInterfaceMetadata.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdInterfaceMetadata.java @@ -19,12 +19,10 @@ import org.codehaus.modello.metadata.InterfaceMetadata; /** - * XsdFieldMetadata + * XsdFieldMetadata * * @author Joakim Erdfelt */ -public class XsdInterfaceMetadata - implements InterfaceMetadata -{ +public class XsdInterfaceMetadata implements InterfaceMetadata { public static final String ID = XsdInterfaceMetadata.class.getName(); } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdMetadataPlugin.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdMetadataPlugin.java index 9368dcd68..685611a28 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdMetadataPlugin.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdMetadataPlugin.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import java.util.Map; + import org.codehaus.modello.ModelloException; import org.codehaus.modello.metadata.AbstractMetadataPlugin; import org.codehaus.modello.metadata.AssociationMetadata; @@ -31,59 +33,47 @@ import org.codehaus.modello.model.ModelInterface; import org.codehaus.plexus.component.annotations.Component; -import java.util.Map; - /** * XsdMetadataPlugin * * @author Joakim Erdfelt */ -@Component( role = MetadataPlugin.class, hint = "xdoc" ) -public class XsdMetadataPlugin - extends AbstractMetadataPlugin -{ +@Component(role = MetadataPlugin.class, hint = "xdoc") +public class XsdMetadataPlugin extends AbstractMetadataPlugin { public static final String NAMESPACE = "xsd.namespace"; public static final String TARGET_NAMESPACE = "xsd.targetNamespace"; public static final String COMPOSITOR = "xsd.compositor"; - public AssociationMetadata getAssociationMetadata( ModelAssociation association, Map data ) - throws ModelloException - { + public AssociationMetadata getAssociationMetadata(ModelAssociation association, Map data) + throws ModelloException { return new XsdAssociationMetadata(); } - public ClassMetadata getClassMetadata( ModelClass clazz, Map data ) - throws ModelloException - { + public ClassMetadata getClassMetadata(ModelClass clazz, Map data) throws ModelloException { XsdClassMetadata metadata = new XsdClassMetadata(); - metadata.setCompositor( getString( data, COMPOSITOR ) ); + metadata.setCompositor(getString(data, COMPOSITOR)); return metadata; } - public InterfaceMetadata getInterfaceMetadata( ModelInterface iface, Map data ) - throws ModelloException - { + public InterfaceMetadata getInterfaceMetadata(ModelInterface iface, Map data) + throws ModelloException { return new XsdInterfaceMetadata(); } - public FieldMetadata getFieldMetadata( ModelField field, Map data ) - throws ModelloException - { + public FieldMetadata getFieldMetadata(ModelField field, Map data) throws ModelloException { return new XsdFieldMetadata(); } - public ModelMetadata getModelMetadata( Model model, Map data ) - throws ModelloException - { + public ModelMetadata getModelMetadata(Model model, Map data) throws ModelloException { XsdModelMetadata metadata = new XsdModelMetadata(); - metadata.setNamespace( getString( data, NAMESPACE ) ); + metadata.setNamespace(getString(data, NAMESPACE)); - metadata.setTargetNamespace( getString( data, TARGET_NAMESPACE ) ); + metadata.setTargetNamespace(getString(data, TARGET_NAMESPACE)); return metadata; } diff --git a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdModelMetadata.java b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdModelMetadata.java index 7671e4db8..dffb35427 100644 --- a/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdModelMetadata.java +++ b/modello-plugins/modello-plugin-xsd/src/main/java/org/codehaus/modello/plugin/xsd/metadata/XsdModelMetadata.java @@ -25,53 +25,44 @@ * * @author Joakim Erdfelt */ -public class XsdModelMetadata implements ModelMetadata -{ +public class XsdModelMetadata implements ModelMetadata { public static final String ID = XsdModelMetadata.class.getName(); private String namespace; private String targetNamespace; - public String getNamespace() - { + public String getNamespace() { return namespace; } - public void setNamespace( String namespace ) - { + public void setNamespace(String namespace) { this.namespace = namespace; } - public String getTargetNamespace() - { + public String getTargetNamespace() { return targetNamespace; } - public void setTargetNamespace( String targetNamespace ) - { + public void setTargetNamespace(String targetNamespace) { this.targetNamespace = targetNamespace; } - public String getNamespace( Version version ) - { + public String getNamespace(Version version) { String namespace = this.namespace; - if ( version != null ) - { - namespace = StringUtils.replace( namespace, "${version}", version.toString() ); + if (version != null) { + namespace = StringUtils.replace(namespace, "${version}", version.toString()); } return namespace; } - public String getTargetNamespace( Version version ) - { + public String getTargetNamespace(Version version) { String targetNamespace = this.targetNamespace; - if ( version != null ) - { - targetNamespace = StringUtils.replace( targetNamespace, "${version}", version.toString() ); + if (version != null) { + targetNamespace = StringUtils.replace(targetNamespace, "${version}", version.toString()); } return targetNamespace; diff --git a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ChangesXsdGeneratorTest.java b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ChangesXsdGeneratorTest.java index 76a69a57c..d3c013121 100755 --- a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ChangesXsdGeneratorTest.java +++ b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ChangesXsdGeneratorTest.java @@ -31,32 +31,26 @@ /** * @author Brett Porter */ -public class ChangesXsdGeneratorTest - extends AbstractModelloGeneratorTest -{ - public ChangesXsdGeneratorTest() - { - super( "xsd-changes" ); +public class ChangesXsdGeneratorTest extends AbstractModelloGeneratorTest { + public ChangesXsdGeneratorTest() { + super("xsd-changes"); } - public void testXsdGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXsdGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/changes.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/changes.mdo")); // generate XSD file - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "xsd", parameters ); + modello.generate(model, "xsd", parameters); - //addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); + // addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); // TODO write verifier that compiles generated schema: use jaxp - //verify( "org.codehaus.modello.generator.xml.xsd.XsdVerifier", "xsd" ); - + // verify( "org.codehaus.modello.generator.xml.xsd.XsdVerifier", "xsd" ); } } diff --git a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/FeaturesXsdGeneratorTest.java b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/FeaturesXsdGeneratorTest.java index 30c612a0b..cf9063fdd 100644 --- a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/FeaturesXsdGeneratorTest.java +++ b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/FeaturesXsdGeneratorTest.java @@ -22,6 +22,15 @@ * SOFTWARE. */ +import javax.xml.XMLConstants; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + +import java.io.File; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloGeneratorTest; import org.codehaus.modello.ModelloException; import org.codehaus.modello.ModelloParameterConstants; @@ -29,83 +38,57 @@ import org.codehaus.modello.model.Model; import org.xml.sax.SAXParseException; -import java.io.File; -import java.util.Properties; - -import javax.xml.XMLConstants; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - /** * @author Hervé Boutemy */ -public class FeaturesXsdGeneratorTest - extends AbstractModelloGeneratorTest -{ - public FeaturesXsdGeneratorTest() - { - super( "features" ); +public class FeaturesXsdGeneratorTest extends AbstractModelloGeneratorTest { + public FeaturesXsdGeneratorTest() { + super("features"); } - public void testXsdGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXsdGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/features.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/features.mdo")); - Properties parameters = getModelloParameters( "1.0.0" ); - parameters.setProperty( ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS, "true" ); - - modello.generate( model, "xsd", parameters ); + Properties parameters = getModelloParameters("1.0.0"); + parameters.setProperty(ModelloParameterConstants.XSD_ENFORCE_MANDATORY_ELEMENTS, "true"); - SchemaFactory sf = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); - Schema schema = sf.newSchema( new StreamSource( new File( getOutputDirectory(), "features-1.0.0.xsd" ) ) ); + modello.generate(model, "xsd", parameters); + + SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + Schema schema = sf.newSchema(new StreamSource(new File(getOutputDirectory(), "features-1.0.0.xsd"))); Validator validator = schema.newValidator(); - try - { - validator.validate( new StreamSource( getClass().getResourceAsStream( "/features.xml" ) ) ); - } - catch ( SAXParseException e ) - { - throw new ModelloException( "line " + e.getLineNumber() + " column " + e.getColumnNumber(), e ); + try { + validator.validate(new StreamSource(getClass().getResourceAsStream("/features.xml"))); + } catch (SAXParseException e) { + throw new ModelloException("line " + e.getLineNumber() + " column " + e.getColumnNumber(), e); } - try - { - validator.validate( new StreamSource( getClass().getResourceAsStream( "/features-invalid.xml" ) ) ); - fail( "parsing of features-invalid.xml should have failed" ); - } - catch ( SAXParseException e ) - { + try { + validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid.xml"))); + fail("parsing of features-invalid.xml should have failed"); + } catch (SAXParseException e) { // ok, expected exception - assertTrue( e.getMessage().contains( "invalidElement" ) ); + assertTrue(e.getMessage().contains("invalidElement")); } - try - { - validator.validate( new StreamSource( getClass().getResourceAsStream( "/features-missing-required.xml" ) ) ); - fail( "parsing of features-invalid.xml should have failed" ); - } - catch ( SAXParseException e ) - { + try { + validator.validate(new StreamSource(getClass().getResourceAsStream("/features-missing-required.xml"))); + fail("parsing of features-invalid.xml should have failed"); + } catch (SAXParseException e) { // ok, expected exception - assertTrue( e.getMessage().contains( "description" ) ); - assertTrue( e.getMessage().endsWith(" is expected.")); + assertTrue(e.getMessage().contains("description")); + assertTrue(e.getMessage().endsWith(" is expected.")); } - try - { - validator.validate( new StreamSource( getClass().getResourceAsStream( "/features-invalid-transient.xml" ) ) ); - fail( "XSD did not prohibit appearance of transient fields" ); - } - catch ( SAXParseException e ) - { + try { + validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid-transient.xml"))); + fail("XSD did not prohibit appearance of transient fields"); + } catch (SAXParseException e) { // ok, expected exception - assertTrue( e.getMessage().contains( "transientString" ) ); + assertTrue(e.getMessage().contains("transientString")); } } } diff --git a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ModelloXsdGeneratorTest.java b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ModelloXsdGeneratorTest.java index 761a78010..2dec50768 100644 --- a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ModelloXsdGeneratorTest.java +++ b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/ModelloXsdGeneratorTest.java @@ -22,64 +22,52 @@ * SOFTWARE. */ +import javax.xml.parsers.SAXParser; + +import java.util.Properties; + import org.codehaus.modello.AbstractModelloGeneratorTest; -import org.codehaus.modello.ModelloParameterConstants; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; -import java.util.Properties; - -import javax.xml.parsers.SAXParser; - /** * Check that features.mdo (which tries to be the most complete model) can be checked against XSD generated from * Modello model modello.mdo. * * @author Hervé Boutemy */ -public class ModelloXsdGeneratorTest - extends AbstractModelloGeneratorTest -{ - public ModelloXsdGeneratorTest() - { - super( "modello" ); +public class ModelloXsdGeneratorTest extends AbstractModelloGeneratorTest { + public ModelloXsdGeneratorTest() { + super("modello"); } - public void testXsdGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXsdGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Properties parameters = getModelloParameters( "1.4.0" ); + Properties parameters = getModelloParameters("1.4.0"); - Model model = modello.loadModel( getTestFile( "../../src/main/mdo/modello.mdo" ) ); + Model model = modello.loadModel(getTestFile("../../src/main/mdo/modello.mdo")); - modello.generate( model, "xsd", parameters ); + modello.generate(model, "xsd", parameters); - SAXParser saxParser = createSaxParserWithSchema( "modello-1.4.0.xsd" ); + SAXParser saxParser = createSaxParserWithSchema("modello-1.4.0.xsd"); // first self-test: validate Modello model with xsd generated from it - saxParser.parse( getTestFile( "../../src/main/mdo/modello.mdo" ), new Handler() ); + saxParser.parse(getTestFile("../../src/main/mdo/modello.mdo"), new Handler()); // then features.mdo - saxParser.parse( getClass().getResourceAsStream( "/features.mdo" ), new Handler() ); + saxParser.parse(getClass().getResourceAsStream("/features.mdo"), new Handler()); } - private static class Handler - extends DefaultHandler - { - public void warning ( SAXParseException e ) - throws SAXException - { + private static class Handler extends DefaultHandler { + public void warning(SAXParseException e) throws SAXException { throw e; } - public void error ( SAXParseException e ) - throws SAXException - { + public void error(SAXParseException e) throws SAXException { throw e; } } diff --git a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/PluginsXsdGeneratorTest.java b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/PluginsXsdGeneratorTest.java index af5ae917f..98ddb19f8 100644 --- a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/PluginsXsdGeneratorTest.java +++ b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/PluginsXsdGeneratorTest.java @@ -17,51 +17,41 @@ import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; -/** +/** * Test that the Maven plugin descriptor * generates an XSD which can validate plugin descriptors (with arbitrary element names below {@code }). * @see Issue 264 * */ -public class PluginsXsdGeneratorTest - extends AbstractModelloGeneratorTest -{ +public class PluginsXsdGeneratorTest extends AbstractModelloGeneratorTest { - public PluginsXsdGeneratorTest() - { - super( "plugins" ); + public PluginsXsdGeneratorTest() { + super("plugins"); } @Test public void testWithNameWildcard() - throws ModelloException, ModelValidationException, IOException, ComponentLookupException, - ParserConfigurationException, SAXException - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + throws ModelloException, ModelValidationException, IOException, ComponentLookupException, + ParserConfigurationException, SAXException { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/plugin.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/plugin.mdo")); // generate XSD file - Properties parameters = getModelloParameters( "1.0.0" ); + Properties parameters = getModelloParameters("1.0.0"); - modello.generate( model, "xsd", parameters ); + modello.generate(model, "xsd", parameters); - SAXParser parser = createSaxParserWithSchema( "plugin-1.0.0.xsd" ); - parser.parse( getClass().getResourceAsStream( "/plugin.xml" ), new Handler() ); + SAXParser parser = createSaxParserWithSchema("plugin-1.0.0.xsd"); + parser.parse(getClass().getResourceAsStream("/plugin.xml"), new Handler()); } - private static class Handler - extends DefaultHandler - { - public void warning( SAXParseException e ) - throws SAXException - { + private static class Handler extends DefaultHandler { + public void warning(SAXParseException e) throws SAXException { throw e; } - public void error( SAXParseException e ) - throws SAXException - { + public void error(SAXParseException e) throws SAXException { throw e; } } diff --git a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/XsdGeneratorTest.java b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/XsdGeneratorTest.java index 8215f1905..e4d34a826 100644 --- a/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/XsdGeneratorTest.java +++ b/modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/XsdGeneratorTest.java @@ -22,6 +22,9 @@ * SOFTWARE. */ +import java.util.List; +import java.util.Properties; + import org.codehaus.modello.AbstractModelloGeneratorTest; import org.codehaus.modello.core.ModelloCore; import org.codehaus.modello.model.Model; @@ -30,67 +33,59 @@ import org.codehaus.modello.model.Version; import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata; -import java.util.List; -import java.util.Properties; - /** * @author Brett Porter */ -public class XsdGeneratorTest - extends AbstractModelloGeneratorTest -{ - public XsdGeneratorTest() - { - super( "xsd" ); +public class XsdGeneratorTest extends AbstractModelloGeneratorTest { + public XsdGeneratorTest() { + super("xsd"); } - public void testXsdGenerator() - throws Throwable - { - ModelloCore modello = (ModelloCore) lookup( ModelloCore.ROLE ); + public void testXsdGenerator() throws Throwable { + ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE); - Model model = modello.loadModel( getXmlResourceReader( "/maven.mdo" ) ); + Model model = modello.loadModel(getXmlResourceReader("/maven.mdo")); // check misc. properties of the model loaded - List classesList = model.getClasses( new Version( "4.0.0" ) ); + List classesList = model.getClasses(new Version("4.0.0")); - assertEquals( 26, classesList.size() ); + assertEquals(26, classesList.size()); - ModelClass clazz = (ModelClass) classesList.get( 0 ); + ModelClass clazz = (ModelClass) classesList.get(0); - assertEquals( "Model", clazz.getName() ); + assertEquals("Model", clazz.getName()); - ModelField extend = clazz.getField( "extend", new Version( "4.0.0" ) ); + ModelField extend = clazz.getField("extend", new Version("4.0.0")); - assertTrue( extend.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(extend.hasMetadata(XmlFieldMetadata.ID)); - XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata( XmlFieldMetadata.ID ); + XmlFieldMetadata xml = (XmlFieldMetadata) extend.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertTrue( xml.isAttribute() ); + assertTrue(xml.isAttribute()); - assertEquals( "extender", xml.getTagName() ); + assertEquals("extender", xml.getTagName()); - ModelField build = clazz.getField( "build", new Version( "4.0.0" ) ); + ModelField build = clazz.getField("build", new Version("4.0.0")); - assertTrue( build.hasMetadata( XmlFieldMetadata.ID ) ); + assertTrue(build.hasMetadata(XmlFieldMetadata.ID)); - xml = (XmlFieldMetadata) build.getMetadata( XmlFieldMetadata.ID ); + xml = (XmlFieldMetadata) build.getMetadata(XmlFieldMetadata.ID); - assertNotNull( xml ); + assertNotNull(xml); - assertEquals( "builder", xml.getTagName() ); + assertEquals("builder", xml.getTagName()); // generate XSD file - Properties parameters = getModelloParameters( "4.0.0" ); + Properties parameters = getModelloParameters("4.0.0"); - modello.generate( model, "xsd", parameters ); + modello.generate(model, "xsd", parameters); - //addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); + // addDependency( "modello", "modello-core", "1.0-SNAPSHOT" ); // TODO write verfier which compile generated schema : use jaxp - //verify( "org.codehaus.modello.generator.xml.xsd.XsdVerifier", "xsd" ); + // verify( "org.codehaus.modello.generator.xml.xsd.XsdVerifier", "xsd" ); } } diff --git a/modello-plugins/pom.xml b/modello-plugins/pom.xml index a34638779..4f4de80f7 100644 --- a/modello-plugins/pom.xml +++ b/modello-plugins/pom.xml @@ -1,19 +1,17 @@ + + 4.0.0 - modello org.codehaus.modello + modello 2.1.2-SNAPSHOT - - 4.0.0 modello-plugins pom Modello Plugins - - Modello Plugins is the main component containing every Modello plugins that are able to generate various types of - code and descriptors. - + Modello Plugins is the main component containing every Modello plugins that are able to generate various types of + code and descriptors. modello-plugin-java @@ -57,10 +55,10 @@ copy-test-libs - process-test-resources copy-dependencies + process-test-resources ${project.build.directory}/test-libs true diff --git a/modello-test/pom.xml b/modello-test/pom.xml index 1fd5c8bac..b8c968f4c 100644 --- a/modello-test/pom.xml +++ b/modello-test/pom.xml @@ -1,18 +1,16 @@ + + 4.0.0 - modello org.codehaus.modello + modello 2.1.2-SNAPSHOT - - 4.0.0 modello-test Modello Test Package - - Modello Test Package contains the basis to create Modello generator unit-tests, including sample models - and xml files to test every feature for every plugin. - + Modello Test Package contains the basis to create Modello generator unit-tests, including sample models + and xml files to test every feature for every plugin. 2.13.0 @@ -47,4 +45,4 @@ test - \ No newline at end of file +
diff --git a/modello-test/src/main/java/org/codehaus/modello/AbstractModelloGeneratorTest.java b/modello-test/src/main/java/org/codehaus/modello/AbstractModelloGeneratorTest.java index e84df04bb..e71231fb4 100644 --- a/modello-test/src/main/java/org/codehaus/modello/AbstractModelloGeneratorTest.java +++ b/modello-test/src/main/java/org/codehaus/modello/AbstractModelloGeneratorTest.java @@ -22,16 +22,16 @@ * SOFTWARE. */ +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Optional; import java.util.Properties; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.ReaderFactory; @@ -42,79 +42,69 @@ * * @author Trygve Laugstøl */ -public abstract class AbstractModelloGeneratorTest - extends PlexusTestCase -{ +public abstract class AbstractModelloGeneratorTest extends PlexusTestCase { private String name; - protected AbstractModelloGeneratorTest( String name ) - { + protected AbstractModelloGeneratorTest(String name) { this.name = name; } - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - FileUtils.deleteDirectory( getOutputDirectory() ); + FileUtils.deleteDirectory(getOutputDirectory()); - assertTrue( getOutputDirectory().mkdirs() ); + assertTrue(getOutputDirectory().mkdirs()); } - protected File getOutputDirectory() - { - return getTestFile( "target/generator-results/" + getName() ); + protected File getOutputDirectory() { + return getTestFile("target/generator-results/" + getName()); } - public String getName() - { + public String getName() { return name; } - protected Properties getModelloParameters() - { + protected Properties getModelloParameters() { Properties parameters = new Properties(); - parameters.setProperty( "modello.output.directory", getOutputDirectory().getAbsolutePath() ); + parameters.setProperty("modello.output.directory", getOutputDirectory().getAbsolutePath()); return parameters; } - protected Properties getModelloParameters( String version ) - { - Properties parameters = getModelloParameters( version, null ); + protected Properties getModelloParameters(String version) { + Properties parameters = getModelloParameters(version, null); return parameters; } - protected Properties getModelloParameters( String version, Integer javaSource ) - { + protected Properties getModelloParameters(String version, Integer javaSource) { Properties parameters = getModelloParameters(); - parameters.setProperty( "modello.package.with.version", Boolean.toString( false ) ); - parameters.setProperty( "modello.version", version ); - Optional.ofNullable( javaSource ).ifPresent( a -> parameters.setProperty( "modello.output.java.source", - Integer.toString( a ) ) ); + parameters.setProperty("modello.package.with.version", Boolean.toString(false)); + parameters.setProperty("modello.version", version); + Optional.ofNullable(javaSource) + .ifPresent(a -> parameters.setProperty("modello.output.java.source", Integer.toString(a))); return parameters; } - protected Reader getXmlResourceReader( String name ) - throws IOException - { - return ReaderFactory.newXmlReader( getClass().getResourceAsStream( name ) ); + protected Reader getXmlResourceReader(String name) throws IOException { + return ReaderFactory.newXmlReader(getClass().getResourceAsStream(name)); } - protected SAXParser createSaxParserWithSchema( String generatedXsdName ) throws ParserConfigurationException, SAXException { + protected SAXParser createSaxParserWithSchema(String generatedXsdName) + throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setValidating( true ); - factory.setNamespaceAware( true ); + factory.setValidating(true); + factory.setNamespaceAware(true); SAXParser saxParser = factory.newSAXParser(); - saxParser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", - "http://www.w3.org/2001/XMLSchema" ); - saxParser.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaSource", - new File( getOutputDirectory(), generatedXsdName ) ); + saxParser.setProperty( + "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); + saxParser.setProperty( + "http://java.sun.com/xml/jaxp/properties/schemaSource", + new File(getOutputDirectory(), generatedXsdName)); return saxParser; } } diff --git a/modello-test/src/main/java/org/codehaus/modello/AbstractModelloJavaGeneratorTest.java b/modello-test/src/main/java/org/codehaus/modello/AbstractModelloJavaGeneratorTest.java index 21808110e..2b9ee7f4c 100755 --- a/modello-test/src/main/java/org/codehaus/modello/AbstractModelloJavaGeneratorTest.java +++ b/modello-test/src/main/java/org/codehaus/modello/AbstractModelloJavaGeneratorTest.java @@ -22,16 +22,6 @@ * SOFTWARE. */ -import org.codehaus.modello.verifier.VerifierException; -import org.codehaus.plexus.compiler.Compiler; -import org.codehaus.plexus.compiler.CompilerConfiguration; -import org.codehaus.plexus.compiler.CompilerException; -import org.codehaus.plexus.compiler.CompilerMessage; -import org.codehaus.plexus.compiler.CompilerResult; -import org.codehaus.plexus.compiler.javac.JavacCompiler; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.util.FileUtils; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -45,6 +35,15 @@ import java.util.List; import java.util.Properties; +import org.codehaus.modello.verifier.VerifierException; +import org.codehaus.plexus.compiler.Compiler; +import org.codehaus.plexus.compiler.CompilerConfiguration; +import org.codehaus.plexus.compiler.CompilerException; +import org.codehaus.plexus.compiler.CompilerMessage; +import org.codehaus.plexus.compiler.CompilerResult; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.codehaus.plexus.util.FileUtils; + /** * Base class for unit-tests of Modello plugins that generate java code. * @@ -54,219 +53,171 @@ * class against compiled generated code * @see org.codehaus.modello.verifier.Verifier Verifier base class for verifiers */ -public abstract class AbstractModelloJavaGeneratorTest - extends AbstractModelloGeneratorTest -{ +public abstract class AbstractModelloJavaGeneratorTest extends AbstractModelloGeneratorTest { private List dependencies = new ArrayList(); private List urls = new ArrayList(); private List classPathElements = new ArrayList(); - protected AbstractModelloJavaGeneratorTest( String name ) - { - super( name ); + protected AbstractModelloJavaGeneratorTest(String name) { + super(name); } - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - FileUtils.deleteDirectory( getOutputClasses() ); + FileUtils.deleteDirectory(getOutputClasses()); - assertTrue( getOutputClasses().mkdirs() ); + assertTrue(getOutputClasses().mkdirs()); } - protected File getOutputDirectory() - { - return new File( super.getOutputDirectory(), "sources" ); + protected File getOutputDirectory() { + return new File(super.getOutputDirectory(), "sources"); } - protected File getOutputClasses() - { - return new File( super.getOutputDirectory(), "classes" ); + protected File getOutputClasses() { + return new File(super.getOutputDirectory(), "classes"); } - protected void addDependency( String groupId, String artifactId ) - { - File dependencyFile = getDependencyFile( groupId, artifactId ); + protected void addDependency(String groupId, String artifactId) { + File dependencyFile = getDependencyFile(groupId, artifactId); - dependencies.add( dependencyFile ); + dependencies.add(dependencyFile); - addClassPathFile( dependencyFile ); + addClassPathFile(dependencyFile); } - protected File getDependencyFile( String groupId, String artifactId ) - { + protected File getDependencyFile(String groupId, String artifactId) { // NOTE: dependency version is managed by project POM and not selectable by test - String libsDir = System.getProperty( "tests.lib.dir", "target/test-libs" ); - File dependencyFile = new File( libsDir, artifactId + ".jar" ); + String libsDir = System.getProperty("tests.lib.dir", "target/test-libs"); + File dependencyFile = new File(libsDir, artifactId + ".jar"); - assertTrue( "Can't find dependency: " + dependencyFile.getAbsolutePath(), dependencyFile.isFile() ); + assertTrue("Can't find dependency: " + dependencyFile.getAbsolutePath(), dependencyFile.isFile()); return dependencyFile; } - public List getClasspath() - { + public List getClasspath() { return dependencies; } - protected String getModelloVersion() - throws IOException - { - Properties properties = new Properties( System.getProperties() ); + protected String getModelloVersion() throws IOException { + Properties properties = new Properties(System.getProperties()); - if ( properties.getProperty( "version" ) == null ) - { - InputStream is = getResourceAsStream( "/META-INF/maven/org.codehaus.modello/modello-test/pom.properties" ); + if (properties.getProperty("version") == null) { + InputStream is = getResourceAsStream("/META-INF/maven/org.codehaus.modello/modello-test/pom.properties"); - if ( is != null ) - { - properties.load( is ); + if (is != null) { + properties.load(is); } } - return properties.getProperty( "version" ); + return properties.getProperty("version"); } - protected void compileGeneratedSources() - throws IOException, CompilerException - { - compileGeneratedSources( getName() ); + protected void compileGeneratedSources() throws IOException, CompilerException { + compileGeneratedSources(getName()); } - protected void compileGeneratedSources( int minJavaSource ) - throws IOException, CompilerException - { - compileGeneratedSources( getName(), minJavaSource ); + protected void compileGeneratedSources(int minJavaSource) throws IOException, CompilerException { + compileGeneratedSources(getName(), minJavaSource); } - protected void compileGeneratedSources( String verifierId ) - throws IOException, CompilerException - { - String runtimeVersion = System.getProperty( "java.specification.version" ); - if ( runtimeVersion.startsWith( "1." ) ) - { - runtimeVersion = runtimeVersion.substring( 2 ); + protected void compileGeneratedSources(String verifierId) throws IOException, CompilerException { + String runtimeVersion = System.getProperty("java.specification.version"); + if (runtimeVersion.startsWith("1.")) { + runtimeVersion = runtimeVersion.substring(2); } - int runtimeSource = Integer.parseInt( runtimeVersion ); - + int runtimeSource = Integer.parseInt(runtimeVersion); + String javaSource; - if ( runtimeSource <= 8 ) - { + if (runtimeSource <= 8) { javaSource = "1.3"; - } - else if ( runtimeSource <= 11 ) - { + } else if (runtimeSource <= 11) { javaSource = "6"; - } - else if ( runtimeSource <= 17 ) - { + } else if (runtimeSource <= 17) { javaSource = "7"; - } - else - { + } else { javaSource = "8"; } - - compileGeneratedSources( verifierId, javaSource ); + + compileGeneratedSources(verifierId, javaSource); } - protected void compileGeneratedSources( String verifierId, int minJavaSource ) - throws IOException, CompilerException - { - String runtimeVersion = System.getProperty( "java.specification.version" ); - if ( runtimeVersion.startsWith( "1." ) ) - { - runtimeVersion = runtimeVersion.substring( 2 ); + protected void compileGeneratedSources(String verifierId, int minJavaSource) throws IOException, CompilerException { + String runtimeVersion = System.getProperty("java.specification.version"); + if (runtimeVersion.startsWith("1.")) { + runtimeVersion = runtimeVersion.substring(2); } - int runtimeSource = Integer.parseInt( runtimeVersion ); - + int runtimeSource = Integer.parseInt(runtimeVersion); + String javaSource; - if ( runtimeSource <= 8 ) - { - javaSource = "1." + Math.max( minJavaSource, 3 ); + if (runtimeSource <= 8) { + javaSource = "1." + Math.max(minJavaSource, 3); + } else if (runtimeSource <= 11) { + javaSource = Integer.toString(Math.max(minJavaSource, 6)); + } else if (runtimeSource <= 17) { + javaSource = Integer.toString(Math.max(minJavaSource, 7)); + } else { + javaSource = Integer.toString(Math.max(minJavaSource, 8)); + ; } - else if ( runtimeSource <= 11 ) - { - javaSource = Integer.toString( Math.max( minJavaSource, 6) ); - } - else if ( runtimeSource <= 17 ) - { - javaSource = Integer.toString( Math.max( minJavaSource, 7) ); - } - else - { - javaSource = Integer.toString( Math.max( minJavaSource, 8) );; - } - - compileGeneratedSources( verifierId, javaSource ); + + compileGeneratedSources(verifierId, javaSource); } - - private void compileGeneratedSources( String verifierId, String javaSource ) - throws IOException, CompilerException - { + + private void compileGeneratedSources(String verifierId, String javaSource) throws IOException, CompilerException { File generatedSources = getOutputDirectory(); File destinationDirectory = getOutputClasses(); - addDependency( "junit", "junit" ); - addDependency( "org.codehaus.plexus", "plexus-utils" ); - addDependency( "org.codehaus.modello", "modello-test" ); + addDependency("junit", "junit"); + addDependency("org.codehaus.plexus", "plexus-utils"); + addDependency("org.codehaus.modello", "modello-test"); String[] classPathElements = new String[dependencies.size() + 2]; - classPathElements[0] = getTestPath( "target/classes" ); - classPathElements[1] = getTestPath( "target/test-classes" ); + classPathElements[0] = getTestPath("target/classes"); + classPathElements[1] = getTestPath("target/test-classes"); - for ( int i = 0; i < dependencies.size(); i++ ) - { - classPathElements[i + 2] = ( (File) dependencies.get( i ) ).getAbsolutePath(); + for (int i = 0; i < dependencies.size(); i++) { + classPathElements[i + 2] = ((File) dependencies.get(i)).getAbsolutePath(); } - File verifierDirectory = getTestFile( "src/test/verifiers/" + verifierId ); + File verifierDirectory = getTestFile("src/test/verifiers/" + verifierId); String[] sourceDirectories; - if ( verifierDirectory.canRead() ) - { - sourceDirectories = new String[]{ verifierDirectory.getAbsolutePath(), generatedSources.getAbsolutePath() }; - } - else - { - sourceDirectories = new String[]{ generatedSources.getAbsolutePath() }; + if (verifierDirectory.canRead()) { + sourceDirectories = new String[] {verifierDirectory.getAbsolutePath(), generatedSources.getAbsolutePath()}; + } else { + sourceDirectories = new String[] {generatedSources.getAbsolutePath()}; } Compiler compiler; - try - { + try { compiler = lookup(Compiler.class, "javac"); - } - catch (ComponentLookupException e) - { + } catch (ComponentLookupException e) { throw new RuntimeException(e.getMessage(), e); } CompilerConfiguration configuration = new CompilerConfiguration(); - configuration.setClasspathEntries( Arrays.asList( classPathElements ) ); - configuration.setSourceLocations( Arrays.asList( sourceDirectories ) ); - configuration.setOutputLocation( destinationDirectory.getAbsolutePath() ); - configuration.setDebug( true ); - - configuration.setSourceVersion( javaSource ); - configuration.setTargetVersion( javaSource ); - - CompilerResult result = compiler.performCompile( configuration ); - - List errors = new ArrayList( 0 ); - for ( CompilerMessage compilerMessage : result.getCompilerMessages() ) - { - if ( compilerMessage.isError() ) - { - errors.add( compilerMessage ); + configuration.setClasspathEntries(Arrays.asList(classPathElements)); + configuration.setSourceLocations(Arrays.asList(sourceDirectories)); + configuration.setOutputLocation(destinationDirectory.getAbsolutePath()); + configuration.setDebug(true); + + configuration.setSourceVersion(javaSource); + configuration.setTargetVersion(javaSource); + + CompilerResult result = compiler.performCompile(configuration); + + List errors = new ArrayList(0); + for (CompilerMessage compilerMessage : result.getCompilerMessages()) { + if (compilerMessage.isError()) { + errors.add(compilerMessage); } } - assertEquals( "There was compilation errors: " + errors, 0, errors.size() ); + assertEquals("There was compilation errors: " + errors, 0, errors.size()); } /** @@ -274,77 +225,61 @@ private void compileGeneratedSources( String verifierId, String javaSource ) * * @param verifierClassName the class name of the verifier class */ - protected void verifyCompiledGeneratedSources( String verifierClassName ) - { - addClassPathFile( getOutputClasses() ); + protected void verifyCompiledGeneratedSources(String verifierClassName) { + addClassPathFile(getOutputClasses()); - addClassPathFile( getTestFile( "target/classes" ) ); + addClassPathFile(getTestFile("target/classes")); - addClassPathFile( getTestFile( "target/test-classes" ) ); + addClassPathFile(getTestFile("target/test-classes")); ClassLoader oldCCL = Thread.currentThread().getContextClassLoader(); - URLClassLoader classLoader = URLClassLoader.newInstance( urls.toArray( new URL[urls.size()] ), null ); + URLClassLoader classLoader = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]), null); - Thread.currentThread().setContextClassLoader( classLoader ); + Thread.currentThread().setContextClassLoader(classLoader); - try - { - Class clazz = classLoader.loadClass( verifierClassName ); + try { + Class clazz = classLoader.loadClass(verifierClassName); - Method verify = clazz.getMethod( "verify", new Class[0] ); + Method verify = clazz.getMethod("verify", new Class[0]); - try - { - verify.invoke( clazz.getDeclaredConstructor().newInstance(), new Object[0] ); - } - catch ( InvocationTargetException ex ) - { + try { + verify.invoke(clazz.getDeclaredConstructor().newInstance(), new Object[0]); + } catch (InvocationTargetException ex) { throw ex.getCause(); } - } - catch ( Throwable throwable ) - { - throw new VerifierException( "Error verifying modello tests: " + throwable.getMessage(), throwable ); - } - finally - { - Thread.currentThread().setContextClassLoader( oldCCL ); + } catch (Throwable throwable) { + throw new VerifierException("Error verifying modello tests: " + throwable.getMessage(), throwable); + } finally { + Thread.currentThread().setContextClassLoader(oldCCL); } } - protected void addClassPathFile( File file ) - { - assertTrue( "File doesn't exists: " + file.getAbsolutePath(), file.exists() ); + protected void addClassPathFile(File file) { + assertTrue("File doesn't exists: " + file.getAbsolutePath(), file.exists()); - try - { - urls.add( file.toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new RuntimeException( e ); + try { + urls.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); } - classPathElements.add( file.getAbsolutePath() ); + classPathElements.add(file.getAbsolutePath()); } - protected void printClasspath( URLClassLoader classLoader ) - { + protected void printClasspath(URLClassLoader classLoader) { URL[] urls = classLoader.getURLs(); - for ( URL url : urls ) - { - System.out.println( url ); + for (URL url : urls) { + System.out.println(url); } } - protected void assertGeneratedFileExists( String filename ) - { - File file = new File( getOutputDirectory(), filename ); + protected void assertGeneratedFileExists(String filename) { + File file = new File(getOutputDirectory(), filename); - assertTrue( "Missing generated file: " + file.getAbsolutePath(), file.canRead() ); + assertTrue("Missing generated file: " + file.getAbsolutePath(), file.canRead()); - assertTrue( "The generated file is empty.", file.length() > 0 ); + assertTrue("The generated file is empty.", file.length() > 0); } /** @@ -352,22 +287,19 @@ protected void assertGeneratedFileExists( String filename ) * * @return true if Java 5 is not available, then feature test should be skipped by caller */ - protected boolean skipJava5FeatureTest() - { - String javaVersion = System.getProperty( "java.specification.version", "1.5" ); + protected boolean skipJava5FeatureTest() { + String javaVersion = System.getProperty("java.specification.version", "1.5"); - if ( "1.5".compareTo( javaVersion ) > 0 ) - { + if ("1.5".compareTo(javaVersion) > 0) { System.out.println( - "Skipped Java 5 feature test, not supported by current test environment (" + javaVersion + ")" ); + "Skipped Java 5 feature test, not supported by current test environment (" + javaVersion + ")"); return true; } return false; } - protected List getClassPathElements() - { + protected List getClassPathElements() { return classPathElements; } } diff --git a/modello-test/src/main/java/org/codehaus/modello/OrderedProperties.java b/modello-test/src/main/java/org/codehaus/modello/OrderedProperties.java index 4aea5e291..f39e6b99c 100644 --- a/modello-test/src/main/java/org/codehaus/modello/OrderedProperties.java +++ b/modello-test/src/main/java/org/codehaus/modello/OrderedProperties.java @@ -32,13 +32,10 @@ * * @author Hervé Boutemy */ -public class OrderedProperties - extends Properties -{ +public class OrderedProperties extends Properties { private static final long serialVersionUID = 4578458610736378768L; - public Set keySet() - { - return new TreeSet( super.keySet() ); + public Set keySet() { + return new TreeSet(super.keySet()); } } diff --git a/modello-test/src/main/java/org/codehaus/modello/verifier/Verifier.java b/modello-test/src/main/java/org/codehaus/modello/verifier/Verifier.java index 6acb10e85..a6a9225c0 100644 --- a/modello-test/src/main/java/org/codehaus/modello/verifier/Verifier.java +++ b/modello-test/src/main/java/org/codehaus/modello/verifier/Verifier.java @@ -22,10 +22,6 @@ * SOFTWARE. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.File; import java.io.IOException; import java.io.Reader; @@ -33,91 +29,77 @@ import org.codehaus.plexus.util.ReaderFactory; -public abstract class Verifier -{ - public abstract void verify() - throws Throwable; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; - protected File getTestFile( String name ) - { - String basedir = System.getProperty( "basedir", new File( "" ).getAbsolutePath() ); +public abstract class Verifier { + public abstract void verify() throws Throwable; - return new File( basedir, name ); + protected File getTestFile(String name) { + String basedir = System.getProperty("basedir", new File("").getAbsolutePath()); + + return new File(basedir, name); } - protected String getTestPath( String name ) - { - String basedir = System.getProperty( "basedir", new File( "" ).getAbsolutePath() ); + protected String getTestPath(String name) { + String basedir = System.getProperty("basedir", new File("").getAbsolutePath()); - return new File( basedir, name ).getAbsolutePath(); + return new File(basedir, name).getAbsolutePath(); } - protected Reader getXmlResourceReader( String name ) - throws IOException - { - return ReaderFactory.newXmlReader( getClass().getResourceAsStream( name ) ); + protected Reader getXmlResourceReader(String name) throws IOException { + return ReaderFactory.newXmlReader(getClass().getResourceAsStream(name)); } - protected void assertReader( Class reader, Class model, Class input, Class exception ) - { + protected void assertReader(Class reader, Class model, Class input, Class exception) { Method read; // Model read( InputStream|Reader ) throws IOException, ? - try - { - read = reader.getMethod( "read", input ); + try { + read = reader.getMethod("read", input); - assertEquals( "Bad return type of " + read, model, read.getReturnType() ); + assertEquals("Bad return type of " + read, model, read.getReturnType()); - for ( Class e : read.getExceptionTypes() ) - { - assertTrue( "Unexpected exception " + e.getName() + " at " + read, IOException.class.equals( e ) - || exception.equals( e ) ); + for (Class e : read.getExceptionTypes()) { + assertTrue( + "Unexpected exception " + e.getName() + " at " + read, + IOException.class.equals(e) || exception.equals(e)); } - } - catch ( NoSuchMethodException e ) - { - fail( e.toString() ); + } catch (NoSuchMethodException e) { + fail(e.toString()); } // Model read( InputStream|Reader, boolean ) throws IOException, ? - try - { - read = reader.getMethod( "read", input, Boolean.TYPE ); + try { + read = reader.getMethod("read", input, Boolean.TYPE); - assertEquals( "Bad return type of " + read, model, read.getReturnType() ); + assertEquals("Bad return type of " + read, model, read.getReturnType()); - for ( Class e : read.getExceptionTypes() ) - { - assertTrue( "Unexpected exception " + e.getName() + " at " + read, IOException.class.equals( e ) - || exception.equals( e ) ); + for (Class e : read.getExceptionTypes()) { + assertTrue( + "Unexpected exception " + e.getName() + " at " + read, + IOException.class.equals(e) || exception.equals(e)); } - } - catch ( NoSuchMethodException e ) - { - fail( e.toString() ); + } catch (NoSuchMethodException e) { + fail(e.toString()); } } - protected void assertWriter( Class writer, Class model, Class output, Class exception ) - { + protected void assertWriter(Class writer, Class model, Class output, Class exception) { Method write; // write( OutputStream|Writer, Model ) throws IOException, ? - try - { - write = writer.getMethod( "write", output, model ); - - for ( Class e : write.getExceptionTypes() ) - { - assertTrue( "Unexpected exception " + e.getName() + " at " + write, IOException.class.equals( e ) - || exception.equals( e ) ); + try { + write = writer.getMethod("write", output, model); + + for (Class e : write.getExceptionTypes()) { + assertTrue( + "Unexpected exception " + e.getName() + " at " + write, + IOException.class.equals(e) || exception.equals(e)); } - } - catch ( NoSuchMethodException e ) - { - fail( e.toString() ); + } catch (NoSuchMethodException e) { + fail(e.toString()); } } - } diff --git a/modello-test/src/main/java/org/codehaus/modello/verifier/VerifierException.java b/modello-test/src/main/java/org/codehaus/modello/verifier/VerifierException.java index dec9c1a8c..ae4d6aca7 100644 --- a/modello-test/src/main/java/org/codehaus/modello/verifier/VerifierException.java +++ b/modello-test/src/main/java/org/codehaus/modello/verifier/VerifierException.java @@ -25,23 +25,18 @@ /** * @author Trygve Laugstøl */ -public class VerifierException - extends RuntimeException -{ +public class VerifierException extends RuntimeException { private static final long serialVersionUID = 104760798383307575L; - public VerifierException( String msg ) - { - super( msg ); + public VerifierException(String msg) { + super(msg); } - public VerifierException( String msg, Exception ex ) - { - super( msg, ex ); + public VerifierException(String msg, Exception ex) { + super(msg, ex); } - public VerifierException( String msg, Throwable throwable ) - { - super( msg, throwable ); + public VerifierException(String msg, Throwable throwable) { + super(msg, throwable); } } diff --git a/pom.xml b/pom.xml index 47c614301..ffa153ba8 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -13,19 +14,17 @@ pom Modello - - Modello is a framework for code generation from a simple model. + Modello is a framework for code generation from a simple model. Modello generates code from a simple model format: based on a plugin architecture, various types of code and descriptors can be generated from the single model, including Java POJOs, XML/JSON/YAML marshallers/unmarshallers, - XSD, JSON Schema and documentation. - + XSD, JSON Schema and documentation. http://codehaus-plexus.github.io/modello/ 2001 Codehaus Plexus http://codehaus-plexus.github.io/ - + The MIT License @@ -173,7 +172,7 @@ http://markmail.org/list/org.codehaus.modello.scm - + @@ -186,8 +185,8 @@ scm:git:https://github.com/codehaus-plexus/modello.git scm:git:https://github.com/codehaus-plexus/modello.git - http://github.com/codehaus-plexus/modello/tree/${project.scm.tag}/ master + http://github.com/codehaus-plexus/modello/tree/${project.scm.tag}/ github @@ -386,8 +385,8 @@ maven-checkstyle-plugin 3.2.2 - - + + true false @@ -395,7 +394,8 @@ com.puppycrawl.tools checkstyle - 9.3 + 9.3 + @@ -511,7 +511,8 @@ maven-site-plugin 3.12.1 - true + true + @@ -592,10 +593,10 @@ source-release-assembly - package single + package true @@ -662,22 +663,22 @@ xdoc - false - pre-site xdoc + pre-site + false 1.0.0 xsd - false - pre-site xsd + pre-site + false ${project.build.directory}/generated-site/resources/xsd