From 2fdc5b83a7b1127e41344f23ccdf53fa52d653c9 Mon Sep 17 00:00:00 2001 From: Sylwester Lachiewicz Date: Tue, 12 Dec 2023 04:09:00 +0100 Subject: [PATCH] Reformat code --- pom.xml | 949 +++++++------- .../codehaus/mojo/jaxb2/AbstractJaxbMojo.java | 81 +- .../mojo/jaxb2/NoSchemasException.java | 1 - .../AbstractJavaGeneratorMojo.java | 35 +- .../jaxb2/javageneration/TestXjcMojo.java | 28 +- .../mojo/jaxb2/javageneration/XjcMojo.java | 35 +- .../jaxb2/javageneration/package-info.java | 2 +- .../org/codehaus/mojo/jaxb2/package-info.java | 2 +- .../AbstractXsdGeneratorMojo.java | 149 +-- .../SchemaGenerationMojo.java | 39 +- .../TestSchemaGenerationMojo.java | 21 +- .../schemageneration/XsdGeneratorHelper.java | 1163 +++++++++-------- .../jaxb2/schemageneration/package-info.java | 2 +- .../postprocessing/NodeProcessor.java | 92 +- .../postprocessing/javadoc/DomHelper.java | 64 +- .../postprocessing/javadoc/JavaDocData.java | 12 +- .../javadoc/JavaDocExtractor.java | 105 +- .../javadoc/NoAuthorJavaDocRenderer.java | 2 +- .../javadoc/XsdAnnotationProcessor.java | 4 +- .../XsdEnumerationAnnotationProcessor.java | 42 +- .../javadoc/location/ClassLocation.java | 8 +- .../javadoc/location/FieldLocation.java | 11 +- .../javadoc/location/MethodLocation.java | 9 +- .../javadoc/location/PackageLocation.java | 3 +- .../ChangeFilenameProcessor.java | 249 ++-- .../ChangeNamespacePrefixProcessor.java | 413 +++--- .../SimpleNamespaceResolver.java | 437 +++---- .../schemaenhancement/TransformSchema.java | 403 +++--- .../jaxb2/shared/FileSystemUtilities.java | 125 +- .../mojo/jaxb2/shared/JavaVersion.java | 3 +- .../codehaus/mojo/jaxb2/shared/Validate.java | 3 +- .../shared/arguments/ArgumentBuilder.java | 13 +- .../environment/ToolExecutionEnvironment.java | 27 +- .../ContextClassLoaderEnvironmentFacet.java | 3 +- .../ThreadContextClassLoaderBuilder.java | 30 +- .../environment/locale/LocaleFacet.java | 15 +- .../LoggingHandlerEnvironmentFacet.java | 28 +- .../environment/logging/MavenLogHandler.java | 12 +- .../SystemPropertyChangeEnvironmentFacet.java | 6 +- .../SystemPropertySaveEnvironmentFacet.java | 4 +- .../jaxb2/shared/filters/AbstractFilter.java | 19 +- .../mojo/jaxb2/shared/filters/Filters.java | 6 +- .../pattern/AbstractPatternFilter.java | 45 +- .../filters/pattern/FileFilterAdapter.java | 6 +- .../filters/pattern/PatternFileFilter.java | 27 +- .../filters/pattern/PatternURLFilter.java | 11 +- .../mojo/jaxb2/shared/package-info.java | 2 +- .../jaxb2/shared/version/DependencyInfo.java | 12 +- .../shared/version/DependsFileParser.java | 27 +- .../org/codehaus/mojo/jaxb2/BufferingLog.java | 9 +- .../AbstractJavadocExtractorTest.java | 22 +- .../postprocessing/DebugNodeProcessor.java | 104 +- .../XsdGeneratorHelperTest.java | 815 ++++++------ ...ractSourceCodeAwareNodeProcessingTest.java | 59 +- .../postprocessing/javadoc/DomHelperTest.java | 25 +- .../javadoc/FieldLocationTest.java | 35 +- .../javadoc/JavaDocExtractorTest.java | 207 ++- .../javadoc/SemiDocumentedClass.java | 7 +- .../javadoc/SomewhatNamedPerson.java | 10 +- ...AnnotationProcessorSemiDocumentedTest.java | 6 +- .../javadoc/XsdAnnotationProcessorTest.java | 6 +- ...XsdEnumerationAnnotationProcessorTest.java | 8 +- .../javadoc/enums/AmericanCoin.java | 15 +- .../postprocessing/javadoc/enums/County.java | 75 +- .../javadoc/enums/ExampleEnumHolder.java | 17 +- .../javadoc/enums/FoodPreference.java | 3 +- .../javadoc/enums/Municipality.java | 887 ++++++++----- .../postprocessing/javadoc/enums/Regions.java | 10 +- .../XsdAnnotationProcessorAndEnumsTest.java | 69 +- ...xampleXmlWapperUsingJavaBeanAccessors.java | 23 +- .../javadoc/wrappers/ExampleXmlWrapper.java | 16 +- .../ChangeFilenameProcessorTest.java | 138 +- .../ChangeNamespacePrefixProcessorTest.java | 173 ++- .../SimpleNamespaceResolverTest.java | 308 ++--- .../XmlNameAnnotatedClassWithFieldAccess.java | 3 +- .../jaxb2/shared/FileSystemUtilitiesTest.java | 480 ++++--- .../shared/arguments/ArgumentBuilderTest.java | 6 +- .../ThreadContextClassLoaderBuilderTest.java | 146 +-- .../environment/locale/LocaleFacetTest.java | 13 +- ...ystemPropertySaveEnvironmentFacetTest.java | 7 +- .../jaxb2/shared/filters/FiltersTest.java | 10 +- .../filters/PackageFilterInclusionTest.java | 47 +- .../shared/filters/T_AbstractFilterTest.java | 4 +- .../pattern/AbstractPatternFilterTest.java | 15 +- .../filters/pattern/DebugPatternFilter.java | 9 +- .../pattern/PatternFileFilterTest.java | 6 +- .../filters/pattern/PatternURLFilterTest.java | 23 +- .../pattern/T_AbstractPatternFilterTest.java | 19 +- .../version/DependencyFileParserTest.java | 21 +- 89 files changed, 4414 insertions(+), 4227 deletions(-) diff --git a/pom.xml b/pom.xml index 7da5531f..eec6c2fe 100644 --- a/pom.xml +++ b/pom.xml @@ -18,504 +18,505 @@ under the License. --> - 4.0.0 + 4.0.0 - - org.codehaus.mojo - mojo-parent - 77 - + + org.codehaus.mojo + mojo-parent + 77 + - jaxb2-maven-plugin - 3.2.0-SNAPSHOT - maven-plugin + jaxb2-maven-plugin + 3.2.0-SNAPSHOT + maven-plugin - JAXB-2 Maven Plugin - Mojo's JAXB-2 Maven plugin is used to create an object graph + JAXB-2 Maven Plugin + Mojo's JAXB-2 Maven plugin is used to create an object graph from XSDs based on the JAXB 2.x implementation and to generate XSDs - from JAXB annotated Java classes. - - https://github.com/mojohaus/jaxb2-maven-plugin/ - 2005 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - Lennart Jörelid - lj@jguru.se - - Committer - - jGuru Europe AB - http://www.jguru.se - Europe/Stockholm - - - jgenender - Jeff Genender - jgenender@codehaus.org - Savoir Technologies, Inc - http://www.savoirtech.com - - Committer - - -7 - - - rfscholte - Robert Scholte - rfscholte@codehaus.org - - Committer - - Europe/Amsterdam - - - - - - Adam Retter - adam@evolvedbinary.com - Evolved Binary - https://www.evolvedbinary.com - - Patch Contributor - - Europe/London - - - - - ${mavenVersion} - - - - scm:git:https://github.com/mojohaus/jaxb2-maven-plugin.git - scm:git:ssh://git@github.com/mojohaus/jaxb2-maven-plugin.git - https://github.com/mojohaus/jaxb2-maven-plugin.git - HEAD - - - GitHub - https://github.com/mojohaus/jaxb2-maven-plugin/issues - - - TravisCI - https://travis-ci.org/mojohaus/jaxb2-maven-plugin - - - - - 3.5.4 - 8 - - - 2.14.0 - 4.0.0 - 0.0.7 - - - 3.0.2 - 2.1.0 - 2.0.3 - 9.6 - - - 2.9.1 - 3.10.2 - 0.12.0 - 2022-04-20T23:14:54Z - - - - + from JAXB annotated Java classes. + https://github.com/mojohaus/jaxb2-maven-plugin/ + 2005 + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + + Lennart Jörelid + lj@jguru.se + jGuru Europe AB + http://www.jguru.se + + Committer + + Europe/Stockholm + + + jgenender + Jeff Genender + jgenender@codehaus.org + Savoir Technologies, Inc + http://www.savoirtech.com + + Committer + + -7 + + + rfscholte + Robert Scholte + rfscholte@codehaus.org + + Committer + + Europe/Amsterdam + + + + + + Adam Retter + adam@evolvedbinary.com + Evolved Binary + https://www.evolvedbinary.com + + Patch Contributor + + Europe/London + + + + + ${mavenVersion} + + + + scm:git:https://github.com/mojohaus/jaxb2-maven-plugin.git + scm:git:ssh://git@github.com/mojohaus/jaxb2-maven-plugin.git + HEAD + https://github.com/mojohaus/jaxb2-maven-plugin.git + + + GitHub + https://github.com/mojohaus/jaxb2-maven-plugin/issues + + + TravisCI + https://travis-ci.org/mojohaus/jaxb2-maven-plugin + + + + + 3.5.4 + 8 + + + 2.14.0 + 4.0.0 + 0.0.7 + + + 3.0.2 + 2.1.0 + 2.0.3 + 9.6 + + + 2.9.1 + 3.10.2 + 0.12.0 + + 2022-04-20T23:14:54Z + + + + - - org.ow2.asm - asm - ${asm.version} - - - - com.sun.xml.bind - jaxb-xjc - ${jaxb.version} - - - com.sun.xml.bind - jaxb-jxc - ${jaxb.version} - - - - se.jguru.shared.algorithms.api - jguru-shared-algorithms-api - ${shared-algorithms.version} - - - - org.jvnet.staxex - stax-ex - ${stax-ex.version} - - - - javax.activation - activation - - - stax-api - javax.xml.stream - - - - - + + org.ow2.asm + asm + ${asm.version} + + + + com.sun.xml.bind + jaxb-xjc + ${jaxb.version} + + + com.sun.xml.bind + jaxb-jxc + ${jaxb.version} + + + + se.jguru.shared.algorithms.api + jguru-shared-algorithms-api + ${shared-algorithms.version} + + + + org.jvnet.staxex + stax-ex + ${stax-ex.version} + + + + javax.activation + activation + + + javax.xml.stream + stax-api + + + + + - - - - com.sun.xml.bind - jaxb-xjc - - - com.sun.xml.bind - jaxb-jxc - - - - - com.thoughtworks.qdox - qdox - ${qdox.version} - - - - - org.apache.maven - maven-plugin-api - ${mavenVersion} - provided - - - org.apache.maven - maven-core - ${mavenVersion} - provided - - - org.apache.maven - maven-artifact - ${mavenVersion} - provided - - - org.apache.maven - maven-model - ${mavenVersion} - provided - - - org.apache.maven.plugin-tools - maven-plugin-annotations - ${maven-plugin-plugin.version} - provided - - - + + com.thoughtworks.qdox + qdox + ${qdox.version} + + + + + org.apache.maven + maven-plugin-api + ${mavenVersion} + provided + + + org.apache.maven + maven-core + ${mavenVersion} + provided + + + org.apache.maven + maven-artifact + ${mavenVersion} + provided + + + org.apache.maven + maven-model + ${mavenVersion} + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${maven-plugin-plugin.version} + provided + + + - - org.codehaus.plexus - plexus-compiler-api - ${plexus-compiler-api.version} - - - org.codehaus.plexus - plexus-utils - ${plexus-utils.version} - - - org.sonatype.plexus - plexus-build-api - ${plexus-build-api.version} - - - - - - - junit - junit - test - - - org.xmlunit - xmlunit-matchers - ${xmlunit.version} - test - - - javax.xml.bind - jaxb-api - - - - - org.xmlunit - xmlunit-legacy - ${xmlunit.version} - test - - - se.jguru.shared.algorithms.api - jguru-shared-algorithms-api - test - - - org.eclipse.ecf - org.objectweb.asm - 5.0.1.v201404251740 - test - - - ch.qos.logback - logback-classic - 1.4.14 - test - - - com.sun.istack - istack-commons-runtime - 4.1.1 - runtime - - - - - - - - - org.apache.maven.plugins - maven-site-plugin - - true - - - - - org.apache.maven.plugins - maven-plugin-plugin - ${maven-plugin-plugin.version} - - true - - - - help-mojo - - helpmojo - - - - - - + + junit + junit + test + + + org.xmlunit + xmlunit-matchers + ${xmlunit.version} + test + + + javax.xml.bind + jaxb-api + + + + + org.xmlunit + xmlunit-legacy + ${xmlunit.version} + test + + + se.jguru.shared.algorithms.api + jguru-shared-algorithms-api + test + + + org.eclipse.ecf + org.objectweb.asm + 5.0.1.v201404251740 + test + + + ch.qos.logback + logback-classic + 1.4.14 + test + + + com.sun.istack + istack-commons-runtime + 4.1.1 + runtime + + + + + + + + + org.apache.maven.plugins + maven-site-plugin + + true + + + + + + org.apache.maven.plugins + maven-plugin-plugin + ${maven-plugin-plugin.version} + + true + + + + help-mojo + + helpmojo + + + + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + + + generate-descriptor + + descriptor + + + + + + + + org.apache.servicemix.tooling + depends-maven-plugin + 1.5.0 + + + generate-depends-file + + generate-depends-file + + + + + + + + com.github.jeluard + plantuml-maven-plugin + 7954 + + + ${basedir} + + src/site/**/*.puml + + + ${project.build.directory}/site/images/plantuml + + + + net.sourceforge.plantuml + plantuml + 8059 + + + + + generate-plantuml-diagrams + + generate + + pre-site + + + + + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + + + + + + + + run-its + + + skipTests + !true + + + - - org.apache.maven.plugins - maven-plugin-plugin - - - generate-descriptor - - descriptor - - - - - - - - org.apache.servicemix.tooling - depends-maven-plugin - 1.5.0 - - - generate-depends-file - - generate-depends-file - - - - - - - - com.github.jeluard - plantuml-maven-plugin - 7954 - - - ${basedir} - - src/site/**/*.puml - - - ${project.build.directory}/site/images/plantuml - - - - generate-plantuml-diagrams - - generate - - pre-site - - - - - net.sourceforge.plantuml - plantuml - 8059 - - - + + org.apache.maven.plugins + maven-invoker-plugin + 3.6.0 + + true + ${project.build.directory}/it + verify + ${project.build.directory}/local-repo + src/it/settings.xml + + clean + test-compile + + + + + org.xmlunit + xmlunit-matchers + ${xmlunit.version} + + + org.xmlunit + xmlunit-core + ${xmlunit.version} + + + jakarta.activation + jakarta.activation-api + 2.1.2 + + + + + integration-test + + install + run + + + + - - - + + + + + reporting + + + skipReports + !true + + + - - - org.apache.maven.plugins - maven-plugin-plugin - + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin.version} + + true + config/maven_checks.xml + config/maven-header.txt + + - - - - - - run-its - - - skipTests - !true - - - - - - org.apache.maven.plugins - maven-invoker-plugin - 3.6.0 - - true - ${project.build.directory}/it - verify - ${project.build.directory}/local-repo - src/it/settings.xml - - clean - test-compile - - - - - integration-test - - install - run - - - - - - org.xmlunit - xmlunit-matchers - ${xmlunit.version} - - - org.xmlunit - xmlunit-core - ${xmlunit.version} - - - jakarta.activation - jakarta.activation-api - 2.1.2 - - - - - - - - - reporting - - - skipReports - !true - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven-checkstyle-plugin.version} - - true - config/maven_checks.xml - config/maven-header.txt - - - - - - - java11+ - - [11,) - - - - - - com.diffplug.spotless - spotless-maven-plugin - - - - - + + + + java11+ + + [11,) + + + + + + com.diffplug.spotless + spotless-maven-plugin + + + + + diff --git a/src/main/java/org/codehaus/mojo/jaxb2/AbstractJaxbMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/AbstractJaxbMojo.java index b2ea25c5..54b01bdd 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/AbstractJaxbMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/AbstractJaxbMojo.java @@ -19,6 +19,23 @@ * under the License. */ +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; + import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecution; @@ -38,23 +55,6 @@ import org.codehaus.mojo.jaxb2.shared.version.DependsFileParser; import org.sonatype.plexus.build.incremental.BuildContext; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Pattern; - /** * Abstract Mojo which collects common infrastructure, required and needed * by all subclass Mojos in the JAXB2 maven plugin codebase. @@ -117,18 +117,17 @@ public abstract class AbstractJaxbMojo extends AbstractMojo { */ public static final List> STANDARD_EXCLUDE_FILTERS; - private static final List RELEVANT_GROUPIDS = - Arrays.asList("com.sun.xml.bind", "jakarta.xml.bind"); + private static final List RELEVANT_GROUPIDS = Arrays.asList("com.sun.xml.bind", "jakarta.xml.bind"); private static final String OWN_ARTIFACT_ID = "jaxb2-maven-plugin"; private static final String SYSTEM_FILE_ENCODING_PROPERTY = "file.encoding"; private static final String[] STANDARD_EXCLUDE_SUFFIXES = {"README.*", "\\.xml", "\\.txt"}; private static final String[] STANDARD_PRELOADED_CLASSES = { - "com.sun.tools.xjc.addon.episode.package-info", - "com.sun.tools.xjc.reader.xmlschema.bindinfo.package-info", - "org.glassfish.jaxb.core.v2.model.core.package-info", - "org.glassfish.jaxb.runtime.v2.model.runtime.package-info", - "org.glassfish.jaxb.core.v2.schemagen.episode.package-info", - "org.glassfish.jaxb.runtime.v2.schemagen.xmlschema.package-info" + "com.sun.tools.xjc.addon.episode.package-info", + "com.sun.tools.xjc.reader.xmlschema.bindinfo.package-info", + "org.glassfish.jaxb.core.v2.model.core.package-info", + "org.glassfish.jaxb.runtime.v2.model.runtime.package-info", + "org.glassfish.jaxb.core.v2.schemagen.episode.package-info", + "org.glassfish.jaxb.runtime.v2.schemagen.xmlschema.package-info" }; static { @@ -148,9 +147,7 @@ public boolean accept(final File aFileOrDir) { final String name = aFileOrDir.getName(); // Ignore hidden files and CVS directories - return name.startsWith(".") - || (aFileOrDir.isDirectory() && name.equals("CVS")); - + return name.startsWith(".") || (aFileOrDir.isDirectory() && name.equals("CVS")); } })); @@ -163,7 +160,7 @@ public boolean accept(final File aFileOrDir) { final ClassLoader cl = AbstractJaxbMojo.class.getClassLoader(); - for(String current : STANDARD_PRELOADED_CLASSES) { + for (String current : STANDARD_PRELOADED_CLASSES) { cl.loadClass(current); } @@ -452,7 +449,12 @@ protected final String[] logAndReturnToolArguments(final String[] arguments, fin argBuilder.append("\n+=================== [" + arguments.length + " " + toolName + " Arguments]\n"); argBuilder.append("|\n"); for (int i = 0; i < arguments.length; i++) { - argBuilder.append("| [").append(i).append("]: ").append(arguments[i]).append("\n"); + argBuilder + .append("| [") + .append(i) + .append("]: ") + .append(arguments[i]) + .append("\n"); } argBuilder.append("|\n"); argBuilder.append("+=================== [End " + arguments.length + " " + toolName + " Arguments]\n\n"); @@ -510,8 +512,8 @@ protected final String getEncoding(final boolean warnIfPlatformEncoding) { if (!configuredEncoding && warnIfPlatformEncoding) { getLog().warn("Using platform encoding [" + effectiveEncoding + "], i.e. build is platform dependent!"); } else if (getLog().isDebugEnabled()) { - getLog().debug("Using " + (configuredEncoding ? "explicitly configured" : "system property") - + " encoding [" + effectiveEncoding + "]"); + getLog().debug("Using " + (configuredEncoding ? "explicitly configured" : "system property") + " encoding [" + + effectiveEncoding + "]"); } // All Done. @@ -552,8 +554,8 @@ protected File getEpisodeFile(final String episodeFileName) throws MojoExecution generatedJaxbEpisodeDirectory = episodePath.toFile(); if (getLog().isInfoEnabled()) { - getLog().info("Created EpisodePath [" + episodePath.toString() + "]: " + - (generatedJaxbEpisodeDirectory.exists() && generatedJaxbEpisodeDirectory.isDirectory())); + getLog().info("Created EpisodePath [" + episodePath.toString() + "]: " + + (generatedJaxbEpisodeDirectory.exists() && generatedJaxbEpisodeDirectory.isDirectory())); } } catch (IOException e) { @@ -568,8 +570,8 @@ protected File getEpisodeFile(final String episodeFileName) throws MojoExecution File episodeFile = new File(generatedJaxbEpisodeDirectory, effectiveEpisodeFileName + ".xjb"); final AtomicInteger index = new AtomicInteger(1); while (episodeFile.exists()) { - episodeFile = new File(generatedJaxbEpisodeDirectory, - effectiveEpisodeFileName + "_" + index.getAndIncrement() + ".xjb"); + episodeFile = new File( + generatedJaxbEpisodeDirectory, effectiveEpisodeFileName + "_" + index.getAndIncrement() + ".xjb"); } // Add the (generated) outputDirectory to the Resources. @@ -638,8 +640,8 @@ private void logPluginAndJaxbDependencyInfo() { private T getInjectedObject(final T objectOrNull, final String objectName) { if (objectOrNull == null) { - getLog().error( - "Found null '" + objectName + "', implying that Maven @Component injection was not done properly."); + getLog().error("Found null '" + objectName + + "', implying that Maven @Component injection was not done properly."); } return objectOrNull; @@ -684,7 +686,8 @@ protected void logSystemPropertiesAndBasedir() { // Sort the system properties final SortedMap props = new TreeMap(); - props.put("basedir", FileSystemUtilities.getCanonicalPath(getProject().getBasedir())); + props.put( + "basedir", FileSystemUtilities.getCanonicalPath(getProject().getBasedir())); for (Map.Entry current : System.getProperties().entrySet()) { props.put("" + current.getKey(), current.getValue()); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/NoSchemasException.java b/src/main/java/org/codehaus/mojo/jaxb2/NoSchemasException.java index 77eb3ae1..c0e46c6a 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/NoSchemasException.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/NoSchemasException.java @@ -19,7 +19,6 @@ * under the License. */ - /** * @author olamy * @version $Id$ diff --git a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/AbstractJavaGeneratorMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/AbstractJavaGeneratorMojo.java index 632a6d40..e6de61f0 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/AbstractJavaGeneratorMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/AbstractJavaGeneratorMojo.java @@ -19,6 +19,16 @@ * under the License. */ +import java.io.File; +import java.io.FileWriter; +import java.net.HttpURLConnection; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import com.sun.tools.xjc.Driver; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -39,16 +49,6 @@ import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; -import java.io.File; -import java.io.FileWriter; -import java.net.HttpURLConnection; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** *

Abstract superclass for Mojos generating Java source or binaries from XML schema(s) by invoking the JAXB XJC * binding compiler. Most of the Configuration options for the AbstractJavaGeneratorMojo are set or copied to the @@ -60,7 +60,8 @@ */ public abstract class AbstractJavaGeneratorMojo extends AbstractJaxbMojo { - private static final List PROXY_PROPERTY_KEYS = Arrays.asList("http.proxyHost", "http.proxyPort", "https.proxyHost", "https.proxyPort"); + private static final List PROXY_PROPERTY_KEYS = + Arrays.asList("http.proxyHost", "http.proxyPort", "https.proxyHost", "https.proxyPort"); private static final int XJC_COMPLETED_OK = 0; @@ -423,7 +424,8 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE final LocaleFacet localeFacet = locale == null ? null : LocaleFacet.createFor(locale, getLog()); // Create the ToolExecutionEnvironment - environment = new ToolExecutionEnvironment(getLog(), + environment = new ToolExecutionEnvironment( + getLog(), ThreadContextClassLoaderBuilder.createFor(this.getClass(), getLog(), getEncoding(false)) .addPaths(getClasspath()), LoggingHandlerEnvironmentFacet.create(getLog(), getClass(), getEncoding(false)), @@ -481,7 +483,10 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE final List sourceXSDs = getSources(); for (int i = 0; i < sourceXSDs.size(); i++) { - errorMsgBuilder.append("| " + i + ": ").append(sourceXSDs.get(i).toString()).append("\n"); + errorMsgBuilder + .append("| " + i + ": ") + .append(sourceXSDs.get(i).toString()) + .append("\n"); } errorMsgBuilder.append("|\n"); @@ -523,8 +528,8 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE // jar:file:/path/to/aJar.jar!/some/path/xsd/aResource.xsd final int bangIndex = current.toString().indexOf("!"); if (bangIndex == -1) { - throw new MojoExecutionException("Illegal JAR URL [" + current.toString() - + "]: lacks a '!'"); + throw new MojoExecutionException( + "Illegal JAR URL [" + current.toString() + "]: lacks a '!'"); } final String internalPath = current.toString().substring(bangIndex + 1); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/TestXjcMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/TestXjcMojo.java index 9869deb5..f37885f7 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/TestXjcMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/TestXjcMojo.java @@ -19,6 +19,13 @@ * under the License. */ +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; @@ -32,13 +39,6 @@ import org.codehaus.mojo.jaxb2.shared.filters.Filters; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - /** *

Mojo that creates test-scope Java source or binaries from XML schema(s) * by invoking the JAXB XJC binding compiler. This implementation is tailored @@ -51,7 +51,8 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -@Mojo(name = "testXjc", +@Mojo( + name = "testXjc", defaultPhase = LifecyclePhase.GENERATE_TEST_SOURCES, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = false) @@ -112,7 +113,6 @@ public class TestXjcMojo extends AbstractJavaGeneratorMojo { public static final List> STANDARD_TEST_XJB_EXCLUDE_FILTERS; static { - final List> xjbTemp = new ArrayList>(); xjbTemp.addAll(AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS); xjbTemp.add(new PatternFileFilter(Arrays.asList("\\.xsd"), true)); @@ -261,9 +261,8 @@ protected boolean shouldExecutionBeSkipped() { @Override protected List getSources() { - final List> excludePatterns = testSourceExcludeFilters == null - ? STANDARD_TEST_SOURCE_EXCLUDE_FILTERS - : testSourceExcludeFilters; + final List> excludePatterns = + testSourceExcludeFilters == null ? STANDARD_TEST_SOURCE_EXCLUDE_FILTERS : testSourceExcludeFilters; Filters.initialize(getLog(), excludePatterns); // All done. @@ -282,9 +281,8 @@ protected List getSources() { @Override protected List getSourceXJBs() { - final List> excludePatterns = testXjbExcludeFilters == null - ? STANDARD_TEST_XJB_EXCLUDE_FILTERS - : testXjbExcludeFilters; + final List> excludePatterns = + testXjbExcludeFilters == null ? STANDARD_TEST_XJB_EXCLUDE_FILTERS : testXjbExcludeFilters; Filters.initialize(getLog(), excludePatterns); return FileSystemUtilities.filterFiles( diff --git a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/XjcMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/XjcMojo.java index 7767a8e9..a085e348 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/XjcMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/XjcMojo.java @@ -19,6 +19,13 @@ * under the License. */ +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; @@ -32,13 +39,6 @@ import org.codehaus.mojo.jaxb2.shared.filters.Filters; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - /** *

Mojo that creates compile-scope Java source or binaries from XML schema(s) * by invoking the JAXB XJC binding compiler. This implementation is tailored @@ -51,7 +51,8 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -@Mojo(name = "xjc", +@Mojo( + name = "xjc", threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE) @@ -109,7 +110,6 @@ public class XjcMojo extends AbstractJavaGeneratorMojo { public static final List> STANDARD_XJB_EXCLUDE_FILTERS; static { - final List> xjbTemp = new ArrayList>(); xjbTemp.addAll(AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS); xjbTemp.add(new PatternFileFilter(Arrays.asList("\\.xsd"), true)); @@ -273,9 +273,8 @@ protected boolean shouldExecutionBeSkipped() { @Override protected List getSources() { - final List> excludePatterns = xjcSourceExcludeFilters == null - ? STANDARD_SOURCE_EXCLUDE_FILTERS - : xjcSourceExcludeFilters; + final List> excludePatterns = + xjcSourceExcludeFilters == null ? STANDARD_SOURCE_EXCLUDE_FILTERS : xjcSourceExcludeFilters; Filters.initialize(getLog(), excludePatterns); return FileSystemUtilities.filterFiles( @@ -293,18 +292,12 @@ protected List getSources() { @Override protected List getSourceXJBs() { - final List> excludePatterns = xjbExcludeFilters == null - ? STANDARD_XJB_EXCLUDE_FILTERS - : xjbExcludeFilters; + final List> excludePatterns = + xjbExcludeFilters == null ? STANDARD_XJB_EXCLUDE_FILTERS : xjbExcludeFilters; Filters.initialize(getLog(), excludePatterns); return FileSystemUtilities.filterFiles( - getProject().getBasedir(), - xjbSources, - STANDARD_XJB_DIRECTORY, - getLog(), - "xjbSources", - excludePatterns); + getProject().getBasedir(), xjbSources, STANDARD_XJB_DIRECTORY, getLog(), "xjbSources", excludePatterns); } /** diff --git a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/package-info.java b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/package-info.java index 65b71563..e202114a 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/javageneration/package-info.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/javageneration/package-info.java @@ -7,4 +7,4 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -package org.codehaus.mojo.jaxb2.javageneration; \ No newline at end of file +package org.codehaus.mojo.jaxb2.javageneration; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/package-info.java b/src/main/java/org/codehaus/mojo/jaxb2/package-info.java index ce044b06..3410616e 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/package-info.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/package-info.java @@ -17,4 +17,4 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -package org.codehaus.mojo.jaxb2; \ No newline at end of file +package org.codehaus.mojo.jaxb2; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/AbstractXsdGeneratorMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/AbstractXsdGeneratorMojo.java index 7cd10d88..94f383f2 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/AbstractXsdGeneratorMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/AbstractXsdGeneratorMojo.java @@ -19,6 +19,23 @@ * under the License. */ +import javax.tools.ToolProvider; + +import java.io.File; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.regex.Pattern; + import com.sun.tools.jxc.SchemaGenerator; import com.thoughtworks.qdox.JavaProjectBuilder; import com.thoughtworks.qdox.model.JavaClass; @@ -46,22 +63,6 @@ import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.util.FileUtils; -import javax.tools.ToolProvider; -import java.io.File; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.regex.Pattern; - /** *

Abstract superclass for Mojos that generate XSD files from annotated Java Sources. * This Mojo delegates execution to the {@code schemagen} tool to perform the XSD file @@ -115,12 +116,10 @@ public abstract class AbstractXsdGeneratorMojo extends AbstractJaxbMojo { * * @see ToolProvider#getSystemToolClassLoader() */ - public static final List SYSTEM_TOOLS_CLASSLOADER_PACKAGES = Arrays.asList( - "com.sun.source.util", - "com.sun.source.tree"); + public static final List SYSTEM_TOOLS_CLASSLOADER_PACKAGES = + Arrays.asList("com.sun.source.util", "com.sun.source.tree"); static { - final List> schemagenTmp = new ArrayList>(); schemagenTmp.addAll(AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS); schemagenTmp.add(new PatternFileFilter(Arrays.asList("\\.java", "\\.scala", "\\.mdo"), false)); @@ -355,8 +354,8 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE } // Configure the ThreadContextClassLoaderBuilder, to enable synthesizing a correct ClassPath for the tool. - final ThreadContextClassLoaderBuilder classLoaderBuilder = ThreadContextClassLoaderBuilder - .createFor(this.getClass(), getLog(), getEncoding(false)) + final ThreadContextClassLoaderBuilder classLoaderBuilder = ThreadContextClassLoaderBuilder.createFor( + this.getClass(), getLog(), getEncoding(false)) .addPaths(getClasspath()) .addPaths(getProject().getCompileSourceRoots()); @@ -368,7 +367,8 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE classLoaderBuilder, LoggingHandlerEnvironmentFacet.create(getLog(), getClass(), getEncoding(false)), localeFacet); - final String projectBasedirPath = FileSystemUtilities.getCanonicalPath(getProject().getBasedir()); + final String projectBasedirPath = + FileSystemUtilities.getCanonicalPath(getProject().getBasedir()); // Add any extra configured EnvironmentFacets, as configured in the POM. if (extraFacets != null) { @@ -383,10 +383,8 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE // Compile the SchemaGen arguments final File episodeFile = getEpisodeFile(episodeFileName); final List sources = getSources(); - final String[] schemaGenArguments = getSchemaGenArguments( - environment.getClassPathAsArgument(), - episodeFile, - sources); + final String[] schemaGenArguments = + getSchemaGenArguments(environment.getClassPathAsArgument(), episodeFile, sources); // Ensure that the outputDirectory and workDirectory exists. // Clear them if configured to do so. @@ -409,15 +407,11 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE // Fire the SchemaGenerator final int result = SchemaGenerator.run( - schemaGenArguments, - Thread.currentThread().getContextClassLoader()); + schemaGenArguments, Thread.currentThread().getContextClassLoader()); if (SCHEMAGEN_INCORRECT_OPTIONS == result) { - printSchemaGenCommandAndThrowException(projectBasedirPath, - sources, - schemaGenArguments, - result, - null); + printSchemaGenCommandAndThrowException( + projectBasedirPath, sources, schemaGenArguments, result, null); } else if (SCHEMAGEN_JAXB_ERRORS == result) { // TODO: Collect the error message(s) which was emitted by SchemaGen. How can this be done? @@ -426,17 +420,17 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE // Copy generated XSDs and episode files from the WorkDirectory to the OutputDirectory, // but do not copy the intermediary bytecode files generated by schemagen. - final List> exclusionFilters = PatternFileFilter.createIncludeFilterList( - getLog(), "\\.class"); + final List> exclusionFilters = + PatternFileFilter.createIncludeFilterList(getLog(), "\\.class"); final List toCopy = FileSystemUtilities.resolveRecursively( - Arrays.asList(getWorkDirectory()), - exclusionFilters, getLog()); + Arrays.asList(getWorkDirectory()), exclusionFilters, getLog()); for (File current : toCopy) { // Get the path to the current file final String currentPath = FileSystemUtilities.getCanonicalPath(current.getAbsoluteFile()); - final File target = new File(getOutputDirectory(), + final File target = new File( + getOutputDirectory(), FileSystemUtilities.relativize(currentPath, getWorkDirectory(), true)); // Copy the file to the same relative structure within the output directory. @@ -482,22 +476,17 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE } } - final List files = FileSystemUtilities.resolveRecursively( - fileSources, null, getLog()); + final List files = FileSystemUtilities.resolveRecursively(fileSources, null, getLog()); // Acquire JavaDocs final JavaDocExtractor extractor = new JavaDocExtractor(getLog()).addSourceFiles(files); final SearchableDocumentation javaDocs = extractor.process(); // Modify the 'vanilla' generated XSDs by inserting the JavaDoc as annotations - final JavaDocRenderer renderer = javaDocRenderer == null - ? STANDARD_JAVADOC_RENDERER - : javaDocRenderer; - final int numProcessedFiles = XsdGeneratorHelper.insertJavaDocAsAnnotations(getLog(), - getEncoding(false), - getOutputDirectory(), - javaDocs, - renderer); + final JavaDocRenderer renderer = + javaDocRenderer == null ? STANDARD_JAVADOC_RENDERER : javaDocRenderer; + final int numProcessedFiles = XsdGeneratorHelper.insertJavaDocAsAnnotations( + getLog(), getEncoding(false), getOutputDirectory(), javaDocs, renderer); if (getLog().isDebugEnabled()) { getLog().info("XSD post-processing: " + numProcessedFiles + " files processed."); @@ -511,18 +500,12 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE } // Transform all namespace prefixes as requested. - XsdGeneratorHelper.replaceNamespacePrefixes(resolverMap, - transformSchemas, - getLog(), - getOutputDirectory(), - getEncoding(false)); + XsdGeneratorHelper.replaceNamespacePrefixes( + resolverMap, transformSchemas, getLog(), getOutputDirectory(), getEncoding(false)); // Rename all generated schema files as requested. - XsdGeneratorHelper.renameGeneratedSchemaFiles(resolverMap, - transformSchemas, - getLog(), - getOutputDirectory(), - getEncoding(false)); + XsdGeneratorHelper.renameGeneratedSchemaFiles( + resolverMap, transformSchemas, getLog(), getOutputDirectory(), getEncoding(false)); } } @@ -552,12 +535,7 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE } getLog().error(rootCauseBuilder.toString().replaceAll("[\r\n]+", "\n")); - printSchemaGenCommandAndThrowException(projectBasedirPath, - sources, - schemaGenArguments, - -1, - current); - + printSchemaGenCommandAndThrowException(projectBasedirPath, sources, schemaGenArguments, -1, current); } // Indicate that the output directory was updated. @@ -610,9 +588,7 @@ protected boolean performExecution() throws MojoExecutionException, MojoFailureE // Private helpers // - private String[] getSchemaGenArguments(final String classPath, - final File episodeFile, - final List sources) + private String[] getSchemaGenArguments(final String classPath, final File episodeFile, final List sources) throws MojoExecutionException { final ArgumentBuilder builder = new ArgumentBuilder(); @@ -640,7 +616,8 @@ private String[] getSchemaGenArguments(final String classPath, // There seems to be two ways of adding sources to the SchemaGen tool: // 1) Using java source files // Define the relative paths to source files, calculated from the System.property "user.dir" - // (i.e. *not* the Maven "basedir" property) on the form 'src/main/java/se/west/something/SomeClass.java'. + // (i.e. *not* the Maven "basedir" property) on the form + // 'src/main/java/se/west/something/SomeClass.java'. // Sample: javac -d . ../github_jaxb2_plugin/src/it/schemagen-main/src/main/java/se/west/gnat/Foo.java // // 2) Using bytecode files @@ -700,10 +677,8 @@ private List getSchemaGeneratorSourceFiles(final List sources) final File sourceCodeFile = FileSystemUtilities.getFileFor(current, encoding); // Calculate the relative path for the current source - final String relativePath = FileSystemUtilities.relativize( - FileSystemUtilities.getCanonicalPath(sourceCodeFile), - userDir, - true); + final String relativePath = + FileSystemUtilities.relativize(FileSystemUtilities.getCanonicalPath(sourceCodeFile), userDir, true); if (getLog().isDebugEnabled()) { getLog().debug("SourceCodeFile [" @@ -727,8 +702,8 @@ private List getSchemaGeneratorSourceFiles(final List sources) builder.addSource(current); final Collection packages = builder.getPackages(); if (packages.size() != 1) { - throw new MojoExecutionException("Exactly one package should be present in file [" - + sourceCodeFile.getPath() + "]"); + throw new MojoExecutionException( + "Exactly one package should be present in file [" + sourceCodeFile.getPath() + "]"); } // Make the key indicate that this is the package-info.java file. @@ -883,8 +858,7 @@ private List getSchemaGeneratorSourceFiles(final List sources) int i = 0; for (Map.Entry current : className2SourcePath.entrySet()) { - getLog().debug(" " + (++i) + "/" + size + ": [" + current.getKey() + "]: " - + current.getValue()); + getLog().debug(" " + (++i) + "/" + size + ": [" + current.getKey() + "]: " + current.getValue()); } getLog().debug("... End [ClassName-2-SourcePath Map]"); } @@ -897,15 +871,17 @@ private List getSchemaGeneratorSourceFiles(final List sources) return toReturn; } - private void printSchemaGenCommandAndThrowException(final String projectBasedirPath, - final List sources, - final String[] schemaGenArguments, - final int result, - final Throwable cause) throws MojoExecutionException { + private void printSchemaGenCommandAndThrowException( + final String projectBasedirPath, + final List sources, + final String[] schemaGenArguments, + final int result, + final Throwable cause) + throws MojoExecutionException { final StringBuilder errorMsgBuilder = new StringBuilder(); - errorMsgBuilder.append("\n+=================== [SchemaGenerator Error '" - + (result == -1 ? "" : result) + "']\n"); + errorMsgBuilder.append( + "\n+=================== [SchemaGenerator Error '" + (result == -1 ? "" : result) + "']\n"); errorMsgBuilder.append("|\n"); errorMsgBuilder.append("| SchemaGen did not complete its operation correctly.\n"); errorMsgBuilder.append("|\n"); @@ -924,7 +900,10 @@ private void printSchemaGenCommandAndThrowException(final String projectBasedirP errorMsgBuilder.append("| The following source files should be processed by schemagen:\n"); for (int i = 0; i < sources.size(); i++) { - errorMsgBuilder.append("| " + i + ": ").append(sources.get(i).toString()).append("\n"); + errorMsgBuilder + .append("| " + i + ": ") + .append(sources.get(i).toString()) + .append("\n"); } errorMsgBuilder.append("|\n"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/SchemaGenerationMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/SchemaGenerationMojo.java index 2b637dfb..bb4f9874 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/SchemaGenerationMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/SchemaGenerationMojo.java @@ -19,6 +19,13 @@ * under the License. */ +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; @@ -32,13 +39,6 @@ import org.codehaus.mojo.jaxb2.shared.filters.Filters; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - /** *

Mojo that creates XML schema(s) from compile-scope Java sources or binaries * by invoking the JAXB SchemaGenerator. This implementation is tailored to use the @@ -51,7 +51,8 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -@Mojo(name = "schemagen", +@Mojo( + name = "schemagen", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) @@ -80,7 +81,6 @@ public class SchemaGenerationMojo extends AbstractXsdGeneratorMojo { public static final List> STANDARD_SOURCE_EXCLUDE_FILTERS; static { - final List> srcTemp = new ArrayList>(); srcTemp.addAll(AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS); srcTemp.add(new PatternFileFilter(Arrays.asList("\\.xjb", "\\.xsd", "\\.properties"), true)); @@ -180,9 +180,8 @@ public class SchemaGenerationMojo extends AbstractXsdGeneratorMojo { @Override protected List getCompiledClassNames() { - List> excludeFilters = schemaSourceExcludeFilters == null - ? STANDARD_BYTECODE_EXCLUDE_FILTERS - : schemaSourceExcludeFilters; + List> excludeFilters = + schemaSourceExcludeFilters == null ? STANDARD_BYTECODE_EXCLUDE_FILTERS : schemaSourceExcludeFilters; Filters.initialize(getLog(), excludeFilters); try { @@ -204,9 +203,8 @@ protected List getCompiledClassNames() { @Override protected List getSources() { - final List> sourceExcludes = schemaSourceExcludeFilters == null - ? STANDARD_SOURCE_EXCLUDE_FILTERS - : schemaSourceExcludeFilters; + final List> sourceExcludes = + schemaSourceExcludeFilters == null ? STANDARD_SOURCE_EXCLUDE_FILTERS : schemaSourceExcludeFilters; Filters.initialize(getLog(), sourceExcludes); final List defaultSources = getProject().getCompileSourceRoots(); @@ -268,23 +266,22 @@ protected File getWorkDirectory() { @Override protected void addResource(final Resource resource) { - if(resource != null) { + if (resource != null) { final String newDirectory = resource.getDirectory(); // Is the supplied resource already added? final List currentResources = getProject().getResources(); - if(getLog().isDebugEnabled()) { + if (getLog().isDebugEnabled()) { getLog().debug("Candidate Resource Directory [" + newDirectory + "]"); - getLog().debug("Found [" + currentResources.size() + "] current Resources: " - + currentResources); + getLog().debug("Found [" + currentResources.size() + "] current Resources: " + currentResources); } for (Resource current : currentResources) { // Is the resource already added? - if(current.getDirectory() != null && current.getDirectory().equalsIgnoreCase(newDirectory)) { + if (current.getDirectory() != null && current.getDirectory().equalsIgnoreCase(newDirectory)) { getLog().debug("Resource already added [" + newDirectory + "]. Not adding again."); return; } @@ -293,7 +290,7 @@ protected void addResource(final Resource resource) { // Add the new Resource currentResources.add(resource); - if(getLog().isDebugEnabled()) { + if (getLog().isDebugEnabled()) { getLog().debug("Added resource [" + newDirectory + "] to existing resources."); } } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/TestSchemaGenerationMojo.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/TestSchemaGenerationMojo.java index 28751f20..aa2931ed 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/TestSchemaGenerationMojo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/TestSchemaGenerationMojo.java @@ -19,6 +19,13 @@ * under the License. */ +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; @@ -32,13 +39,6 @@ import org.codehaus.mojo.jaxb2.shared.filters.Filters; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - /** *

Mojo that creates XML schema(s) from test-scope Java testSources or binaries * by invoking the JAXB SchemaGenerator. This implementation is tailored to use the @@ -51,7 +51,8 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -@Mojo(name = "testSchemagen", +@Mojo( + name = "testSchemagen", defaultPhase = LifecyclePhase.GENERATE_TEST_RESOURCES, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) @@ -80,7 +81,6 @@ public class TestSchemaGenerationMojo extends AbstractXsdGeneratorMojo { public static final List> STANDARD_TEST_SOURCE_EXCLUDE_FILTERS; static { - final List> testSrcTemp = new ArrayList>(); testSrcTemp.addAll(AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS); testSrcTemp.add(new PatternFileFilter(Arrays.asList("\\.xjb", "\\.xsd", "\\.properties"), true)); @@ -274,8 +274,7 @@ protected void addResource(final Resource resource) { if (getLog().isDebugEnabled()) { getLog().debug("Candidate Test Resource Directory [" + newDirectory + "]"); - getLog().debug("Found [" + currentResources.size() + "] current Test Resources: " - + currentResources); + getLog().debug("Found [" + currentResources.size() + "] current Test Resources: " + currentResources); } for (Resource current : currentResources) { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/XsdGeneratorHelper.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/XsdGeneratorHelper.java index 22a4f192..c23f4815 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/XsdGeneratorHelper.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/XsdGeneratorHelper.java @@ -1,577 +1,586 @@ -package org.codehaus.mojo.jaxb2.schemageneration; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocRenderer; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SearchableDocumentation; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdAnnotationProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdEnumerationAnnotationProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeFilenameProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeNamespacePrefixProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.SimpleNamespaceResolver; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.TransformSchema; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.StringUtils; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileFilter; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Utility class holding algorithms used when generating XSD schema. - * - * @author Lennart Jörelid - * @since 1.4 - */ -public final class XsdGeneratorHelper { - - // Constants - private static final String MISCONFIG = "Misconfiguration detected: "; - private static TransformerFactory FACTORY; - private static final FileFilter RECURSIVE_XSD_FILTER; - - /** - * Hide the constructor for utility classes. - */ - private XsdGeneratorHelper() { - // Do nothing. - } - - static { - - // Create the static filter used for recursive generated XSD files detection. - RECURSIVE_XSD_FILTER = new FileFilter() { - @Override - public boolean accept(final File toMatch) { - - if (toMatch.exists()) { - - // Accept directories for recursive operation, and - // files with names matching the SCHEMAGEN_EMITTED_FILENAME Pattern. - return toMatch.isDirectory() - || AbstractXsdGeneratorMojo.SCHEMAGEN_EMITTED_FILENAME.matcher(toMatch.getName()).matches(); - } - - // Not a directory or XSD file. - return false; - } - }; - } - - /** - * Acquires a map relating generated schema filename to its SimpleNamespaceResolver. - * - * @param outputDirectory The output directory of the generated schema files. - * @return a map relating generated schema filename to an initialized SimpleNamespaceResolver. - * @throws MojoExecutionException if two generated schema files used the same namespace URI. - */ - public static Map getFileNameToResolverMap(final File outputDirectory) - throws MojoExecutionException { - - final Map toReturn = new TreeMap(); - - // Each generated schema file should be written to the output directory. - // Each generated schema file should have a unique targetNamespace. - File[] generatedSchemaFiles = outputDirectory.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.getName().startsWith("schema") && pathname.getName().endsWith(".xsd"); - } - }); - - for (File current : generatedSchemaFiles) { - toReturn.put(current.getName(), new SimpleNamespaceResolver(current)); - } - - return toReturn; - } - - /** - * Validates that the list of Schemas provided within the configuration all contain unique values. Should a - * MojoExecutionException be thrown, it contains informative text about the exact nature of the configuration - * problem - we should simplify for all plugin users. - * - * @param configuredTransformSchemas The List of configuration schemas provided to this mojo. - * @throws MojoExecutionException if any two configuredSchemas instances contain duplicate values for any of the - * properties uri, prefix or file. Also throws a MojoExecutionException if the uri of any Schema is null - * or empty, or if none of the 'file' and 'prefix' properties are given within any of the - * configuredSchema instances. - */ - public static void validateSchemasInPluginConfiguration(final List configuredTransformSchemas) - throws MojoExecutionException { - - final List uris = new ArrayList(); - final List prefixes = new ArrayList(); - final List fileNames = new ArrayList(); - - for (int i = 0; i < configuredTransformSchemas.size(); i++) { - final TransformSchema current = configuredTransformSchemas.get(i); - final String currentURI = current.getUri(); - final String currentPrefix = current.getToPrefix(); - final String currentFile = current.getToFile(); - - // We cannot work with a null or empty uri - if (StringUtils.isEmpty(currentURI)) { - throw new MojoExecutionException(MISCONFIG + "Null or empty property 'uri' found in " - + "plugin configuration for schema element at index [" + i + "]: " + current); - } - - // No point in having *only* a namespace. - if (StringUtils.isEmpty(currentPrefix) && StringUtils.isEmpty(currentFile)) { - throw new MojoExecutionException(MISCONFIG + "Null or empty properties 'prefix' " - + "and 'file' found within plugin configuration for schema element at index [" - + i + "]: " + current); - } - - // Validate that all given uris are unique. - if (uris.contains(currentURI)) { - throw new MojoExecutionException(getDuplicationErrorMessage("uri", currentURI, - uris.indexOf(currentURI), i)); - } - uris.add(currentURI); - - // Validate that all given prefixes are unique. - if (prefixes.contains(currentPrefix) && !(currentPrefix == null)) { - throw new MojoExecutionException(getDuplicationErrorMessage("prefix", currentPrefix, - prefixes.indexOf(currentPrefix), i)); - } - prefixes.add(currentPrefix); - - // Validate that all given files are unique. - if (fileNames.contains(currentFile)) { - throw new MojoExecutionException(getDuplicationErrorMessage("file", currentFile, - fileNames.indexOf(currentFile), i)); - } - fileNames.add(currentFile); - } - } - - /** - * Inserts XML documentation annotations into all generated XSD files found - * within the supplied outputDir. - * - * @param log A Maven Log. - * @param outputDir The outputDir, where generated XSD files are found. - * @param docs The SearchableDocumentation for the source files within the compilation unit. - * @param renderer The JavaDocRenderer used to convert JavaDoc annotations into XML documentation annotations. - * @return The number of processed XSDs. - */ - public static int insertJavaDocAsAnnotations(final Log log, - final String encoding, - final File outputDir, - final SearchableDocumentation docs, - final JavaDocRenderer renderer) { - - // Check sanity - Validate.notNull(docs, "docs"); - Validate.notNull(log, "log"); - Validate.notNull(outputDir, "outputDir"); - Validate.isTrue(outputDir.isDirectory(), "'outputDir' must be a Directory."); - Validate.notNull(renderer, "renderer"); - - int processedXSDs = 0; - final List foundFiles = new ArrayList(); - addRecursively(foundFiles, RECURSIVE_XSD_FILTER, outputDir); - - if (foundFiles.size() > 0) { - - // Create the processors. - final XsdAnnotationProcessor classProcessor = new XsdAnnotationProcessor(docs, renderer); - final XsdEnumerationAnnotationProcessor enumProcessor - = new XsdEnumerationAnnotationProcessor(docs, renderer); - - for (File current : foundFiles) { - - // Create an XSD document from the current File. - final Document generatedSchemaFileDocument = parseXmlToDocument(current); - - // Replace all namespace prefixes within the provided document. - process(generatedSchemaFileDocument.getFirstChild(), true, classProcessor); - processedXSDs++; - - // Overwrite the vanilla file. - savePrettyPrintedDocument(generatedSchemaFileDocument, current, encoding); - } - - } else { - if (log.isWarnEnabled()) { - log.warn("Found no generated 'vanilla' XSD files to process under [" - + FileSystemUtilities.getCanonicalPath(outputDir) + "]. Aborting processing."); - } - } - - // All done. - return processedXSDs; - } - - /** - * Replaces all namespaces within generated schema files, as instructed by the configured Schema instances. - * - * @param resolverMap The map relating generated schema file name to SimpleNamespaceResolver instances. - * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin. - * @param mavenLog The active Log. - * @param schemaDirectory The directory where all generated schema files reside. - * @param encoding The encoding to use when writing the file. - * @throws MojoExecutionException If the namespace replacement could not be done. - */ - public static void replaceNamespacePrefixes( - final Map resolverMap, - final List configuredTransformSchemas, - final Log mavenLog, - final File schemaDirectory, - final String encoding) throws MojoExecutionException { - - if (mavenLog.isDebugEnabled()) { - mavenLog.debug("Got resolverMap.keySet() [generated filenames]: " + resolverMap.keySet()); - } - - for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { - File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename()); - Document generatedSchemaFileDocument = null; - - for (TransformSchema currentTransformSchema : configuredTransformSchemas) { - // Should we alter the namespace prefix as instructed by the current schema? - final String newPrefix = currentTransformSchema.getToPrefix(); - final String currentUri = currentTransformSchema.getUri(); - - if (StringUtils.isNotEmpty(newPrefix)) { - // Find the old/current prefix of the namespace for the current schema uri. - final String oldPrefix = currentResolver.getNamespaceURI2PrefixMap().get(currentUri); - - if (StringUtils.isNotEmpty(oldPrefix)) { - // Can we perform the prefix substitution? - validatePrefixSubstitutionIsPossible(oldPrefix, newPrefix, currentResolver); - - if (mavenLog.isDebugEnabled()) { - mavenLog.debug("Subtituting namespace prefix [" + oldPrefix + "] with [" + newPrefix - + "] in file [" + currentResolver.getSourceFilename() + "]."); - } - - // Get the Document of the current schema file. - if (generatedSchemaFileDocument == null) { - generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile); - } - - // Replace all namespace prefixes within the provided document. - process(generatedSchemaFileDocument.getFirstChild(), true, - new ChangeNamespacePrefixProcessor(oldPrefix, newPrefix)); - } - } - } - - if (generatedSchemaFileDocument != null) { - // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument. - mavenLog.debug("Overwriting file [" + currentResolver.getSourceFilename() + "] with content [" - + getHumanReadableXml(generatedSchemaFileDocument) + "]"); - savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile, encoding); - } else { - mavenLog.debug("No namespace prefix changes to generated schema file [" - + generatedSchemaFile.getName() + "]"); - } - } - } - - /** - * Updates all schemaLocation attributes within the generated schema files to match the 'file' properties within the - * Schemas read from the plugin configuration. After that, the files are physically renamed. - * - * @param resolverMap The map relating generated schema file name to SimpleNamespaceResolver instances. - * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin. - * @param mavenLog The active Log. - * @param schemaDirectory The directory where all generated schema files reside. - * @param charsetName The encoding / charset name. - */ - public static void renameGeneratedSchemaFiles(final Map resolverMap, - final List configuredTransformSchemas, - final Log mavenLog, - final File schemaDirectory, - final String charsetName) { - - // Create the map relating namespace URI to desired filenames. - Map namespaceUriToDesiredFilenameMap = new TreeMap(); - for (TransformSchema current : configuredTransformSchemas) { - if (StringUtils.isNotEmpty(current.getToFile())) { - namespaceUriToDesiredFilenameMap.put(current.getUri(), current.getToFile()); - } - } - - // Replace the schemaLocation values to correspond to the new filenames - for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { - File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename()); - Document generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile); - - // Replace all namespace prefixes within the provided document. - process(generatedSchemaFileDocument.getFirstChild(), true, - new ChangeFilenameProcessor(namespaceUriToDesiredFilenameMap)); - - // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument. - if (mavenLog.isDebugEnabled()) { - mavenLog.debug("Changed schemaLocation entries within [" + currentResolver.getSourceFilename() + "]. " - + "Result: [" + getHumanReadableXml(generatedSchemaFileDocument) + "]"); - } - savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile, charsetName); - } - - // Now, rename the actual files. - for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { - final String localNamespaceURI = currentResolver.getLocalNamespaceURI(); - - if (StringUtils.isEmpty(localNamespaceURI)) { - mavenLog.warn("SimpleNamespaceResolver contained no localNamespaceURI; aborting rename."); - continue; - } - - final String newFilename = namespaceUriToDesiredFilenameMap.get(localNamespaceURI); - final File originalFile = new File(schemaDirectory, currentResolver.getSourceFilename()); - - if (StringUtils.isNotEmpty(newFilename)) { - File renamedFile = FileUtils.resolveFile(schemaDirectory, newFilename); - String renameResult = (originalFile.renameTo(renamedFile) ? "Success " : "Failure "); - - if (mavenLog.isDebugEnabled()) { - String suffix = "renaming [" + originalFile.getAbsolutePath() + "] to [" + renamedFile + "]"; - mavenLog.debug(renameResult + suffix); - } - } - } - } - - /** - * Drives the supplied visitor to process the provided Node and all its children, should the recurseToChildren flag - * be set to true. All attributes of the current node are processed before recursing to children (i.e. - * breadth first recursion). - * - * @param node The Node to process. - * @param recurseToChildren if true, processes all children of the supplied node recursively. - * @param visitor The NodeProcessor instance which should process the nodes. - */ - public static void process(final Node node, final boolean recurseToChildren, final NodeProcessor visitor) { - - // Process the current Node, if the NodeProcessor accepts it. - if (visitor.accept(node)) { - visitor.process(node); - } - - NamedNodeMap attributes = node.getAttributes(); - for (int i = 0; i < attributes.getLength(); i++) { - Node attribute = attributes.item(i); - - // Process the current attribute, if the NodeProcessor accepts it. - if (visitor.accept(attribute)) { - visitor.process(attribute); - } - } - - if (recurseToChildren) { - NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - - // Recurse to Element children. - if (child.getNodeType() == Node.ELEMENT_NODE) { - process(child, true, visitor); - } - } - } - } - - /** - * Parses the provided InputStream to create a dom Document. - * - * @param xmlStream An InputStream connected to an XML document. - * @return A DOM Document created from the contents of the provided stream. - */ - public static Document parseXmlStream(final Reader xmlStream) { - - // Build a DOM model of the provided xmlFileStream. - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - - try { - return factory.newDocumentBuilder().parse(new InputSource(xmlStream)); - } catch (Exception e) { - throw new IllegalArgumentException("Could not acquire DOM Document", e); - } - } - - /** - * Converts the provided DOM Node to a pretty-printed XML-formatted string. - * - * @param node The Node whose children should be converted to a String. - * @return a pretty-printed XML-formatted string. - */ - protected static String getHumanReadableXml(final Node node) { - StringWriter toReturn = new StringWriter(); - - try { - Transformer transformer = getFactory().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); - transformer.transform(new DOMSource(node), new StreamResult(toReturn)); - } catch (TransformerException e) { - throw new IllegalStateException("Could not transform node [" + node.getNodeName() + "] to XML", e); - } - - return toReturn.toString(); - } - - // - // Private helpers - // - - private static String getDuplicationErrorMessage(final String propertyName, final String propertyValue, - final int firstIndex, final int currentIndex) { - return MISCONFIG + "Duplicate '" + propertyName + "' property with value [" + propertyValue - + "] found in plugin configuration. Correct schema elements index (" + firstIndex + ") and (" - + currentIndex + "), to ensure that all '" + propertyName + "' values are unique."; - } - - /** - * Validates that the transformation from oldPrefix to newPrefix is possible, in that - * newPrefix is not already used by a schema file. This would corrupt the schema by assigning elements - * from one namespace to another. - * - * @param oldPrefix The old/current namespace prefix. - * @param newPrefix The new/future namespace prefix. - * @param currentResolver The currently active SimpleNamespaceResolver. - * @throws MojoExecutionException if any schema file currently uses newPrefix. - */ - private static void validatePrefixSubstitutionIsPossible(final String oldPrefix, final String newPrefix, - final SimpleNamespaceResolver currentResolver) - throws MojoExecutionException { - // Make certain the newPrefix does not exist already. - if (currentResolver.getNamespaceURI2PrefixMap().containsValue(newPrefix)) { - throw new MojoExecutionException(MISCONFIG + "Namespace prefix [" + newPrefix + "] is already in use." - + " Cannot replace namespace prefix [" + oldPrefix + "] with [" + newPrefix + "] in file [" - + currentResolver.getSourceFilename() + "]."); - } - } - - /** - * Creates a Document from parsing the XML within the provided xmlFile. - * - * @param xmlFile The XML file to be parsed. - * @return The Document corresponding to the xmlFile. - */ - private static Document parseXmlToDocument(final File xmlFile) { - Document result = null; - Reader reader = null; - try { - reader = new FileReader(xmlFile); - result = parseXmlStream(reader); - } catch (FileNotFoundException e) { - // This should never happen... - } finally { - IOUtil.close(reader); - } - - return result; - } - - private static void savePrettyPrintedDocument(final Document toSave, - final File targetFile, - final String charsetName) { - Writer out = null; - try { - out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), charsetName)); - out.write(getHumanReadableXml(toSave.getFirstChild())); - } catch (IOException e) { - throw new IllegalStateException("Could not write to file [" + targetFile.getAbsolutePath() + "]", e); - } finally { - IOUtil.close(out); - } - } - - private static void addRecursively(final List toPopulate, - final FileFilter fileFilter, - final File aDir) { - - // Check sanity - Validate.notNull(toPopulate, "toPopulate"); - Validate.notNull(fileFilter, "fileFilter"); - Validate.notNull(aDir, "aDir"); - - // Add all matching files. - for (File current : aDir.listFiles(fileFilter)) { - - if (current.isFile()) { - toPopulate.add(current); - } else if (current.isDirectory()) { - addRecursively(toPopulate, fileFilter, current); - } - } - } - - private static TransformerFactory getFactory() { - - if (FACTORY == null) { - - try { - FACTORY = TransformerFactory.newInstance(); - - // Harmonize XML formatting - for (String currentAttributeName : Arrays.asList("indent-number", OutputKeys.INDENT)) { - try { - FACTORY.setAttribute(currentAttributeName, 2); - } catch (IllegalArgumentException ex) { - // Ignore this. - } - } - } catch (Throwable exception) { - - // This should really not happen... but it seems to happen in some test cases. - throw new IllegalStateException("Could not acquire TransformerFactory implementation.", exception); - } - } - - // All done. - return FACTORY; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileFilter; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocRenderer; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SearchableDocumentation; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdAnnotationProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdEnumerationAnnotationProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeFilenameProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeNamespacePrefixProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.SimpleNamespaceResolver; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.TransformSchema; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.IOUtil; +import org.codehaus.plexus.util.StringUtils; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * Utility class holding algorithms used when generating XSD schema. + * + * @author Lennart Jörelid + * @since 1.4 + */ +public final class XsdGeneratorHelper { + + // Constants + private static final String MISCONFIG = "Misconfiguration detected: "; + private static TransformerFactory FACTORY; + private static final FileFilter RECURSIVE_XSD_FILTER; + + /** + * Hide the constructor for utility classes. + */ + private XsdGeneratorHelper() { + // Do nothing. + } + + static { + + // Create the static filter used for recursive generated XSD files detection. + RECURSIVE_XSD_FILTER = new FileFilter() { + @Override + public boolean accept(final File toMatch) { + + if (toMatch.exists()) { + + // Accept directories for recursive operation, and + // files with names matching the SCHEMAGEN_EMITTED_FILENAME Pattern. + return toMatch.isDirectory() + || AbstractXsdGeneratorMojo.SCHEMAGEN_EMITTED_FILENAME + .matcher(toMatch.getName()) + .matches(); + } + + // Not a directory or XSD file. + return false; + } + }; + } + + /** + * Acquires a map relating generated schema filename to its SimpleNamespaceResolver. + * + * @param outputDirectory The output directory of the generated schema files. + * @return a map relating generated schema filename to an initialized SimpleNamespaceResolver. + * @throws MojoExecutionException if two generated schema files used the same namespace URI. + */ + public static Map getFileNameToResolverMap(final File outputDirectory) + throws MojoExecutionException { + + final Map toReturn = new TreeMap(); + + // Each generated schema file should be written to the output directory. + // Each generated schema file should have a unique targetNamespace. + File[] generatedSchemaFiles = outputDirectory.listFiles(new FileFilter() { + public boolean accept(File pathname) { + return pathname.getName().startsWith("schema") + && pathname.getName().endsWith(".xsd"); + } + }); + + for (File current : generatedSchemaFiles) { + toReturn.put(current.getName(), new SimpleNamespaceResolver(current)); + } + + return toReturn; + } + + /** + * Validates that the list of Schemas provided within the configuration all contain unique values. Should a + * MojoExecutionException be thrown, it contains informative text about the exact nature of the configuration + * problem - we should simplify for all plugin users. + * + * @param configuredTransformSchemas The List of configuration schemas provided to this mojo. + * @throws MojoExecutionException if any two configuredSchemas instances contain duplicate values for any of the + * properties uri, prefix or file. Also throws a MojoExecutionException if the uri of any Schema is null + * or empty, or if none of the 'file' and 'prefix' properties are given within any of the + * configuredSchema instances. + */ + public static void validateSchemasInPluginConfiguration(final List configuredTransformSchemas) + throws MojoExecutionException { + + final List uris = new ArrayList(); + final List prefixes = new ArrayList(); + final List fileNames = new ArrayList(); + + for (int i = 0; i < configuredTransformSchemas.size(); i++) { + final TransformSchema current = configuredTransformSchemas.get(i); + final String currentURI = current.getUri(); + final String currentPrefix = current.getToPrefix(); + final String currentFile = current.getToFile(); + + // We cannot work with a null or empty uri + if (StringUtils.isEmpty(currentURI)) { + throw new MojoExecutionException(MISCONFIG + "Null or empty property 'uri' found in " + + "plugin configuration for schema element at index [" + i + "]: " + current); + } + + // No point in having *only* a namespace. + if (StringUtils.isEmpty(currentPrefix) && StringUtils.isEmpty(currentFile)) { + throw new MojoExecutionException(MISCONFIG + "Null or empty properties 'prefix' " + + "and 'file' found within plugin configuration for schema element at index [" + + i + "]: " + current); + } + + // Validate that all given uris are unique. + if (uris.contains(currentURI)) { + throw new MojoExecutionException( + getDuplicationErrorMessage("uri", currentURI, uris.indexOf(currentURI), i)); + } + uris.add(currentURI); + + // Validate that all given prefixes are unique. + if (prefixes.contains(currentPrefix) && !(currentPrefix == null)) { + throw new MojoExecutionException( + getDuplicationErrorMessage("prefix", currentPrefix, prefixes.indexOf(currentPrefix), i)); + } + prefixes.add(currentPrefix); + + // Validate that all given files are unique. + if (fileNames.contains(currentFile)) { + throw new MojoExecutionException( + getDuplicationErrorMessage("file", currentFile, fileNames.indexOf(currentFile), i)); + } + fileNames.add(currentFile); + } + } + + /** + * Inserts XML documentation annotations into all generated XSD files found + * within the supplied outputDir. + * + * @param log A Maven Log. + * @param outputDir The outputDir, where generated XSD files are found. + * @param docs The SearchableDocumentation for the source files within the compilation unit. + * @param renderer The JavaDocRenderer used to convert JavaDoc annotations into XML documentation annotations. + * @return The number of processed XSDs. + */ + public static int insertJavaDocAsAnnotations( + final Log log, + final String encoding, + final File outputDir, + final SearchableDocumentation docs, + final JavaDocRenderer renderer) { + + // Check sanity + Validate.notNull(docs, "docs"); + Validate.notNull(log, "log"); + Validate.notNull(outputDir, "outputDir"); + Validate.isTrue(outputDir.isDirectory(), "'outputDir' must be a Directory."); + Validate.notNull(renderer, "renderer"); + + int processedXSDs = 0; + final List foundFiles = new ArrayList(); + addRecursively(foundFiles, RECURSIVE_XSD_FILTER, outputDir); + + if (foundFiles.size() > 0) { + + // Create the processors. + final XsdAnnotationProcessor classProcessor = new XsdAnnotationProcessor(docs, renderer); + final XsdEnumerationAnnotationProcessor enumProcessor = + new XsdEnumerationAnnotationProcessor(docs, renderer); + + for (File current : foundFiles) { + + // Create an XSD document from the current File. + final Document generatedSchemaFileDocument = parseXmlToDocument(current); + + // Replace all namespace prefixes within the provided document. + process(generatedSchemaFileDocument.getFirstChild(), true, classProcessor); + processedXSDs++; + + // Overwrite the vanilla file. + savePrettyPrintedDocument(generatedSchemaFileDocument, current, encoding); + } + + } else { + if (log.isWarnEnabled()) { + log.warn("Found no generated 'vanilla' XSD files to process under [" + + FileSystemUtilities.getCanonicalPath(outputDir) + "]. Aborting processing."); + } + } + + // All done. + return processedXSDs; + } + + /** + * Replaces all namespaces within generated schema files, as instructed by the configured Schema instances. + * + * @param resolverMap The map relating generated schema file name to SimpleNamespaceResolver instances. + * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin. + * @param mavenLog The active Log. + * @param schemaDirectory The directory where all generated schema files reside. + * @param encoding The encoding to use when writing the file. + * @throws MojoExecutionException If the namespace replacement could not be done. + */ + public static void replaceNamespacePrefixes( + final Map resolverMap, + final List configuredTransformSchemas, + final Log mavenLog, + final File schemaDirectory, + final String encoding) + throws MojoExecutionException { + + if (mavenLog.isDebugEnabled()) { + mavenLog.debug("Got resolverMap.keySet() [generated filenames]: " + resolverMap.keySet()); + } + + for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { + File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename()); + Document generatedSchemaFileDocument = null; + + for (TransformSchema currentTransformSchema : configuredTransformSchemas) { + // Should we alter the namespace prefix as instructed by the current schema? + final String newPrefix = currentTransformSchema.getToPrefix(); + final String currentUri = currentTransformSchema.getUri(); + + if (StringUtils.isNotEmpty(newPrefix)) { + // Find the old/current prefix of the namespace for the current schema uri. + final String oldPrefix = + currentResolver.getNamespaceURI2PrefixMap().get(currentUri); + + if (StringUtils.isNotEmpty(oldPrefix)) { + // Can we perform the prefix substitution? + validatePrefixSubstitutionIsPossible(oldPrefix, newPrefix, currentResolver); + + if (mavenLog.isDebugEnabled()) { + mavenLog.debug("Subtituting namespace prefix [" + oldPrefix + "] with [" + newPrefix + + "] in file [" + currentResolver.getSourceFilename() + "]."); + } + + // Get the Document of the current schema file. + if (generatedSchemaFileDocument == null) { + generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile); + } + + // Replace all namespace prefixes within the provided document. + process( + generatedSchemaFileDocument.getFirstChild(), + true, + new ChangeNamespacePrefixProcessor(oldPrefix, newPrefix)); + } + } + } + + if (generatedSchemaFileDocument != null) { + // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument. + mavenLog.debug("Overwriting file [" + currentResolver.getSourceFilename() + "] with content [" + + getHumanReadableXml(generatedSchemaFileDocument) + "]"); + savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile, encoding); + } else { + mavenLog.debug( + "No namespace prefix changes to generated schema file [" + generatedSchemaFile.getName() + "]"); + } + } + } + + /** + * Updates all schemaLocation attributes within the generated schema files to match the 'file' properties within the + * Schemas read from the plugin configuration. After that, the files are physically renamed. + * + * @param resolverMap The map relating generated schema file name to SimpleNamespaceResolver instances. + * @param configuredTransformSchemas The Schema instances read from the configuration of this plugin. + * @param mavenLog The active Log. + * @param schemaDirectory The directory where all generated schema files reside. + * @param charsetName The encoding / charset name. + */ + public static void renameGeneratedSchemaFiles( + final Map resolverMap, + final List configuredTransformSchemas, + final Log mavenLog, + final File schemaDirectory, + final String charsetName) { + + // Create the map relating namespace URI to desired filenames. + Map namespaceUriToDesiredFilenameMap = new TreeMap(); + for (TransformSchema current : configuredTransformSchemas) { + if (StringUtils.isNotEmpty(current.getToFile())) { + namespaceUriToDesiredFilenameMap.put(current.getUri(), current.getToFile()); + } + } + + // Replace the schemaLocation values to correspond to the new filenames + for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { + File generatedSchemaFile = new File(schemaDirectory, currentResolver.getSourceFilename()); + Document generatedSchemaFileDocument = parseXmlToDocument(generatedSchemaFile); + + // Replace all namespace prefixes within the provided document. + process( + generatedSchemaFileDocument.getFirstChild(), + true, + new ChangeFilenameProcessor(namespaceUriToDesiredFilenameMap)); + + // Overwrite the generatedSchemaFile with the content of the generatedSchemaFileDocument. + if (mavenLog.isDebugEnabled()) { + mavenLog.debug("Changed schemaLocation entries within [" + currentResolver.getSourceFilename() + "]. " + + "Result: [" + getHumanReadableXml(generatedSchemaFileDocument) + "]"); + } + savePrettyPrintedDocument(generatedSchemaFileDocument, generatedSchemaFile, charsetName); + } + + // Now, rename the actual files. + for (SimpleNamespaceResolver currentResolver : resolverMap.values()) { + final String localNamespaceURI = currentResolver.getLocalNamespaceURI(); + + if (StringUtils.isEmpty(localNamespaceURI)) { + mavenLog.warn("SimpleNamespaceResolver contained no localNamespaceURI; aborting rename."); + continue; + } + + final String newFilename = namespaceUriToDesiredFilenameMap.get(localNamespaceURI); + final File originalFile = new File(schemaDirectory, currentResolver.getSourceFilename()); + + if (StringUtils.isNotEmpty(newFilename)) { + File renamedFile = FileUtils.resolveFile(schemaDirectory, newFilename); + String renameResult = (originalFile.renameTo(renamedFile) ? "Success " : "Failure "); + + if (mavenLog.isDebugEnabled()) { + String suffix = "renaming [" + originalFile.getAbsolutePath() + "] to [" + renamedFile + "]"; + mavenLog.debug(renameResult + suffix); + } + } + } + } + + /** + * Drives the supplied visitor to process the provided Node and all its children, should the recurseToChildren flag + * be set to true. All attributes of the current node are processed before recursing to children (i.e. + * breadth first recursion). + * + * @param node The Node to process. + * @param recurseToChildren if true, processes all children of the supplied node recursively. + * @param visitor The NodeProcessor instance which should process the nodes. + */ + public static void process(final Node node, final boolean recurseToChildren, final NodeProcessor visitor) { + + // Process the current Node, if the NodeProcessor accepts it. + if (visitor.accept(node)) { + visitor.process(node); + } + + NamedNodeMap attributes = node.getAttributes(); + for (int i = 0; i < attributes.getLength(); i++) { + Node attribute = attributes.item(i); + + // Process the current attribute, if the NodeProcessor accepts it. + if (visitor.accept(attribute)) { + visitor.process(attribute); + } + } + + if (recurseToChildren) { + NodeList children = node.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node child = children.item(i); + + // Recurse to Element children. + if (child.getNodeType() == Node.ELEMENT_NODE) { + process(child, true, visitor); + } + } + } + } + + /** + * Parses the provided InputStream to create a dom Document. + * + * @param xmlStream An InputStream connected to an XML document. + * @return A DOM Document created from the contents of the provided stream. + */ + public static Document parseXmlStream(final Reader xmlStream) { + + // Build a DOM model of the provided xmlFileStream. + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + + try { + return factory.newDocumentBuilder().parse(new InputSource(xmlStream)); + } catch (Exception e) { + throw new IllegalArgumentException("Could not acquire DOM Document", e); + } + } + + /** + * Converts the provided DOM Node to a pretty-printed XML-formatted string. + * + * @param node The Node whose children should be converted to a String. + * @return a pretty-printed XML-formatted string. + */ + protected static String getHumanReadableXml(final Node node) { + StringWriter toReturn = new StringWriter(); + + try { + Transformer transformer = getFactory().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); + transformer.transform(new DOMSource(node), new StreamResult(toReturn)); + } catch (TransformerException e) { + throw new IllegalStateException("Could not transform node [" + node.getNodeName() + "] to XML", e); + } + + return toReturn.toString(); + } + + // + // Private helpers + // + + private static String getDuplicationErrorMessage( + final String propertyName, final String propertyValue, final int firstIndex, final int currentIndex) { + return MISCONFIG + "Duplicate '" + propertyName + "' property with value [" + propertyValue + + "] found in plugin configuration. Correct schema elements index (" + firstIndex + ") and (" + + currentIndex + "), to ensure that all '" + propertyName + "' values are unique."; + } + + /** + * Validates that the transformation from oldPrefix to newPrefix is possible, in that + * newPrefix is not already used by a schema file. This would corrupt the schema by assigning elements + * from one namespace to another. + * + * @param oldPrefix The old/current namespace prefix. + * @param newPrefix The new/future namespace prefix. + * @param currentResolver The currently active SimpleNamespaceResolver. + * @throws MojoExecutionException if any schema file currently uses newPrefix. + */ + private static void validatePrefixSubstitutionIsPossible( + final String oldPrefix, final String newPrefix, final SimpleNamespaceResolver currentResolver) + throws MojoExecutionException { + // Make certain the newPrefix does not exist already. + if (currentResolver.getNamespaceURI2PrefixMap().containsValue(newPrefix)) { + throw new MojoExecutionException(MISCONFIG + "Namespace prefix [" + newPrefix + "] is already in use." + + " Cannot replace namespace prefix [" + oldPrefix + "] with [" + newPrefix + "] in file [" + + currentResolver.getSourceFilename() + "]."); + } + } + + /** + * Creates a Document from parsing the XML within the provided xmlFile. + * + * @param xmlFile The XML file to be parsed. + * @return The Document corresponding to the xmlFile. + */ + private static Document parseXmlToDocument(final File xmlFile) { + Document result = null; + Reader reader = null; + try { + reader = new FileReader(xmlFile); + result = parseXmlStream(reader); + } catch (FileNotFoundException e) { + // This should never happen... + } finally { + IOUtil.close(reader); + } + + return result; + } + + private static void savePrettyPrintedDocument( + final Document toSave, final File targetFile, final String charsetName) { + Writer out = null; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), charsetName)); + out.write(getHumanReadableXml(toSave.getFirstChild())); + } catch (IOException e) { + throw new IllegalStateException("Could not write to file [" + targetFile.getAbsolutePath() + "]", e); + } finally { + IOUtil.close(out); + } + } + + private static void addRecursively(final List toPopulate, final FileFilter fileFilter, final File aDir) { + + // Check sanity + Validate.notNull(toPopulate, "toPopulate"); + Validate.notNull(fileFilter, "fileFilter"); + Validate.notNull(aDir, "aDir"); + + // Add all matching files. + for (File current : aDir.listFiles(fileFilter)) { + + if (current.isFile()) { + toPopulate.add(current); + } else if (current.isDirectory()) { + addRecursively(toPopulate, fileFilter, current); + } + } + } + + private static TransformerFactory getFactory() { + + if (FACTORY == null) { + + try { + FACTORY = TransformerFactory.newInstance(); + + // Harmonize XML formatting + for (String currentAttributeName : Arrays.asList("indent-number", OutputKeys.INDENT)) { + try { + FACTORY.setAttribute(currentAttributeName, 2); + } catch (IllegalArgumentException ex) { + // Ignore this. + } + } + } catch (Throwable exception) { + + // This should really not happen... but it seems to happen in some test cases. + throw new IllegalStateException("Could not acquire TransformerFactory implementation.", exception); + } + } + + // All done. + return FACTORY; + } +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/package-info.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/package-info.java index a57677d2..b9a6ee50 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/package-info.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/package-info.java @@ -8,4 +8,4 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -package org.codehaus.mojo.jaxb2.schemageneration; \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/NodeProcessor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/NodeProcessor.java index 10cf46c0..7ce216d6 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/NodeProcessor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/NodeProcessor.java @@ -1,46 +1,46 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.w3c.dom.Node; - -/** - * Processor/visitor pattern specification for DOM Nodes. - * - * @author Lennart Jörelid - * @since 1.4 - */ -public interface NodeProcessor { - - /** - * Defines if this visitor should process the provided node. - * - * @param aNode The DOM node to process. - * @return true if the provided Node should be processed by this NodeProcessor. - */ - boolean accept(Node aNode); - - /** - * Processes the provided DOM Node. - * - * @param aNode The DOM Node to process. - */ - void process(Node aNode); -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.w3c.dom.Node; + +/** + * Processor/visitor pattern specification for DOM Nodes. + * + * @author Lennart Jörelid + * @since 1.4 + */ +public interface NodeProcessor { + + /** + * Defines if this visitor should process the provided node. + * + * @param aNode The DOM node to process. + * @return true if the provided Node should be processed by this NodeProcessor. + */ + boolean accept(Node aNode); + + /** + * Processes the provided DOM Node. + * + * @param aNode The DOM Node to process. + */ + void process(Node aNode); +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java index a0b7b6f0..8855f4b6 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java @@ -1,15 +1,7 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.MethodLocation; -import org.w3c.dom.CDATASection; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; - import javax.xml.XMLConstants; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -18,6 +10,15 @@ import java.util.Set; import java.util.SortedMap; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.MethodLocation; +import org.w3c.dom.CDATASection; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + /** * Helper class stashing commonly used algorithms to work with DOM documents. * @@ -60,8 +61,7 @@ public final class DomHelper { /* * Hide constructor for utility classes */ - private DomHelper() { - } + private DomHelper() {} /** * Retrieves the value of the {@code name} attribute of the supplied Node. @@ -137,10 +137,9 @@ public static void addXmlDocumentAnnotationTo(final Node aNode, final String for // Add the new Elements, as required. final Document doc = aNode.getOwnerDocument(); - final Element annotation = doc.createElementNS( - XMLConstants.W3C_XML_SCHEMA_NS_URI, ANNOTATION_ELEMENT_NAME); - final Element docElement = doc.createElementNS( - XMLConstants.W3C_XML_SCHEMA_NS_URI, DOCUMENTATION_ELEMENT_NAME); + final Element annotation = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, ANNOTATION_ELEMENT_NAME); + final Element docElement = + doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, DOCUMENTATION_ELEMENT_NAME); final CDATASection xsdDocumentation = doc.createCDATASection(formattedDocumentation); // Set the prefixes @@ -213,13 +212,12 @@ public static String getXPathFor(final Node aNode) { */ public static ClassLocation getClassLocation(final Node aNode, final Set classLocations) { - if (aNode != null) { // The LocalName of the supplied DOM Node should be either "complexType" or "simpleType". final String nodeLocalName = aNode.getLocalName(); - final boolean acceptableType = "complexType".equalsIgnoreCase(nodeLocalName) - || "simpleType".equalsIgnoreCase(nodeLocalName); + final boolean acceptableType = + "complexType".equalsIgnoreCase(nodeLocalName) || "simpleType".equalsIgnoreCase(nodeLocalName); if (acceptableType) { @@ -254,11 +252,12 @@ public static MethodLocation getMethodLocation(final Node aNode, final Set T getFieldOrMethodLocationIfValid( - final Node aNode, - final Node containingClassNode, - final Set locations) { + final Node aNode, final Node containingClassNode, final Set locations) { T toReturn = null; @@ -357,8 +355,10 @@ public static T getFieldOrMethodLocationIfValid( toReturn = (T) current; } } catch (Exception e) { - throw new IllegalStateException("Could not acquire FieldLocation for fieldName [" - + fieldName + "] and className [" + className + "]", e); + throw new IllegalStateException( + "Could not acquire FieldLocation for fieldName [" + fieldName + "] and className [" + + className + "]", + e); } } } @@ -417,8 +417,8 @@ public static void insertXmlDocumentationAnnotationsFor( humanReadableName = "enumeration#" + getValueAttribute(aNode); } - throw new IllegalStateException("Could not find JavaDocData for XSD node [" - + humanReadableName + "] with XPath [" + DomHelper.getXPathFor(aNode) + "]"); + throw new IllegalStateException("Could not find JavaDocData for XSD node [" + humanReadableName + + "] with XPath [" + DomHelper.getXPathFor(aNode) + "]"); } // Add the XML documentation annotation. @@ -435,8 +435,8 @@ private static Node getContainingClassOrNull(final Node aNode) { for (Node current = aNode.getParentNode(); current != null; current = current.getParentNode()) { final String localName = current.getLocalName(); - final boolean foundClassMatch = "complexType".equalsIgnoreCase(localName) - || "simpleType".equalsIgnoreCase(localName); + final boolean foundClassMatch = + "complexType".equalsIgnoreCase(localName) || "simpleType".equalsIgnoreCase(localName); if (foundClassMatch) { return current; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocData.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocData.java index bc5e296c..7a47dfe9 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocData.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocData.java @@ -19,14 +19,14 @@ * under the License. */ -import com.thoughtworks.qdox.model.DocletTag; -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; - import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; +import com.thoughtworks.qdox.model.DocletTag; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; + /** * Simplified structure containing comments and tags read from a JavaDoc comment block. * @@ -116,7 +116,11 @@ public String toString() { toReturn.append("| ").append(tag2ValueMap.size()).append(" JavaDoc tags ...\n"); for (Map.Entry current : tag2ValueMap.entrySet()) { - toReturn.append("| ").append(current.getKey()).append(": ").append(current.getValue()).append("\n"); + toReturn.append("| ") + .append(current.getKey()) + .append(": ") + .append(current.getValue()) + .append("\n"); } } toReturn.append("+=================\n\n"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractor.java index ce74ae40..4fbbe593 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractor.java @@ -19,6 +19,17 @@ * under the License. */ +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; + import com.thoughtworks.qdox.JavaProjectBuilder; import com.thoughtworks.qdox.model.JavaAnnotatedElement; import com.thoughtworks.qdox.model.JavaAnnotation; @@ -27,6 +38,11 @@ import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaPackage; import com.thoughtworks.qdox.model.JavaSource; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; +import jakarta.xml.bind.annotation.XmlEnumValue; +import jakarta.xml.bind.annotation.XmlType; import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; @@ -35,22 +51,6 @@ import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; import org.codehaus.mojo.jaxb2.shared.Validate; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; -import jakarta.xml.bind.annotation.XmlEnumValue; -import jakarta.xml.bind.annotation.XmlType; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; - /** *

The schemagen tool operates on compiled bytecode, where JavaDoc comments are not present. * However, the javadoc documentation present in java source files is required within the generated @@ -114,8 +114,8 @@ public JavaDocExtractor addSourceFiles(final List sourceCodeFiles) throws try { builder.addSource(current); } catch (IOException e) { - throw new IllegalArgumentException("Could not add file [" - + FileSystemUtilities.getCanonicalPath(current) + "]", e); + throw new IllegalArgumentException( + "Could not add file [" + FileSystemUtilities.getCanonicalPath(current) + "]", e); } } @@ -179,9 +179,8 @@ public SearchableDocumentation process() { // Add the class-level JavaDoc final String simpleClassName = currentClass.getName(); - final String classXmlName = getAnnotationAttributeValueFrom(XmlType.class, - "name", - currentClass.getAnnotations()); + final String classXmlName = + getAnnotationAttributeValueFrom(XmlType.class, "name", currentClass.getAnnotations()); final ClassLocation classLocation = new ClassLocation(packageName, simpleClassName, classXmlName); addEntry(dataHolder, classLocation, currentClass); @@ -221,9 +220,7 @@ public SearchableDocumentation process() { // ==> annotatedXmlName == "integerSet" // annotatedXmlName = getAnnotationAttributeValueFrom( - XmlElementWrapper.class, - "name", - currentFieldAnnotations); + XmlElementWrapper.class, "name", currentFieldAnnotations); if (annotatedXmlName == null || annotatedXmlName.equals(DEFAULT_VALUE)) { annotatedXmlName = currentField.getName(); @@ -232,32 +229,22 @@ public SearchableDocumentation process() { // Find the XML name if provided within an annotation. if (annotatedXmlName == null) { - annotatedXmlName = getAnnotationAttributeValueFrom( - XmlElement.class, - "name", - currentFieldAnnotations); + annotatedXmlName = + getAnnotationAttributeValueFrom(XmlElement.class, "name", currentFieldAnnotations); } if (annotatedXmlName == null) { - annotatedXmlName = getAnnotationAttributeValueFrom( - XmlAttribute.class, - "name", - currentFieldAnnotations); + annotatedXmlName = + getAnnotationAttributeValueFrom(XmlAttribute.class, "name", currentFieldAnnotations); } if (annotatedXmlName == null) { - annotatedXmlName = getAnnotationAttributeValueFrom( - XmlEnumValue.class, - "value", - currentFieldAnnotations); + annotatedXmlName = + getAnnotationAttributeValueFrom(XmlEnumValue.class, "value", currentFieldAnnotations); } // Add the field-level JavaDoc final FieldLocation fieldLocation = new FieldLocation( - packageName, - simpleClassName, - classXmlName, - currentField.getName(), - annotatedXmlName); + packageName, simpleClassName, classXmlName, currentField.getName(), annotatedXmlName); addEntry(dataHolder, fieldLocation, currentField); @@ -297,33 +284,27 @@ public SearchableDocumentation process() { // ==> annotatedXmlName == "getIntegerSet" // annotatedXmlName = getAnnotationAttributeValueFrom( - XmlElementWrapper.class, - "name", - currentMethodAnnotations); + XmlElementWrapper.class, "name", currentMethodAnnotations); if (annotatedXmlName == null || annotatedXmlName.equals(DEFAULT_VALUE)) { annotatedXmlName = currentMethod.getName(); } } - // Find the XML name if provided within an annotation. if (annotatedXmlName == null) { annotatedXmlName = getAnnotationAttributeValueFrom( - XmlElement.class, - "name", - currentMethod.getAnnotations()); + XmlElement.class, "name", currentMethod.getAnnotations()); } if (annotatedXmlName == null) { annotatedXmlName = getAnnotationAttributeValueFrom( - XmlAttribute.class, - "name", - currentMethod.getAnnotations()); + XmlAttribute.class, "name", currentMethod.getAnnotations()); } // Add the method-level JavaDoc - final MethodLocation location = new MethodLocation(packageName, + final MethodLocation location = new MethodLocation( + packageName, simpleClassName, classXmlName, currentMethod.getName(), @@ -355,9 +336,7 @@ public SearchableDocumentation process() { * @since 2.2 */ private static String getAnnotationAttributeValueFrom( - final Class annotationType, - final String attributeName, - final List annotations) { + final Class annotationType, final String attributeName, final List annotations) { // QDox uses the fully qualified class name of the annotation for comparison. // Extract it. @@ -395,8 +374,7 @@ private static String getAnnotationAttributeValueFrom( return toReturn; } - private static boolean hasAnnotation(final Class annotationType, - final List annotations) { + private static boolean hasAnnotation(final Class annotationType, final List annotations) { if (annotations != null && !annotations.isEmpty() && annotationType != null) { @@ -416,9 +394,10 @@ private static boolean hasAnnotation(final Class annotationType, // Private helpers // - private void addEntry(final SortedMap map, - final SortableLocation key, - final JavaAnnotatedElement value) { + private void addEntry( + final SortedMap map, + final SortableLocation key, + final JavaAnnotatedElement value) { // Check sanity if (map.containsKey(key)) { @@ -429,8 +408,10 @@ private void addEntry(final SortedMap map, // Is this an empty package-level documentation? if (key instanceof PackageLocation) { - final boolean emptyExisting = existing.getComment() == null || existing.getComment().isEmpty(); - final boolean emptyGiven = value.getComment() == null || value.getComment().isEmpty(); + final boolean emptyExisting = + existing.getComment() == null || existing.getComment().isEmpty(); + final boolean emptyGiven = + value.getComment() == null || value.getComment().isEmpty(); if (emptyGiven) { if (log.isDebugEnabled()) { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/NoAuthorJavaDocRenderer.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/NoAuthorJavaDocRenderer.java index c07a8a57..99b42f4a 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/NoAuthorJavaDocRenderer.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/NoAuthorJavaDocRenderer.java @@ -45,7 +45,7 @@ public class NoAuthorJavaDocRenderer extends DefaultJavaDocRenderer { protected String renderJavaDocTag(final String name, final String value, final SortableLocation location) { // Don't render the author - if(AUTHOR_KEY.equalsIgnoreCase(name)) { + if (AUTHOR_KEY.equalsIgnoreCase(name)) { return ""; } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessor.java index 3567d788..9576747a 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessor.java @@ -19,6 +19,8 @@ * under the License. */ +import java.util.SortedMap; + import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; @@ -26,8 +28,6 @@ import org.codehaus.mojo.jaxb2.shared.Validate; import org.w3c.dom.Node; -import java.util.SortedMap; - /** *

Node processor that injects XSD documentation annotations consisting of JavaDoc harvested Java source code * into ComplexTypes, Elements and Attributes. The documentation is injected as follows:

diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessor.java index f08b20f5..cb875523 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessor.java @@ -1,5 +1,7 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.util.SortedMap; + import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; @@ -8,9 +10,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; -import java.util.SortedMap; - - /** *

Node processor that injects XSD documentation annotations consisting of JavaDoc harvested Java source code * into SimpleTypes, Elements and Attributes typically produced by SchemaGen when generate XSDs for Java Enumerations. @@ -122,8 +121,7 @@ public boolean accept(final Node aNode) { if (localName != null) { final String trimmed = localName.trim(); - return trimmed.equalsIgnoreCase("enumeration") - || trimmed.equalsIgnoreCase("simpleType"); + return trimmed.equalsIgnoreCase("enumeration") || trimmed.equalsIgnoreCase("simpleType"); } /* @@ -146,23 +144,23 @@ public boolean accept(final Node aNode) { */ /* - - - - - - - - - - - - - - - - - */ + + + + + + + + + + + + + + + + + */ // All done. return false; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/ClassLocation.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/ClassLocation.java index a41b2a54..3d8b1703 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/ClassLocation.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/ClassLocation.java @@ -19,11 +19,10 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.shared.Validate; - import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; +import org.codehaus.mojo.jaxb2.shared.Validate; /** * Comparable path structure to locate a particular class within compilation unit. @@ -106,9 +105,8 @@ public int hashCode() { @Override public String toString() { - final String xmlOverriddenFrom = classXmlName != null && !className.equals(classXmlName) - ? " (from: " + className + ")" - : ""; + final String xmlOverriddenFrom = + classXmlName != null && !className.equals(classXmlName) ? " (from: " + className + ")" : ""; return super.toString() + "." + getClassName() + xmlOverriddenFrom; } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/FieldLocation.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/FieldLocation.java index f5835a17..842cd83e 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/FieldLocation.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/FieldLocation.java @@ -19,11 +19,10 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.shared.Validate; - import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; +import org.codehaus.mojo.jaxb2.shared.Validate; /** * Comparable path structure to locate a particular field within compilation unit. @@ -48,7 +47,8 @@ public class FieldLocation extends ClassLocation { * @param memberXmlName The name given as the {@link XmlElement#name()} or {@link XmlAttribute#name()} value of * an annotation placed on this Field, or {@code null} if none is provided. */ - public FieldLocation(final String packageName, + public FieldLocation( + final String packageName, final String className, final String classXmlName, final String memberName, @@ -97,9 +97,8 @@ public String getPath() { @Override public String toString() { - final String xmlOverriddenFrom = memberXmlName != null && !memberName.equals(memberXmlName) - ? " (from: " + memberName + ")" - : ""; + final String xmlOverriddenFrom = + memberXmlName != null && !memberName.equals(memberXmlName) ? " (from: " + memberName + ")" : ""; return super.toString() + "#" + getMemberName() + xmlOverriddenFrom; } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/MethodLocation.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/MethodLocation.java index f4d25356..0897c4c6 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/MethodLocation.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/MethodLocation.java @@ -19,13 +19,13 @@ * under the License. */ -import com.thoughtworks.qdox.model.JavaParameter; -import org.codehaus.mojo.jaxb2.shared.Validate; +import java.util.List; +import com.thoughtworks.qdox.model.JavaParameter; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; -import java.util.List; +import org.codehaus.mojo.jaxb2.shared.Validate; /** * Comparable path structure to locate a particular method within compilation unit. @@ -60,7 +60,8 @@ public class MethodLocation extends FieldLocation { * an annotation placed on this Field, or {@code null} if none is provided. * @param parameters The names of the types which are parameters to this method. */ - public MethodLocation(final String packageName, + public MethodLocation( + final String packageName, final String className, final String classXmlName, final String memberName, diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/PackageLocation.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/PackageLocation.java index 0fa7e393..bd58aac0 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/PackageLocation.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/location/PackageLocation.java @@ -68,8 +68,7 @@ public boolean equals(final Object obj) { } // Delegate - return obj instanceof PackageLocation - && toString().equals(obj.toString()); + return obj instanceof PackageLocation && toString().equals(obj.toString()); } /** diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessor.java index b738f0a2..27b58515 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessor.java @@ -1,124 +1,125 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import javax.xml.XMLConstants; -import java.util.Map; - -/** - *

NodeProcessor which alters the filename for generated XML schema files. - * The ChangeNamespacePrefixProcessor alters the following:

- *
- *
Schema Import Definitions
- *
<xs:import namespace="http://some/namespace" schemaLocation="schema2.xsd"/> is - * altered to - * <xs:import namespace="http://some/namespace" schemaLocation="anotherFile.xsd"/>
- *
- * - * @author Lennart Jörelid - * @since 1.4 - */ -public class ChangeFilenameProcessor implements NodeProcessor { - - // Constants - private static final String SCHEMA_LOCATION = "schemaLocation"; - private static final String IMPORT = "import"; - private static final String NAMESPACE = "namespace"; - - // Internal state - private Map namespaceUriToNewFilenameMap; - - /** - *

Creates a new ChangeFilenameProcessor using the provided map relating namespace URIs - * to desired new file names.

- * - * @param namespaceUriToNewFilenameMap A map relating namespace URIs [key] to - * new/desired schema filenames [value]. - */ - public ChangeFilenameProcessor(final Map namespaceUriToNewFilenameMap) { - - // Check sanity - Validate.notNull(namespaceUriToNewFilenameMap, "namespaceUriToNewFilenameMap"); - - // Assign internal state - this.namespaceUriToNewFilenameMap = namespaceUriToNewFilenameMap; - } - - /** - * {@inheritDoc} - */ - public boolean accept(final Node aNode) { - return aNode instanceof Attr && isSchemaLocationAttributeForKnownNamespaceUri((Attr) aNode); - } - - /** - * {@inheritDoc} - */ - public void process(final Node aNode) { - - // Only attributes are permitted here. - Attr attribute = (Attr) aNode; - - // Change the fileName. - String newFilename = namespaceUriToNewFilenameMap.get(getNamespace(attribute)); - attribute.setValue(newFilename); - } - - // - // Private helpers - // - - /** - * Discovers if the provided attribute is a schemaLocation definition, which should - * be changed by this ChangeFilenameProcessor. Such an attribute is on the form - * <xs:import namespace="http://a/registered/namespace" schemaLocation="schema1.xsd"/>. - * - * @param attribute the attribute to test. - * @return true if the provided attribute is a schemaLocation definition - * whose namespace is known to this ChangeFilenameProcessor. - */ - private boolean isSchemaLocationAttributeForKnownNamespaceUri(final Attr attribute) { - - final Element parent = attribute.getOwnerElement(); - - // - return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) - && IMPORT.equalsIgnoreCase(parent.getLocalName()) - && namespaceUriToNewFilenameMap.containsKey(getNamespace(attribute)) - && SCHEMA_LOCATION.equals(attribute.getName()); - } - - /** - * Retrieves the value of the "namespace" attribute found within the parent element of the provided attribute. - * - * @param attribute An attribute defined within the parent holding the "namespace" attribute. - * @return The value of the "namespace" attribute. - */ - private String getNamespace(final Attr attribute) { - final Element parent = attribute.getOwnerElement(); - return parent.getAttribute(NAMESPACE); - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import javax.xml.XMLConstants; + +import java.util.Map; + +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + *

NodeProcessor which alters the filename for generated XML schema files. + * The ChangeNamespacePrefixProcessor alters the following:

+ *
+ *
Schema Import Definitions
+ *
<xs:import namespace="http://some/namespace" schemaLocation="schema2.xsd"/> is + * altered to + * <xs:import namespace="http://some/namespace" schemaLocation="anotherFile.xsd"/>
+ *
+ * + * @author Lennart Jörelid + * @since 1.4 + */ +public class ChangeFilenameProcessor implements NodeProcessor { + + // Constants + private static final String SCHEMA_LOCATION = "schemaLocation"; + private static final String IMPORT = "import"; + private static final String NAMESPACE = "namespace"; + + // Internal state + private Map namespaceUriToNewFilenameMap; + + /** + *

Creates a new ChangeFilenameProcessor using the provided map relating namespace URIs + * to desired new file names.

+ * + * @param namespaceUriToNewFilenameMap A map relating namespace URIs [key] to + * new/desired schema filenames [value]. + */ + public ChangeFilenameProcessor(final Map namespaceUriToNewFilenameMap) { + + // Check sanity + Validate.notNull(namespaceUriToNewFilenameMap, "namespaceUriToNewFilenameMap"); + + // Assign internal state + this.namespaceUriToNewFilenameMap = namespaceUriToNewFilenameMap; + } + + /** + * {@inheritDoc} + */ + public boolean accept(final Node aNode) { + return aNode instanceof Attr && isSchemaLocationAttributeForKnownNamespaceUri((Attr) aNode); + } + + /** + * {@inheritDoc} + */ + public void process(final Node aNode) { + + // Only attributes are permitted here. + Attr attribute = (Attr) aNode; + + // Change the fileName. + String newFilename = namespaceUriToNewFilenameMap.get(getNamespace(attribute)); + attribute.setValue(newFilename); + } + + // + // Private helpers + // + + /** + * Discovers if the provided attribute is a schemaLocation definition, which should + * be changed by this ChangeFilenameProcessor. Such an attribute is on the form + * <xs:import namespace="http://a/registered/namespace" schemaLocation="schema1.xsd"/>. + * + * @param attribute the attribute to test. + * @return true if the provided attribute is a schemaLocation definition + * whose namespace is known to this ChangeFilenameProcessor. + */ + private boolean isSchemaLocationAttributeForKnownNamespaceUri(final Attr attribute) { + + final Element parent = attribute.getOwnerElement(); + + // + return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) + && IMPORT.equalsIgnoreCase(parent.getLocalName()) + && namespaceUriToNewFilenameMap.containsKey(getNamespace(attribute)) + && SCHEMA_LOCATION.equals(attribute.getName()); + } + + /** + * Retrieves the value of the "namespace" attribute found within the parent element of the provided attribute. + * + * @param attribute An attribute defined within the parent holding the "namespace" attribute. + * @return The value of the "namespace" attribute. + */ + private String getNamespace(final Attr attribute) { + final Element parent = attribute.getOwnerElement(); + return parent.getAttribute(NAMESPACE); + } +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessor.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessor.java index 21ae6f62..df79b161 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessor.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessor.java @@ -1,206 +1,207 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import javax.xml.XMLConstants; - -/** - *

NodeProcessor which alters the namespace prefix for all relevant Nodes within an XML - * document Node. It alters namespace prefixes in the following logical places:

- *
- *
Schema Namespace Definition
- *
xmlns:oldPrefix="http://some/namespace" is altered to xmlns:newPrefix="http://some/namespace"
- *
Elements Namespace Prefix
- *
<oldPrefix:someElement ... > is altered to <newPrefix:someElement ... >
- *
Element Reference
- *
<xs:element ref="oldPrefix:aRequiredElementInTheOldPrefixNamespace"/> is altered to - * <xs:element ref="newPrefix:aRequiredElementInTheOldPrefixNamespace"/>
- *
Type Attribute
- *
<xs:element type="oldPrefix:something"/> is altered to - * <xs:element type="newPrefix:something"/>
- *
Type Extension
- *
<xs:extension base="oldPrefix:something"/> is altered to - * <xs:extension base="newPrefix:something"/>
- *
- * - * @author Lennart Jörelid - * @since 1.4 - */ -public class ChangeNamespacePrefixProcessor implements NodeProcessor { - - // Constants - // - private static final String EXTENSION_ELEMENT_NAME = "extension"; - private static final String EXTENSION_BASE_ATTRIBUTE_NAME = "base"; - private static final String REFERENCE_ATTRIBUTE_NAME = "ref"; - private static final String TYPE_ATTRIBUTE_NAME = "type"; - private static final String SCHEMA = "schema"; - private static final String XMLNS = "xmlns:"; - - // - // private static final String ELEMENT_NAME = "element"; - - // Internal state - private String oldPrefix; - private String newPrefix; - - /** - * Creates a new ChangeNamespacePrefixProcessor providing the oldPrefix which should be replaced by the newPrefix. - * - * @param oldPrefix The old/current namespace prefix - * @param newPrefix The new/substituted namespace prefix - */ - public ChangeNamespacePrefixProcessor(final String oldPrefix, final String newPrefix) { - this.oldPrefix = oldPrefix; - this.newPrefix = newPrefix; - } - - /** - * {@inheritDoc} - */ - public boolean accept(final Node aNode) { - - if (oldPrefix.equals(aNode.getPrefix())) { - // Process any nodes on the form [oldPrefix]:something. - return true; - } - - if (aNode instanceof Attr) { - - // These cases are defined by attribute properties. - final Attr attribute = (Attr) aNode; - - if (isNamespaceDefinition(attribute) - || isElementReference(attribute) - || isTypeAttributeWithPrefix(attribute) - || isExtension(attribute)) { - return true; - } - } - - // Nopes. - return false; - } - - /** - * {@inheritDoc} - */ - public void process(final Node aNode) { - - if (aNode instanceof Attr) { - - final Attr attribute = (Attr) aNode; - final Element parentElement = attribute.getOwnerElement(); - - if (isNamespaceDefinition(attribute)) { - - // Use the incredibly smooth DOM way to rename an attribute... - parentElement.setAttributeNS(attribute.getNamespaceURI(), XMLNS + newPrefix, aNode.getNodeValue()); - parentElement.removeAttribute(XMLNS + oldPrefix); - - } else if (isElementReference(attribute) - || isTypeAttributeWithPrefix(attribute) - || isExtension(attribute)) { - - // Simply alter the value of the reference - final String value = attribute.getValue(); - final String elementName = value.substring(value.indexOf(":") + 1); - attribute.setValue(newPrefix + ":" + elementName); - } - } - - if (oldPrefix.equals(aNode.getPrefix())) { - // Simply change the prefix to the new one. - aNode.setPrefix(newPrefix); - } - } - - // - // Private helpers - // - - /** - * Discovers if the provided attribute is the oldPrefix namespace definition, i.e. if the given attribute is the - * xmlns:[oldPrefix] within the schema Element. - * - * @param attribute the attribute to test. - * @return true if the provided attribute is the oldPrefix namespace definition, i.e. if the given - * attribute is the xmlns:[oldPrefix] within the schema Element. - */ - private boolean isNamespaceDefinition(final Attr attribute) { - - final Element parent = attribute.getOwnerElement(); - - return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) - && SCHEMA.equalsIgnoreCase(parent.getLocalName()) - && oldPrefix.equals(attribute.getLocalName()); - } - - /** - * Discovers if the provided attribute is a namespace reference to the oldPrefix namespace, on the form - * <xs:element ref="oldPrefix:anElementInTheOldPrefixNamespace"/> - * - * @param attribute the attribute to test. - * @return true if the provided attribute is named "ref" and starts with [oldPrefix]:, in - * which case it is a reference to the oldPrefix namespace. - */ - private boolean isElementReference(final Attr attribute) { - return REFERENCE_ATTRIBUTE_NAME.equals(attribute.getName()) - && attribute.getValue().startsWith(oldPrefix + ":"); - } - - /** - * Discovers if the provided attribute is a type attribute using the oldPrefix namespace, on the form - * <xs:element type="oldPrefix:anElementInTheOldPrefixNamespace"/> - * - * @param attribute the attribute to test. - * @return true if the provided attribute is named "type" and starts with [oldPrefix]:, in - * which case it is a type in the oldPrefix namespace. - */ - private boolean isTypeAttributeWithPrefix(final Attr attribute) { - return TYPE_ATTRIBUTE_NAME.equals(attribute.getName()) && attribute.getValue().startsWith(oldPrefix + ":"); - } - - /** - * Discovers if the provided attribute is a namespace reference to the oldPrefix namespace, on the form - *

- *

-     *     <xs:extension base="[oldPrefix]:importItem">
-     * 
- * - * @param attribute the attribute to test. - * @return true if the provided attribute is named "extension" and starts with - * [oldPrefix]:, in which case it is a reference to the oldPrefix namespace. - */ - private boolean isExtension(final Attr attribute) { - - final Element parent = attribute.getOwnerElement(); - - return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) - && EXTENSION_ELEMENT_NAME.equalsIgnoreCase(parent.getLocalName()) - && EXTENSION_BASE_ATTRIBUTE_NAME.equalsIgnoreCase(attribute.getName()) - && attribute.getValue().startsWith(oldPrefix + ":"); - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import javax.xml.XMLConstants; + +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + *

NodeProcessor which alters the namespace prefix for all relevant Nodes within an XML + * document Node. It alters namespace prefixes in the following logical places:

+ *
+ *
Schema Namespace Definition
+ *
xmlns:oldPrefix="http://some/namespace" is altered to xmlns:newPrefix="http://some/namespace"
+ *
Elements Namespace Prefix
+ *
<oldPrefix:someElement ... > is altered to <newPrefix:someElement ... >
+ *
Element Reference
+ *
<xs:element ref="oldPrefix:aRequiredElementInTheOldPrefixNamespace"/> is altered to + * <xs:element ref="newPrefix:aRequiredElementInTheOldPrefixNamespace"/>
+ *
Type Attribute
+ *
<xs:element type="oldPrefix:something"/> is altered to + * <xs:element type="newPrefix:something"/>
+ *
Type Extension
+ *
<xs:extension base="oldPrefix:something"/> is altered to + * <xs:extension base="newPrefix:something"/>
+ *
+ * + * @author Lennart Jörelid + * @since 1.4 + */ +public class ChangeNamespacePrefixProcessor implements NodeProcessor { + + // Constants + // + private static final String EXTENSION_ELEMENT_NAME = "extension"; + private static final String EXTENSION_BASE_ATTRIBUTE_NAME = "base"; + private static final String REFERENCE_ATTRIBUTE_NAME = "ref"; + private static final String TYPE_ATTRIBUTE_NAME = "type"; + private static final String SCHEMA = "schema"; + private static final String XMLNS = "xmlns:"; + + // + // private static final String ELEMENT_NAME = "element"; + + // Internal state + private String oldPrefix; + private String newPrefix; + + /** + * Creates a new ChangeNamespacePrefixProcessor providing the oldPrefix which should be replaced by the newPrefix. + * + * @param oldPrefix The old/current namespace prefix + * @param newPrefix The new/substituted namespace prefix + */ + public ChangeNamespacePrefixProcessor(final String oldPrefix, final String newPrefix) { + this.oldPrefix = oldPrefix; + this.newPrefix = newPrefix; + } + + /** + * {@inheritDoc} + */ + public boolean accept(final Node aNode) { + + if (oldPrefix.equals(aNode.getPrefix())) { + // Process any nodes on the form [oldPrefix]:something. + return true; + } + + if (aNode instanceof Attr) { + + // These cases are defined by attribute properties. + final Attr attribute = (Attr) aNode; + + if (isNamespaceDefinition(attribute) + || isElementReference(attribute) + || isTypeAttributeWithPrefix(attribute) + || isExtension(attribute)) { + return true; + } + } + + // Nopes. + return false; + } + + /** + * {@inheritDoc} + */ + public void process(final Node aNode) { + + if (aNode instanceof Attr) { + + final Attr attribute = (Attr) aNode; + final Element parentElement = attribute.getOwnerElement(); + + if (isNamespaceDefinition(attribute)) { + + // Use the incredibly smooth DOM way to rename an attribute... + parentElement.setAttributeNS(attribute.getNamespaceURI(), XMLNS + newPrefix, aNode.getNodeValue()); + parentElement.removeAttribute(XMLNS + oldPrefix); + + } else if (isElementReference(attribute) + || isTypeAttributeWithPrefix(attribute) + || isExtension(attribute)) { + + // Simply alter the value of the reference + final String value = attribute.getValue(); + final String elementName = value.substring(value.indexOf(":") + 1); + attribute.setValue(newPrefix + ":" + elementName); + } + } + + if (oldPrefix.equals(aNode.getPrefix())) { + // Simply change the prefix to the new one. + aNode.setPrefix(newPrefix); + } + } + + // + // Private helpers + // + + /** + * Discovers if the provided attribute is the oldPrefix namespace definition, i.e. if the given attribute is the + * xmlns:[oldPrefix] within the schema Element. + * + * @param attribute the attribute to test. + * @return true if the provided attribute is the oldPrefix namespace definition, i.e. if the given + * attribute is the xmlns:[oldPrefix] within the schema Element. + */ + private boolean isNamespaceDefinition(final Attr attribute) { + + final Element parent = attribute.getOwnerElement(); + + return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) + && SCHEMA.equalsIgnoreCase(parent.getLocalName()) + && oldPrefix.equals(attribute.getLocalName()); + } + + /** + * Discovers if the provided attribute is a namespace reference to the oldPrefix namespace, on the form + * <xs:element ref="oldPrefix:anElementInTheOldPrefixNamespace"/> + * + * @param attribute the attribute to test. + * @return true if the provided attribute is named "ref" and starts with [oldPrefix]:, in + * which case it is a reference to the oldPrefix namespace. + */ + private boolean isElementReference(final Attr attribute) { + return REFERENCE_ATTRIBUTE_NAME.equals(attribute.getName()) + && attribute.getValue().startsWith(oldPrefix + ":"); + } + + /** + * Discovers if the provided attribute is a type attribute using the oldPrefix namespace, on the form + * <xs:element type="oldPrefix:anElementInTheOldPrefixNamespace"/> + * + * @param attribute the attribute to test. + * @return true if the provided attribute is named "type" and starts with [oldPrefix]:, in + * which case it is a type in the oldPrefix namespace. + */ + private boolean isTypeAttributeWithPrefix(final Attr attribute) { + return TYPE_ATTRIBUTE_NAME.equals(attribute.getName()) + && attribute.getValue().startsWith(oldPrefix + ":"); + } + + /** + * Discovers if the provided attribute is a namespace reference to the oldPrefix namespace, on the form + *

+ *

+     *     <xs:extension base="[oldPrefix]:importItem">
+     * 
+ * + * @param attribute the attribute to test. + * @return true if the provided attribute is named "extension" and starts with + * [oldPrefix]:, in which case it is a reference to the oldPrefix namespace. + */ + private boolean isExtension(final Attr attribute) { + + final Element parent = attribute.getOwnerElement(); + + return XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) + && EXTENSION_ELEMENT_NAME.equalsIgnoreCase(parent.getLocalName()) + && EXTENSION_BASE_ATTRIBUTE_NAME.equalsIgnoreCase(attribute.getName()) + && attribute.getValue().startsWith(oldPrefix + ":"); + } +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolver.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolver.java index 0e096e9b..4f99bf36 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolver.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolver.java @@ -1,220 +1,217 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; -import org.codehaus.plexus.util.IOUtil; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import javax.xml.XMLConstants; -import javax.xml.namespace.NamespaceContext; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.Reader; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - *

Namespace resolver for XML documents, which relates XML Namespace Prefixes to XML Namespace URIs. - * Doubles as a JAXB NamespaceContext, if we decide to use JAXB instead of DOM to parse our generated - * schema files.

- * - * @author Lennart Jörelid - * @since 1.4 - */ -public class SimpleNamespaceResolver implements NamespaceContext { - - // Constants - private static final String DEFAULT_NS = "DEFAULT"; - private static final String TARGET_NAMESPACE = "targetNamespace"; - private static final String SCHEMA = "schema"; - - // Internal state - private String sourceFilename; - private String localNamespaceURI; - private Map prefix2Uri = new HashMap(); - private Map uri2Prefix = new HashMap(); - - /** - * Creates a new SimpleNamespaceResolver which collects namespace data - * from the provided XML file. - * - * @param xmlFile The XML file from which to collect namespace data, should not be null. - */ - public SimpleNamespaceResolver(final File xmlFile) { - this.sourceFilename = xmlFile.getName(); - - Reader reader = null; - try { - reader = new FileReader(xmlFile); - initialize(reader); - } catch (FileNotFoundException e) { - throw new IllegalArgumentException("File [" + xmlFile + "] could not be found."); - } finally { - IOUtil.close(reader); - } - } - - /** - * {@inheritDoc} - */ - public String getNamespaceURI(final String prefix) { - if (prefix == null) { - // Be compliant with the JAXB contract for NamespaceResolver. - throw new IllegalArgumentException("Cannot handle null prefix argument."); - } - - return prefix2Uri.get(XMLConstants.DEFAULT_NS_PREFIX.equals(prefix) ? DEFAULT_NS : prefix); - } - - /** - * {@inheritDoc} - */ - public String getPrefix(final String namespaceURI) { - if (namespaceURI == null) { - // Be compliant with the JAXB contract for NamespaceResolver. - throw new IllegalArgumentException("Cannot acquire prefix for null namespaceURI."); - } - - return uri2Prefix.get(namespaceURI); - } - - /** - * {@inheritDoc} - */ - public Iterator getPrefixes(final String namespaceURI) { - if (namespaceURI == null) { - // Be compliant with the JAXB contract for NamespaceResolver. - throw new IllegalArgumentException("Cannot acquire prefixes for null namespaceURI."); - } - - return Collections.singletonList(uri2Prefix.get(namespaceURI)).iterator(); - } - - /** - * @return A readonly map relating namespace URIs to namespace prefixes. - */ - public Map getNamespaceURI2PrefixMap() { - return Collections.unmodifiableMap(uri2Prefix); - } - - /** - * @return The namespace URI of the default namespace within the sourceFile of this SimpleNamespaceResolver. - */ - public String getLocalNamespaceURI() { - return localNamespaceURI; - } - - /** - * @return The name of the source file used for this SimpleNamespaceResolver. - */ - public String getSourceFilename() { - return sourceFilename; - } - - // - // Private helpers - // - - /** - * Initializes this SimpleNamespaceResolver to collect namespace data from the provided stream. - * - * @param xmlFileStream A Reader connected to the XML file from which we should read namespace data. - */ - private void initialize(final Reader xmlFileStream) { - - // Build a DOM model. - final Document parsedDocument = XsdGeneratorHelper.parseXmlStream(xmlFileStream); - - // Process the DOM model. - XsdGeneratorHelper.process(parsedDocument.getFirstChild(), true, new NamespaceAttributeNodeProcessor()); - } - - private class NamespaceAttributeNodeProcessor - implements NodeProcessor { - /** - * Defines if this visitor should process the provided node. - * - * @param aNode The DOM node to process. - * @return true if the provided Node should be processed by this NodeProcessor. - */ - public boolean accept(final Node aNode) { - - // Correct namespace? - if (aNode.getNamespaceURI() != null - && XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(aNode.getNamespaceURI())) { - return true; - } - - // Is this Node the targetNamespace attribute? - if (aNode instanceof Attr) { - - final Attr attribute = (Attr) aNode; - final Element parent = attribute.getOwnerElement(); - if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) - && SCHEMA.equalsIgnoreCase(parent.getLocalName()) - && TARGET_NAMESPACE.equals(attribute.getLocalName())) { - - SimpleNamespaceResolver.this.localNamespaceURI = attribute.getNodeValue(); - } - } - - // Ignore processing this Node. - return false; - } - - /** - * Processes the provided DOM Node. - * - * @param aNode The DOM Node to process. - */ - public void process(final Node aNode) { - - // If we have no namespace, use the DEFAULT_NS as the prefix - final String cacheKey = XMLConstants.XMLNS_ATTRIBUTE.equals(aNode.getNodeName()) - ? DEFAULT_NS - : aNode.getLocalName(); - final String nodeValue = aNode.getNodeValue(); - - // Cache the namespace in both caches. - final String oldUriValue = prefix2Uri.put(cacheKey, nodeValue); - final String oldPrefixValue = uri2Prefix.put(nodeValue, cacheKey); - - // Check sanity; we should not be overwriting values here. - if (oldUriValue != null) { - throw new IllegalStateException( - "Replaced URI [" + oldUriValue + "] with [" + aNode.getNodeValue() + "] for prefix [" + cacheKey - + "]"); - } - if (oldPrefixValue != null) { - throw new IllegalStateException( - "Replaced prefix [" + oldPrefixValue + "] with [" + cacheKey + "] for URI [" + aNode.getNodeValue() - + "]"); - } - } - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.Reader; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; +import org.codehaus.plexus.util.IOUtil; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + *

Namespace resolver for XML documents, which relates XML Namespace Prefixes to XML Namespace URIs. + * Doubles as a JAXB NamespaceContext, if we decide to use JAXB instead of DOM to parse our generated + * schema files.

+ * + * @author Lennart Jörelid + * @since 1.4 + */ +public class SimpleNamespaceResolver implements NamespaceContext { + + // Constants + private static final String DEFAULT_NS = "DEFAULT"; + private static final String TARGET_NAMESPACE = "targetNamespace"; + private static final String SCHEMA = "schema"; + + // Internal state + private String sourceFilename; + private String localNamespaceURI; + private Map prefix2Uri = new HashMap(); + private Map uri2Prefix = new HashMap(); + + /** + * Creates a new SimpleNamespaceResolver which collects namespace data + * from the provided XML file. + * + * @param xmlFile The XML file from which to collect namespace data, should not be null. + */ + public SimpleNamespaceResolver(final File xmlFile) { + this.sourceFilename = xmlFile.getName(); + + Reader reader = null; + try { + reader = new FileReader(xmlFile); + initialize(reader); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException("File [" + xmlFile + "] could not be found."); + } finally { + IOUtil.close(reader); + } + } + + /** + * {@inheritDoc} + */ + public String getNamespaceURI(final String prefix) { + if (prefix == null) { + // Be compliant with the JAXB contract for NamespaceResolver. + throw new IllegalArgumentException("Cannot handle null prefix argument."); + } + + return prefix2Uri.get(XMLConstants.DEFAULT_NS_PREFIX.equals(prefix) ? DEFAULT_NS : prefix); + } + + /** + * {@inheritDoc} + */ + public String getPrefix(final String namespaceURI) { + if (namespaceURI == null) { + // Be compliant with the JAXB contract for NamespaceResolver. + throw new IllegalArgumentException("Cannot acquire prefix for null namespaceURI."); + } + + return uri2Prefix.get(namespaceURI); + } + + /** + * {@inheritDoc} + */ + public Iterator getPrefixes(final String namespaceURI) { + if (namespaceURI == null) { + // Be compliant with the JAXB contract for NamespaceResolver. + throw new IllegalArgumentException("Cannot acquire prefixes for null namespaceURI."); + } + + return Collections.singletonList(uri2Prefix.get(namespaceURI)).iterator(); + } + + /** + * @return A readonly map relating namespace URIs to namespace prefixes. + */ + public Map getNamespaceURI2PrefixMap() { + return Collections.unmodifiableMap(uri2Prefix); + } + + /** + * @return The namespace URI of the default namespace within the sourceFile of this SimpleNamespaceResolver. + */ + public String getLocalNamespaceURI() { + return localNamespaceURI; + } + + /** + * @return The name of the source file used for this SimpleNamespaceResolver. + */ + public String getSourceFilename() { + return sourceFilename; + } + + // + // Private helpers + // + + /** + * Initializes this SimpleNamespaceResolver to collect namespace data from the provided stream. + * + * @param xmlFileStream A Reader connected to the XML file from which we should read namespace data. + */ + private void initialize(final Reader xmlFileStream) { + + // Build a DOM model. + final Document parsedDocument = XsdGeneratorHelper.parseXmlStream(xmlFileStream); + + // Process the DOM model. + XsdGeneratorHelper.process(parsedDocument.getFirstChild(), true, new NamespaceAttributeNodeProcessor()); + } + + private class NamespaceAttributeNodeProcessor implements NodeProcessor { + /** + * Defines if this visitor should process the provided node. + * + * @param aNode The DOM node to process. + * @return true if the provided Node should be processed by this NodeProcessor. + */ + public boolean accept(final Node aNode) { + + // Correct namespace? + if (aNode.getNamespaceURI() != null + && XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(aNode.getNamespaceURI())) { + return true; + } + + // Is this Node the targetNamespace attribute? + if (aNode instanceof Attr) { + + final Attr attribute = (Attr) aNode; + final Element parent = attribute.getOwnerElement(); + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(parent.getNamespaceURI()) + && SCHEMA.equalsIgnoreCase(parent.getLocalName()) + && TARGET_NAMESPACE.equals(attribute.getLocalName())) { + + SimpleNamespaceResolver.this.localNamespaceURI = attribute.getNodeValue(); + } + } + + // Ignore processing this Node. + return false; + } + + /** + * Processes the provided DOM Node. + * + * @param aNode The DOM Node to process. + */ + public void process(final Node aNode) { + + // If we have no namespace, use the DEFAULT_NS as the prefix + final String cacheKey = + XMLConstants.XMLNS_ATTRIBUTE.equals(aNode.getNodeName()) ? DEFAULT_NS : aNode.getLocalName(); + final String nodeValue = aNode.getNodeValue(); + + // Cache the namespace in both caches. + final String oldUriValue = prefix2Uri.put(cacheKey, nodeValue); + final String oldPrefixValue = uri2Prefix.put(nodeValue, cacheKey); + + // Check sanity; we should not be overwriting values here. + if (oldUriValue != null) { + throw new IllegalStateException("Replaced URI [" + oldUriValue + "] with [" + aNode.getNodeValue() + + "] for prefix [" + cacheKey + "]"); + } + if (oldPrefixValue != null) { + throw new IllegalStateException("Replaced prefix [" + oldPrefixValue + "] with [" + cacheKey + + "] for URI [" + aNode.getNodeValue() + "]"); + } + } + } +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/TransformSchema.java b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/TransformSchema.java index 46a524bb..9789c4fa 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/TransformSchema.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/TransformSchema.java @@ -1,202 +1,201 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.codehaus.mojo.jaxb2.shared.Validate; - -/** - *

Data holder for schema transformation operations, to permit customization of the - * schema namespace prefix and file name of generated schema. As the schemagen - * tool has no mechanics to control namespace prefix and file name of generated schema, - * the Jaxb2-Maven-plugin must supply a post-processing step to work around this situation.

- *

Each TransformSchema object holds data pertaining to changes for one namespace - * URI - either namespace prefix used within the generated XSD or resulting filename for - * the schema definition.

- *
    - *
  1. Namespace prefix. Each XML element within a namespace uses the supplied - * prefix. (As a reference, in the XML element <foo:bar/>, the namespace prefix - * is "foo" and the element name is "bar"). The Schemagen tool by default only generates namespace - * prefixes on the form "ns1", "ns2" etc., which means that the generated schema will contain elements - * on the form <xs:extension base="ns1:nazgulEntity">. - * Use a toPrefix element to change the namespace prefix of a particular XML URI to - * simplify understanding the schema.
  2. - *
  3. Filename. By default, the Schemagen tool creates files called "schema1.xsd", - * "schema2.xsd" etc. Since the XSD imports one another, simply changing the filename will frequently - * break the schema structure - you will need to change all import statements in all generated XSD files - * to match the new file names. The Jaxb2 Maven plugin can do all this housekeeping automatically, if you - * create a transformSchema element containing a toFile element to change the filename for a - * particular XML URI. Changing the file names frequently improves overview and usability of the generated schema - * files.
  4. - *
- *

Example TransformSchemas

- *

The URI element is mandatory for each TransformSchema element. The first example illustrates how - * to use the TransformSchema element to change the prefix and file name of 3 XML URIs. This is the recommended - * use of a TransformSchema - change both prefix and filename to something meaningful for each URI:

- *
- * <transformSchemas>
- *      <transformSchema>
- *          <uri>http://some/namespace</uri>
- *          <toPrefix>some</toPrefix>
- *          <toFile>some_schema.xsd</toFile>
- *      </transformSchema>
- *      <transformSchema>
- *          <uri>http://another/namespace</uri>
- *          <toPrefix>another</toPrefix>
- *          <toFile>another_schema.xsd</toFile>
- *      </transformSchema>
- *      <transformSchema>
- *          <uri>http://yet/another/namespace</uri>
- *          <toPrefix>yetAnother</toPrefix>
- *          <toFile>yet_another_schema.xsd</toFile>
- *      </transformSchema>
- * </transformSchemas>
- * 
- *

The URI element is mandatory for each TransformSchema element, along with at least one of the other two - * elements in the TransformSchema. This implies that partial configuration for TransformSchema can be used, - * although this is not recommended since the readability and usability of the automatically generated - * namespace prefixes and file names are poor. The second example illustrates how to use the TransformSchema element - * to change either prefix or file name for 2 XML URIs:

- *
- * <transformSchemas>
- *      <transformSchema>
- *          <uri>http://another/namespace</uri>
- *          <toPrefix>another</toPrefix>
- *      </transformSchema>
- *      <transformSchema>
- *          <uri>http://yet/another/namespace</uri>
- *          <toFile>yet_another_schema.xsd</toFile>
- *      </transformSchema>
- * </transformSchemas>
- * 
- * - * @author Lennart Jörelid - * @since 1.4 - */ -public class TransformSchema { - - /** - * The empty XML Namespace. - */ - public static final String EMPTY_NAMESPACE = ""; - - // Internal state - private String uri = EMPTY_NAMESPACE; - private String toPrefix; - private String toFile; - - /** - * Default constructor. - */ - public TransformSchema() { - } - - /** - * Compound constructor, creating a TransformSchema instruction wrapping the supplied data. - * - * @param uri The URI of this Schema, such as - * http://www.jguru.se/some/namespace. Cannot be null or empty. - * @param toPrefix The new namespace prefix for this Schema. Optional. - * @param toFile The new name of the generated schema file. - */ - public TransformSchema(final String uri, final String toPrefix, final String toFile) { - this.uri = uri; - this.toPrefix = toPrefix; - this.toFile = toFile; - } - - /** - * @return The URI of this Schema, such as http://www.jguru.se/some/namespace. - * The namespace URI is mapped to its prefix in the schema element, i.e: - * xmlns:xs="http://www.w3.org/2001/XMLSchema" or - * xmlns:foo="http://www.acme.com/xml/schema/foo". - */ - public String getUri() { - return uri; - } - - /** - * @return The namespace prefix of this Schema. Each schema element is related to its namespace using the prefix. - * For an XML element <foo:bar/>, the prefix is "foo" (and the element name is "bar"). - */ - public String getToPrefix() { - return toPrefix; - } - - /** - * @return the name of the target file if/when renamed. - */ - public String getToFile() { - return toFile; - } - - /** - * Assigns the URI of this Schema, such as http://www.jguru.se/some/namespace. - * The namespace URI is mapped to its prefix in the schema element, i.e: - * xmlns:xs="http://www.w3.org/2001/XMLSchema" or - * xmlns:foo="http://www.acme.com/xml/schema/foo". - * - * @param uri The non-empty uri of this Schema. - */ - public void setUri(final String uri) { - - // Check sanity - Validate.notEmpty(uri, "uri"); - - // Assign internal state - this.uri = uri; - } - - /** - * Assigns the namespace prefix of this Schema. Each schema element is related to its namespace - * using the prefix. For an XML element <foo:bar/>, the prefix is "foo" - * (and the element name is "bar"). - * - * @param toPrefix The non-empty prefix to assign. - */ - public void setToPrefix(final String toPrefix) { - - // Check sanity - Validate.notEmpty(toPrefix, "toPrefix"); - - // Assign internal state - this.toPrefix = toPrefix; - } - - /** - * Assigns the the name of the target file if/when renamed. - * - * @param toFile The non-empty filename to assign. - */ - public void setToFile(final String toFile) { - - // Check sanity - Validate.notEmpty(toFile, "toFile"); - - // Assign internal state - this.toFile = toFile; - } - - /** - * {@inheritDoc} - */ - public String toString() { - return "[ uri: " + uri + " --> prefix: " + toPrefix + ", file: " + toFile + " ]"; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.codehaus.mojo.jaxb2.shared.Validate; + +/** + *

Data holder for schema transformation operations, to permit customization of the + * schema namespace prefix and file name of generated schema. As the schemagen + * tool has no mechanics to control namespace prefix and file name of generated schema, + * the Jaxb2-Maven-plugin must supply a post-processing step to work around this situation.

+ *

Each TransformSchema object holds data pertaining to changes for one namespace + * URI - either namespace prefix used within the generated XSD or resulting filename for + * the schema definition.

+ *
    + *
  1. Namespace prefix. Each XML element within a namespace uses the supplied + * prefix. (As a reference, in the XML element <foo:bar/>, the namespace prefix + * is "foo" and the element name is "bar"). The Schemagen tool by default only generates namespace + * prefixes on the form "ns1", "ns2" etc., which means that the generated schema will contain elements + * on the form <xs:extension base="ns1:nazgulEntity">. + * Use a toPrefix element to change the namespace prefix of a particular XML URI to + * simplify understanding the schema.
  2. + *
  3. Filename. By default, the Schemagen tool creates files called "schema1.xsd", + * "schema2.xsd" etc. Since the XSD imports one another, simply changing the filename will frequently + * break the schema structure - you will need to change all import statements in all generated XSD files + * to match the new file names. The Jaxb2 Maven plugin can do all this housekeeping automatically, if you + * create a transformSchema element containing a toFile element to change the filename for a + * particular XML URI. Changing the file names frequently improves overview and usability of the generated schema + * files.
  4. + *
+ *

Example TransformSchemas

+ *

The URI element is mandatory for each TransformSchema element. The first example illustrates how + * to use the TransformSchema element to change the prefix and file name of 3 XML URIs. This is the recommended + * use of a TransformSchema - change both prefix and filename to something meaningful for each URI:

+ *
+ * <transformSchemas>
+ *      <transformSchema>
+ *          <uri>http://some/namespace</uri>
+ *          <toPrefix>some</toPrefix>
+ *          <toFile>some_schema.xsd</toFile>
+ *      </transformSchema>
+ *      <transformSchema>
+ *          <uri>http://another/namespace</uri>
+ *          <toPrefix>another</toPrefix>
+ *          <toFile>another_schema.xsd</toFile>
+ *      </transformSchema>
+ *      <transformSchema>
+ *          <uri>http://yet/another/namespace</uri>
+ *          <toPrefix>yetAnother</toPrefix>
+ *          <toFile>yet_another_schema.xsd</toFile>
+ *      </transformSchema>
+ * </transformSchemas>
+ * 
+ *

The URI element is mandatory for each TransformSchema element, along with at least one of the other two + * elements in the TransformSchema. This implies that partial configuration for TransformSchema can be used, + * although this is not recommended since the readability and usability of the automatically generated + * namespace prefixes and file names are poor. The second example illustrates how to use the TransformSchema element + * to change either prefix or file name for 2 XML URIs:

+ *
+ * <transformSchemas>
+ *      <transformSchema>
+ *          <uri>http://another/namespace</uri>
+ *          <toPrefix>another</toPrefix>
+ *      </transformSchema>
+ *      <transformSchema>
+ *          <uri>http://yet/another/namespace</uri>
+ *          <toFile>yet_another_schema.xsd</toFile>
+ *      </transformSchema>
+ * </transformSchemas>
+ * 
+ * + * @author Lennart Jörelid + * @since 1.4 + */ +public class TransformSchema { + + /** + * The empty XML Namespace. + */ + public static final String EMPTY_NAMESPACE = ""; + + // Internal state + private String uri = EMPTY_NAMESPACE; + private String toPrefix; + private String toFile; + + /** + * Default constructor. + */ + public TransformSchema() {} + + /** + * Compound constructor, creating a TransformSchema instruction wrapping the supplied data. + * + * @param uri The URI of this Schema, such as + * http://www.jguru.se/some/namespace. Cannot be null or empty. + * @param toPrefix The new namespace prefix for this Schema. Optional. + * @param toFile The new name of the generated schema file. + */ + public TransformSchema(final String uri, final String toPrefix, final String toFile) { + this.uri = uri; + this.toPrefix = toPrefix; + this.toFile = toFile; + } + + /** + * @return The URI of this Schema, such as http://www.jguru.se/some/namespace. + * The namespace URI is mapped to its prefix in the schema element, i.e: + * xmlns:xs="http://www.w3.org/2001/XMLSchema" or + * xmlns:foo="http://www.acme.com/xml/schema/foo". + */ + public String getUri() { + return uri; + } + + /** + * @return The namespace prefix of this Schema. Each schema element is related to its namespace using the prefix. + * For an XML element <foo:bar/>, the prefix is "foo" (and the element name is "bar"). + */ + public String getToPrefix() { + return toPrefix; + } + + /** + * @return the name of the target file if/when renamed. + */ + public String getToFile() { + return toFile; + } + + /** + * Assigns the URI of this Schema, such as http://www.jguru.se/some/namespace. + * The namespace URI is mapped to its prefix in the schema element, i.e: + * xmlns:xs="http://www.w3.org/2001/XMLSchema" or + * xmlns:foo="http://www.acme.com/xml/schema/foo". + * + * @param uri The non-empty uri of this Schema. + */ + public void setUri(final String uri) { + + // Check sanity + Validate.notEmpty(uri, "uri"); + + // Assign internal state + this.uri = uri; + } + + /** + * Assigns the namespace prefix of this Schema. Each schema element is related to its namespace + * using the prefix. For an XML element <foo:bar/>, the prefix is "foo" + * (and the element name is "bar"). + * + * @param toPrefix The non-empty prefix to assign. + */ + public void setToPrefix(final String toPrefix) { + + // Check sanity + Validate.notEmpty(toPrefix, "toPrefix"); + + // Assign internal state + this.toPrefix = toPrefix; + } + + /** + * Assigns the the name of the target file if/when renamed. + * + * @param toFile The non-empty filename to assign. + */ + public void setToFile(final String toFile) { + + // Check sanity + Validate.notEmpty(toFile, "toFile"); + + // Assign internal state + this.toFile = toFile; + } + + /** + * {@inheritDoc} + */ + public String toString() { + return "[ uri: " + uri + " --> prefix: " + toPrefix + ", file: " + toFile + " ]"; + } +} diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java index e58333b9..62036e02 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilities.java @@ -19,15 +19,6 @@ * under the License. */ -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.shared.filters.Filter; -import org.codehaus.mojo.jaxb2.shared.filters.Filters; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.Os; -import org.codehaus.plexus.util.StringUtils; - import java.io.File; import java.io.FileFilter; import java.io.IOException; @@ -43,6 +34,15 @@ import java.util.SortedMap; import java.util.TreeMap; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.shared.filters.Filter; +import org.codehaus.mojo.jaxb2.shared.filters.Filters; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.Os; +import org.codehaus.plexus.util.StringUtils; + /** * The Jaxb2 Maven Plugin needs to fiddle with the filesystem a great deal, to create and optionally prune * directories or detect/create various files. This utility class contains all such algorithms, and serves as @@ -114,8 +114,8 @@ public static File getCanonicalFile(final File file) { try { return file.getCanonicalFile(); } catch (IOException e) { - throw new IllegalArgumentException("Could not acquire the canonical file for [" - + file.getAbsolutePath() + "]", e); + throw new IllegalArgumentException( + "Could not acquire the canonical file for [" + file.getAbsolutePath() + "]", e); } } @@ -180,8 +180,8 @@ public static URL getUrlFor(final File aFile) throws IllegalArgumentException { try { return aFile.toURI().normalize().toURL(); } catch (MalformedURLException e) { - throw new IllegalArgumentException("Could not retrieve the URL from file [" - + getCanonicalPath(aFile) + "]", e); + throw new IllegalArgumentException( + "Could not retrieve the URL from file [" + getCanonicalPath(aFile) + "]", e); } } @@ -237,7 +237,6 @@ public static File getFileFor(final URL anURL, final String encoding) { return toReturn; } - /** * Filters files found either in the sources paths (or in the standardDirectory if no explicit sources are given), * and retrieves a List holding those files that do not match any of the supplied Java Regular Expression @@ -258,12 +257,13 @@ public static File getFileFor(final URL anURL, final String encoding) { * are given) which do not match the supplied Java Regular excludePatterns. */ @SuppressWarnings("all") - public static List filterFiles(final File baseDir, - final List sources, - final List standardDirectories, - final Log log, - final String fileTypeDescription, - final List> excludePatterns) { + public static List filterFiles( + final File baseDir, + final List sources, + final List standardDirectories, + final Log log, + final String fileTypeDescription, + final List> excludePatterns) { final SortedMap pathToResolvedSourceMap = new TreeMap(); @@ -278,8 +278,7 @@ public static List filterFiles(final File baseDir, // Add the source pathToResolvedSourceMap.put( - FileSystemUtilities.getCanonicalPath(currentResolvedSource), - currentResolvedSource); + FileSystemUtilities.getCanonicalPath(currentResolvedSource), currentResolvedSource); } } @@ -304,8 +303,8 @@ public static List filterFiles(final File baseDir, builder.append("|\n"); builder.append("| " + standardDirectories.size() + " Standard Directories:\n"); for (int i = 0; i < standardDirectories.size(); i++) { - builder.append("| [" + (i + 1) + "/" + standardDirectories.size() + "]: " - + standardDirectories.get(i) + "\n"); + builder.append( + "| [" + (i + 1) + "/" + standardDirectories.size() + "]: " + standardDirectories.get(i) + "\n"); } builder.append("|\n"); @@ -343,12 +342,13 @@ public static List filterFiles(final File baseDir, * do not match the supplied Java Regular excludePatterns. */ @SuppressWarnings("CheckStyle") - public static List filterFiles(final File baseDir, - final List sources, - final String standardDirectory, - final Log log, - final String fileTypeDescription, - final List> excludeFilters) { + public static List filterFiles( + final File baseDir, + final List sources, + final String standardDirectory, + final Log log, + final String fileTypeDescription, + final List> excludeFilters) { // Check sanity Validate.notNull(baseDir, "baseDir"); @@ -453,26 +453,24 @@ public static List filterFiles(final List files, final Filter * @return All files in (or files in subdirectories of directories provided in) the files List, provided that each * file is accepted by an ExclusionRegExpFileFilter. */ - public static List resolveRecursively(final List files, - final List> exclusionFilters, - final Log log) { + public static List resolveRecursively( + final List files, final List> exclusionFilters, final Log log) { // Check sanity Validate.notNull(files, "files"); - final List> effectiveExclusions = exclusionFilters == null - ? new ArrayList>() - : exclusionFilters; + final List> effectiveExclusions = + exclusionFilters == null ? new ArrayList>() : exclusionFilters; final List toReturn = new ArrayList(); if (files.size() > 0) { for (File current : files) { - final boolean isAcceptedFile = EXISTING_FILE.accept(current) - && Filters.noFilterMatches(current, effectiveExclusions); - final boolean isAcceptedDirectory = EXISTING_DIRECTORY.accept(current) - && Filters.noFilterMatches(current, effectiveExclusions); + final boolean isAcceptedFile = + EXISTING_FILE.accept(current) && Filters.noFilterMatches(current, effectiveExclusions); + final boolean isAcceptedDirectory = + EXISTING_DIRECTORY.accept(current) && Filters.noFilterMatches(current, effectiveExclusions); if (isAcceptedFile) { toReturn.add(current); @@ -513,8 +511,8 @@ public static void createDirectory(final File aDirectory, final boolean cleanBef // Now, make the required directory, if it does not already exist as a directory. final boolean existsAsFile = aDirectory.exists() && aDirectory.isFile(); if (existsAsFile) { - throw new MojoExecutionException("[" + getCanonicalPath(aDirectory) + "] exists and is a file. " - + "Cannot make directory"); + throw new MojoExecutionException( + "[" + getCanonicalPath(aDirectory) + "] exists and is a file. " + "Cannot make directory"); } else if (!aDirectory.exists() && !aDirectory.mkdirs()) { throw new MojoExecutionException("Could not create directory [" + getCanonicalPath(aDirectory) + "]"); } @@ -529,9 +527,7 @@ public static void createDirectory(final File aDirectory, final boolean cleanBef * @param removeInitialFileSep If true, an initial {@code File#separator} is removed before returning. * @return The path relative to basedir, if it is situated below the basedir. Otherwise the supplied path. */ - public static String relativize(final String path, - final File parentDir, - final boolean removeInitialFileSep) { + public static String relativize(final String path, final File parentDir, final boolean removeInitialFileSep) { // Check sanity Validate.notNull(path, "path"); @@ -572,9 +568,7 @@ public static String relativize(final String path, * least one Filter accepts them. */ @SuppressWarnings("all") - public static List listFiles(final File fileOrDir, - final List> fileFilters, - final Log log) { + public static List listFiles(final File fileOrDir, final List> fileFilters, final Log log) { return listFiles(fileOrDir, fileFilters, false, log); } @@ -594,10 +588,11 @@ public static List listFiles(final File fileOrDir, * least one Filter accepts them. */ @SuppressWarnings("all") - public static List listFiles(final File fileOrDir, - final List> fileFilters, - final boolean excludeFilterOperation, - final Log log) { + public static List listFiles( + final File fileOrDir, + final List> fileFilters, + final boolean excludeFilterOperation, + final Log log) { // Check sanity Validate.notNull(log, "log"); @@ -630,11 +625,12 @@ public static List listFiles(final File fileOrDir, // Private helpers // - private static void checkAndAdd(final List toPopulate, - final File current, - final List> fileFilters, - final boolean excludeFilterOperation, - final Log log) { + private static void checkAndAdd( + final List toPopulate, + final File current, + final List> fileFilters, + final boolean excludeFilterOperation, + final Log log) { // // When no filters are supplied... @@ -645,8 +641,8 @@ private static void checkAndAdd(final List toPopulate, final boolean addFile = excludeFilterOperation ? noFilters || Filters.rejectAtLeastOnce(current, fileFilters) : noFilters || Filters.matchAtLeastOnce(current, fileFilters); - final String logPrefix = (addFile ? "Accepted " : "Rejected ") - + (current.isDirectory() ? "directory" : "file") + " ["; + final String logPrefix = + (addFile ? "Accepted " : "Rejected ") + (current.isDirectory() ? "directory" : "file") + " ["; if (addFile) { toPopulate.add(current); @@ -666,11 +662,12 @@ private static void validateFileOrDirectoryName(final File fileOrDir) { } } - private static void recurseAndPopulate(final List toPopulate, - final List> fileFilters, - final File aDirectory, - final boolean excludeOperation, - final Log log) { + private static void recurseAndPopulate( + final List toPopulate, + final List> fileFilters, + final File aDirectory, + final boolean excludeOperation, + final Log log) { final List files = listFiles(aDirectory, fileFilters, excludeOperation, log); for (File current : files) { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/JavaVersion.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/JavaVersion.java index 643e1dc5..d7049c30 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/JavaVersion.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/JavaVersion.java @@ -36,7 +36,8 @@ public final class JavaVersion { */ public static int getJavaMajorVersion() { - final String[] versionElements = System.getProperty(JAVA_VERSION_PROPERTY).split("\\."); + final String[] versionElements = + System.getProperty(JAVA_VERSION_PROPERTY).split("\\."); final int[] versionNumbers = new int[versionElements.length]; for (int i = 0; i < versionElements.length; i++) { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java index e18e448e..f5f437ff 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/Validate.java @@ -30,8 +30,7 @@ public final class Validate { /** * Hide constructor for utility classes. */ - private Validate() { - } + private Validate() {} /** * Validates that the supplied object is not null, and throws a NullPointerException otherwise. diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java index d7393f2b..6452caf4 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilder.java @@ -19,12 +19,12 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.util.ArrayList; import java.util.List; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.shared.Validate; + /** * Utility class to build an array containing method arguments, as received from a command-line invocation of a tool. * @@ -80,7 +80,8 @@ public ArgumentBuilder withFlag(final boolean addFlag, final String flag) { // Check sanity Validate.notEmpty(flag, "flag"); - Validate.isTrue(!AbstractJaxbMojo.CONTAINS_WHITESPACE.matcher(flag).matches(), + Validate.isTrue( + !AbstractJaxbMojo.CONTAINS_WHITESPACE.matcher(flag).matches(), "Flags cannot contain whitespace. Got: [" + flag + "]"); // Trim, and add the flag as an argument. @@ -126,9 +127,7 @@ public ArgumentBuilder withFlag(final boolean addFlag, final String flag) { * @param value The value of the namedArgument to add. * @return This ArgumentBuilder, for chaining. */ - public ArgumentBuilder withNamedArgument(final boolean addNamedArgument, - final String name, - final String value) { + public ArgumentBuilder withNamedArgument(final boolean addNamedArgument, final String name, final String value) { // Bail out? if (!addNamedArgument) { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/ToolExecutionEnvironment.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/ToolExecutionEnvironment.java index 2b7fba44..fa7d35ed 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/ToolExecutionEnvironment.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/ToolExecutionEnvironment.java @@ -19,6 +19,9 @@ * under the License. */ +import java.util.ArrayList; +import java.util.List; + import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.jaxb2.shared.Validate; import org.codehaus.mojo.jaxb2.shared.environment.classloading.ThreadContextClassLoaderBuilder; @@ -26,9 +29,6 @@ import org.codehaus.mojo.jaxb2.shared.environment.locale.LocaleFacet; import org.codehaus.mojo.jaxb2.shared.environment.logging.LoggingHandlerEnvironmentFacet; -import java.util.ArrayList; -import java.util.List; - /** * Compound EnvironmentFacet implementation which is used to set up and use a collection * of other EnvironmentFacet instances during the run of the JAXB2 Maven Plugin. @@ -54,10 +54,11 @@ public class ToolExecutionEnvironment extends AbstractLogAwareFacet { * the localeFacet is {@code null}, the locale will not be changed. * @param loggingHandlerFacet The EnvironmentFacet for replacing Handlers from Java Util Logging with a Maven Log. */ - public ToolExecutionEnvironment(final Log mavenLog, - final ThreadContextClassLoaderBuilder builder, - final LoggingHandlerEnvironmentFacet loggingHandlerFacet, - final LocaleFacet localeFacet) { + public ToolExecutionEnvironment( + final Log mavenLog, + final ThreadContextClassLoaderBuilder builder, + final LoggingHandlerEnvironmentFacet loggingHandlerFacet, + final LocaleFacet localeFacet) { super(mavenLog); // Check sanity @@ -132,8 +133,10 @@ public final void setup() { try { current.setup(); } catch (Exception e) { - throw new IllegalStateException("Could not setup() EnvironmentFacet of type [" - + current.getClass().getName() + "]", e); + throw new IllegalStateException( + "Could not setup() EnvironmentFacet of type [" + + current.getClass().getName() + "]", + e); } } @@ -164,8 +167,10 @@ public final void restore() { try { current.restore(); } catch (Exception e) { - throw new IllegalStateException("Could not restore() EnvironmentFacet of type [" - + current.getClass().getName() + "]", e); + throw new IllegalStateException( + "Could not restore() EnvironmentFacet of type [" + + current.getClass().getName() + "]", + e); } } } finally { diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ContextClassLoaderEnvironmentFacet.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ContextClassLoaderEnvironmentFacet.java index c0137edb..175d8e8a 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ContextClassLoaderEnvironmentFacet.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ContextClassLoaderEnvironmentFacet.java @@ -43,8 +43,7 @@ public class ContextClassLoaderEnvironmentFacet extends AbstractLogAwareFacet { * should not be invoked yet. * @see ThreadContextClassLoaderBuilder */ - public ContextClassLoaderEnvironmentFacet(final Log log, - final ThreadContextClassLoaderBuilder builder) { + public ContextClassLoaderEnvironmentFacet(final Log log, final ThreadContextClassLoaderBuilder builder) { super(log); // Check sanity diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java index 5a022ae6..5428c00f 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/classloading/ThreadContextClassLoaderBuilder.java @@ -19,9 +19,6 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; @@ -32,6 +29,9 @@ import java.util.Collections; import java.util.List; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.shared.Validate; + import static org.codehaus.mojo.jaxb2.shared.environment.classloading.ThreadContextClassLoaderBuilder.SupportedURLProtocols.*; /** @@ -68,7 +68,6 @@ public final class ThreadContextClassLoaderBuilder { * Simple enumeration of supported classpath URL protocols. */ enum SupportedURLProtocols { - FILE, JAR, @@ -250,9 +249,8 @@ public ThreadContextClassLoaderHolder buildAndSet() { * @param encoding The encoding used by Maven. Cannot be null. * @return A ThreadContextClassLoaderBuilder wrapping the supplied members. */ - public static ThreadContextClassLoaderBuilder createFor(final ClassLoader classLoader, - final Log log, - final String encoding) { + public static ThreadContextClassLoaderBuilder createFor( + final ClassLoader classLoader, final Log log, final String encoding) { // Check sanity Validate.notNull(classLoader, "classLoader"); @@ -271,9 +269,8 @@ public static ThreadContextClassLoaderBuilder createFor(final ClassLoader classL * @param encoding The encoding used by Maven. Cannot be null. * @return A ThreadContextClassLoaderBuilder wrapping the supplied members. */ - public static ThreadContextClassLoaderBuilder createFor(final Class aClass, - final Log log, - final String encoding) { + public static ThreadContextClassLoaderBuilder createFor( + final Class aClass, final Log log, final String encoding) { // Check sanity Validate.notNull(aClass, "aClass"); @@ -304,8 +301,8 @@ public static String getClassPathElement(final URL anURL, final String encoding) try { return URLDecoder.decode(anURL.getPath(), encoding); } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException("Could not URLDecode path [" + originalPath - + "] using encoding [" + encoding + "]", e); + throw new IllegalArgumentException( + "Could not URLDecode path [" + originalPath + "] using encoding [" + encoding + "]", e); } } else if (JAR.supports(protocol)) { toReturn = anURL.getPath(); @@ -314,8 +311,8 @@ public static String getClassPathElement(final URL anURL, final String encoding) } else if (BUNDLERESOURCE.supports(protocol)) { // e.g. when used in Eclipse/m2e toReturn = anURL.toString(); } else { - throw new IllegalArgumentException("Unknown protocol [" + protocol + "]; could not handle URL [" - + anURL + "]"); + throw new IllegalArgumentException( + "Unknown protocol [" + protocol + "]; could not handle URL [" + anURL + "]"); } return toReturn; @@ -375,9 +372,8 @@ class DefaultHolder implements ThreadContextClassLoaderHolder { * @param classPathArgument The non-null classpath argument, to be returned * from the method call to {@link #getClassPathAsArgument()}. */ - public DefaultHolder(final Thread affectedThread, - final ClassLoader originalClassLoader, - final String classPathArgument) { + public DefaultHolder( + final Thread affectedThread, final ClassLoader originalClassLoader, final String classPathArgument) { // Check sanity Validate.notNull(affectedThread, "affectedThread"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacet.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacet.java index e1ced8da..2d36c299 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacet.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacet.java @@ -19,14 +19,14 @@ * under the License. */ +import java.util.Locale; +import java.util.StringTokenizer; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.jaxb2.shared.Validate; import org.codehaus.mojo.jaxb2.shared.environment.AbstractLogAwareFacet; -import java.util.Locale; -import java.util.StringTokenizer; - /** * EnvironmentFacet implementation which alters the default Locale for the * remainder of the tool execution. @@ -71,8 +71,7 @@ public void setup() { try { Locale.setDefault(newLocale); } catch (Exception e) { - log.error("Could not switch locale to [" - + newLocale + "]. Continuing with standard locale.", e); + log.error("Could not switch locale to [" + newLocale + "]. Continuing with standard locale.", e); } } @@ -90,8 +89,10 @@ public void restore() { try { Locale.setDefault(originalLocale); } catch (Exception e) { - log.error("Could not restore locale to [" + originalLocale + "]. Continuing with [" - + Locale.getDefault() + "]", e); + log.error( + "Could not restore locale to [" + originalLocale + "]. Continuing with [" + Locale.getDefault() + + "]", + e); } } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java index eca3550b..c9dd2b5f 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/LoggingHandlerEnvironmentFacet.java @@ -19,17 +19,17 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.codehaus.mojo.jaxb2.shared.environment.AbstractLogAwareFacet; - import java.util.ArrayList; import java.util.List; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.codehaus.mojo.jaxb2.shared.environment.AbstractLogAwareFacet; + /** * EnvironmentFacet for replacing Handlers from Java Util Logging with a Maven Log. * This is required as an environment facet for capturing log statements from tools @@ -43,7 +43,7 @@ public class LoggingHandlerEnvironmentFacet extends AbstractLogAwareFacet { /** * Standard logger names/categories for the java.util.Logger. */ - public static final String[] DEFAULT_LOGGER_NAMES = new String[]{"com.sun", "javax.xml", "javax.tools"}; + public static final String[] DEFAULT_LOGGER_NAMES = new String[] {"com.sun", "javax.xml", "javax.tools"}; // Internal state private boolean restored; @@ -66,10 +66,8 @@ public class LoggingHandlerEnvironmentFacet extends AbstractLogAwareFacet { * @param encoding The configured encoding. * @param loggerNamePrefixes The prefixes of the Logger names to be permitted logging. */ - public LoggingHandlerEnvironmentFacet(final String logPrefix, - final Log mavenLog, - final String encoding, - final String[] loggerNamePrefixes) { + public LoggingHandlerEnvironmentFacet( + final String logPrefix, final Log mavenLog, final String encoding, final String[] loggerNamePrefixes) { super(mavenLog); @@ -139,9 +137,8 @@ public void restore() { * @param encoding The encoding used by the Maven Mojo subclass. * @return A fully set up LoggingHandlerEnvironmentFacet */ - public static LoggingHandlerEnvironmentFacet create(final Log mavenLog, - final Class caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class caller, final String encoding) { // Check sanity Validate.notNull(mavenLog, "mavenLog"); @@ -149,9 +146,8 @@ public static LoggingHandlerEnvironmentFacet create(final Log mavenLog, Validate.notEmpty(encoding, "encoding"); // Find the standard log prefix for the tool in question. - final String logPrefix = caller.getClass().getCanonicalName().toUpperCase().contains("XJC") - ? "XJC" - : "SchemaGen"; + final String logPrefix = + caller.getClass().getCanonicalName().toUpperCase().contains("XJC") ? "XJC" : "SchemaGen"; // All done. return new LoggingHandlerEnvironmentFacet(logPrefix, mavenLog, encoding, DEFAULT_LOGGER_NAMES); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/MavenLogHandler.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/MavenLogHandler.java index 3b610826..66abe24e 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/MavenLogHandler.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/logging/MavenLogHandler.java @@ -19,9 +19,6 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; @@ -31,6 +28,9 @@ import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.shared.Validate; + /** * Handler implementation which delegates its actual logging to an internal Maven log. * This is required to capture logging statements from tools that use the Java Util Logging @@ -54,10 +54,8 @@ public class MavenLogHandler extends Handler { * @param acceptedLogRecordPrefixes A non-null list of prefixes holding LogRecord logger names for * permitted/accepted LogRecords. */ - public MavenLogHandler(final Log log, - final String prefix, - final String encoding, - final String[] acceptedLogRecordPrefixes) { + public MavenLogHandler( + final Log log, final String prefix, final String encoding, final String[] acceptedLogRecordPrefixes) { // Check sanity Validate.notNull(log, "log"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertyChangeEnvironmentFacet.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertyChangeEnvironmentFacet.java index 595a47b4..45886fb7 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertyChangeEnvironmentFacet.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertyChangeEnvironmentFacet.java @@ -19,14 +19,14 @@ * under the License. */ +import java.util.ArrayList; +import java.util.List; + import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; import org.codehaus.mojo.jaxb2.shared.Validate; import org.codehaus.mojo.jaxb2.shared.environment.AbstractLogAwareFacet; -import java.util.ArrayList; -import java.util.List; - /** * EnvironmentFacet which changes the value of a system property for the duration * of executing a tool. This is required for tools (such as the JDK SchemaGen) which diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacet.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacet.java index 16ad569a..12c6b4d9 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacet.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacet.java @@ -7,10 +7,10 @@ * EnvironmentFacet which saves the value of a system property for the duration * of executing a tool. This may be required for tools (such as the XJC tool) which * may overwrite property values for its own purpose. - * + * * Unlike {@link SystemPropertyChangeEnvironmentFacet}, this does not a set a new * property value itself, just saves the old value and later restores or clears it. - * + * * This facet accepts the key of the property to save. * * @author Svein Elgstøen diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/AbstractFilter.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/AbstractFilter.java index e7cb21f4..c86a973d 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/AbstractFilter.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/AbstractFilter.java @@ -19,13 +19,13 @@ * under the License. */ +import java.util.ArrayList; +import java.util.List; + import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; import org.codehaus.mojo.jaxb2.shared.Validate; -import java.util.ArrayList; -import java.util.List; - /** * Abstract Filter implementation which handles separating {@code null} candidate values from non-null * ones, and delegates processing to concrete subclass implementations. Also, this AbstractFilter @@ -73,8 +73,9 @@ protected AbstractFilter() { * @param setterPropertyName The name of the property to inject. */ protected final void validateDiSetterCalledBeforeInitialization(final String setterPropertyName) { - Validate.isTrue(log == null, "DI Setters should only be called before initializing. Stray call: [" - + setterPropertyName + "]"); + Validate.isTrue( + log == null, + "DI Setters should only be called before initializing. Stray call: [" + setterPropertyName + "]"); } /** @@ -164,8 +165,8 @@ public final boolean accept(final T candidate) throws IllegalStateException { toReturn = onNullCandidate(); } else { if (log.isDebugEnabled()) { - log.debug("Received null candidate, and Filter [" + getClass().getSimpleName() - + "] is configured not to match nulls."); + log.debug("Received null candidate, and Filter [" + + getClass().getSimpleName() + "] is configured not to match nulls."); } } @@ -209,7 +210,7 @@ protected boolean onNullCandidate() { */ @Override public String toString() { - return "Filter [" + getClass().getSimpleName() + "]" + AbstractJaxbMojo.NEWLINE - + TOSTRING_INDENT + "Processes nulls: [" + processNullValues + "]" + AbstractJaxbMojo.NEWLINE; + return "Filter [" + getClass().getSimpleName() + "]" + AbstractJaxbMojo.NEWLINE + TOSTRING_INDENT + + "Processes nulls: [" + processNullValues + "]" + AbstractJaxbMojo.NEWLINE; } } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java index 4c69c11e..a1d67a46 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/Filters.java @@ -19,14 +19,14 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.shared.Validate; + /** *

Algorithm definitions for common operations using Filters.

*

SPI Note:This class/these methods should be replaced diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilter.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilter.java index 580c9dc0..77fe4757 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilter.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilter.java @@ -19,14 +19,14 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.codehaus.mojo.jaxb2.shared.filters.AbstractFilter; - import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.codehaus.mojo.jaxb2.shared.filters.AbstractFilter; + /** *

AbstractFilter implementation containing a Java Pattern which should be used to determine if candidate T objects * match any of the supplied regularExpressions. Since Java regexp Patterns only match strings, a pluggable @@ -78,8 +78,10 @@ public final void setPatternPrefix(final String patternPrefix) { // Assign internal state this.patternPrefix = patternPrefix; } else { - addDelayedLogMessage("warn", "Received null patternPrefix for configuring AbstractPatternFilter of type [" - + getClass().getName() + "]. Ignoring and proceeding."); + addDelayedLogMessage( + "warn", + "Received null patternPrefix for configuring AbstractPatternFilter of type [" + + getClass().getName() + "]. Ignoring and proceeding."); } } @@ -105,8 +107,10 @@ public void setPatterns(final List patterns) { this.patterns = new ArrayList(); this.patterns.addAll(patterns); } else { - addDelayedLogMessage("warn", "Received null patterns for configuring AbstractPatternFilter of type [" - + getClass().getName() + "]. Ignoring and proceeding."); + addDelayedLogMessage( + "warn", + "Received null patterns for configuring AbstractPatternFilter of type [" + + getClass().getName() + "]. Ignoring and proceeding."); } } @@ -159,8 +163,8 @@ protected void onInitialize() { if (patterns == null && log.isWarnEnabled()) { // Log somewhat - log.warn("No Patterns configured for AbstractPatternFilter [" + getClass().getName() + "]. " - + "This could imply a configuration problem."); + log.warn("No Patterns configured for AbstractPatternFilter [" + + getClass().getName() + "]. " + "This could imply a configuration problem."); } else { // Complete internal state @@ -212,8 +216,8 @@ protected boolean onCandidate(final T nonNullCandidate) { if (current.matcher(candidateString).matches()) { if (log.isDebugEnabled()) { - log.debug("CandidateString [" + candidateString + "] matched pattern [" - + current.pattern() + "]"); + log.debug("CandidateString [" + candidateString + "] matched pattern [" + current.pattern() + + "]"); } // Adjust and return @@ -276,20 +280,25 @@ public static List convert(final List patternStrings, final Str public String toString() { final StringBuilder builder = new StringBuilder(super.toString()); - builder.append(TOSTRING_INDENT + "Accept on match: [").append(acceptCandidateOnPatternMatch).append("]\n"); - builder.append(TOSTRING_INDENT + "Initialized : [").append(isInitialized()).append("]\n"); + builder.append(TOSTRING_INDENT + "Accept on match: [") + .append(acceptCandidateOnPatternMatch) + .append("]\n"); + builder.append(TOSTRING_INDENT + "Initialized : [") + .append(isInitialized()) + .append("]\n"); final List effectivePatterns = isInitialized() ? regularExpressions : convert(patterns, patternPrefix); - final int numPatterns = effectivePatterns != null && effectivePatterns.size() > 0 - ? effectivePatterns.size() - : 0; + final int numPatterns = + effectivePatterns != null && effectivePatterns.size() > 0 ? effectivePatterns.size() : 0; builder.append(TOSTRING_INDENT).append(numPatterns).append(" regularExpressions "); if (numPatterns > 0) { builder.append(":\n"); for (int i = 0; i < effectivePatterns.size(); i++) { final String prefix = TOSTRING_INDENT + " [" + (i + 1) + "/" + effectivePatterns.size() + "]: "; - builder.append(prefix).append(effectivePatterns.get(i).pattern()).append("\n"); + builder.append(prefix) + .append(effectivePatterns.get(i).pattern()) + .append("\n"); } } else { builder.append("\n"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/FileFilterAdapter.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/FileFilterAdapter.java index 8961f387..39b46ca4 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/FileFilterAdapter.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/FileFilterAdapter.java @@ -19,13 +19,13 @@ * under the License. */ +import java.io.File; +import java.io.FileFilter; + import org.codehaus.mojo.jaxb2.shared.Validate; import org.codehaus.mojo.jaxb2.shared.filters.AbstractFilter; import org.codehaus.mojo.jaxb2.shared.filters.Filter; -import java.io.File; -import java.io.FileFilter; - /** * Filter implementation adapting a FileFilter instance to the Filter interface. * Delegates the {@link #onCandidate(File)} call to the supplied {@link FileFilter} delegate. diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java index 6e469478..4e94bc47 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilter.java @@ -19,18 +19,17 @@ * under the License. */ -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.codehaus.mojo.jaxb2.shared.filters.Filter; -import org.codehaus.mojo.jaxb2.shared.filters.Filters; - import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.regex.Pattern; + +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.codehaus.mojo.jaxb2.shared.filters.Filter; +import org.codehaus.mojo.jaxb2.shared.filters.Filters; /** *

AbstractPatternFilter and FileFilter combination, using a set of Regular expressions @@ -81,7 +80,8 @@ public String convert(final File toConvert) { * if {@code false}, this PatternFileFilter will noFilterMatches * candidates that match at least one of the supplied patterns. */ - public PatternFileFilter(final boolean processNullValues, + public PatternFileFilter( + final boolean processNullValues, final String patternPrefix, final List patterns, final StringConverter converter, @@ -149,8 +149,7 @@ public PatternFileFilter() { * @return A List containing a PatternFileFilter using the supplied suffix patterns to match Files. * @see PatternFileFilter */ - public static List> createExcludeFilterList(final Log log, - final String... patterns) { + public static List> createExcludeFilterList(final Log log, final String... patterns) { return createFilterList(log, false, patterns); } @@ -164,8 +163,7 @@ public static List> createExcludeFilterList(final Log log, * @return A List containing a PatternFileFilter using the supplied suffix patterns to match Files. * @see PatternFileFilter */ - public static List> createIncludeFilterList(final Log log, - final String... patterns) { + public static List> createIncludeFilterList(final Log log, final String... patterns) { return createFilterList(log, true, patterns); } @@ -173,9 +171,8 @@ public static List> createIncludeFilterList(final Log log, // Private helpers // - private static List> createFilterList(final Log log, - final boolean includeOperation, - final String... patterns) { + private static List> createFilterList( + final Log log, final boolean includeOperation, final String... patterns) { // Check sanity Validate.notNull(patterns, "patterns"); diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilter.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilter.java index a043f85d..80c7d1c2 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilter.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilter.java @@ -84,11 +84,12 @@ public PatternURLFilter(final List patternStrings) { * {@code false}, this ExclusionRegularExpressionURLFilter will noFilterMatches * candidates that match at least one of the supplied patterns. */ - public PatternURLFilter(final boolean processNullValues, - final String patternPrefix, - final List patterns, - final StringConverter converter, - final boolean acceptCandidateOnPatternMatch) { + public PatternURLFilter( + final boolean processNullValues, + final String patternPrefix, + final List patterns, + final StringConverter converter, + final boolean acceptCandidateOnPatternMatch) { super(); // Assign internal state diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/package-info.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/package-info.java index b5e7137f..c08a7717 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/package-info.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/package-info.java @@ -7,4 +7,4 @@ * @author Lennart Jörelid * @see The JAXB Reference Implementation */ -package org.codehaus.mojo.jaxb2.shared; \ No newline at end of file +package org.codehaus.mojo.jaxb2.shared; diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependencyInfo.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependencyInfo.java index 64ea0451..f5df9d0f 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependencyInfo.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependencyInfo.java @@ -126,10 +126,14 @@ public int hashCode() { */ @Override public String toString() { - return groupId + GROUP_ARTIFACT_SEPARATOR - + artifactId + GROUP_ARTIFACT_SEPARATOR - + version + GROUP_ARTIFACT_SEPARATOR - + scope + GROUP_ARTIFACT_SEPARATOR + return groupId + + GROUP_ARTIFACT_SEPARATOR + + artifactId + + GROUP_ARTIFACT_SEPARATOR + + version + + GROUP_ARTIFACT_SEPARATOR + + scope + + GROUP_ARTIFACT_SEPARATOR + type; } diff --git a/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependsFileParser.java b/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependsFileParser.java index 044790ee..07b86b29 100644 --- a/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependsFileParser.java +++ b/src/main/java/org/codehaus/mojo/jaxb2/shared/version/DependsFileParser.java @@ -19,8 +19,6 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -32,6 +30,8 @@ import java.util.StringTokenizer; import java.util.TreeMap; +import org.codehaus.mojo.jaxb2.shared.Validate; + /** * Trivial parser to handle depends-plugin-style files. * @@ -84,8 +84,7 @@ public final class DependsFileParser { /** * Hide constructors for utility classes */ - private DependsFileParser() { - } + private DependsFileParser() {} /** * Extracts all build-time dependency information from a dependencies.properties file @@ -106,8 +105,8 @@ public static SortedMap getVersionMap(final String artifactId) { try { // Get the ClassLoader used final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - final List manifestURLs = Collections.list( - contextClassLoader.getResources(DEPENDENCIES_PROPERTIES_FILE)); + final List manifestURLs = + Collections.list(contextClassLoader.getResources(DEPENDENCIES_PROPERTIES_FILE)); // Find the latest of the URLs matching, to cope with test-scope dependencies. URL matching = null; @@ -129,8 +128,8 @@ public static SortedMap getVersionMap(final String artifactId) { if (extractionException != null) { throw new IllegalStateException("Could not read data from manifest.", extractionException); } else { - throw new IllegalStateException("Found no manifest corresponding to artifact name snippet '" - + artifactId + "'."); + throw new IllegalStateException( + "Found no manifest corresponding to artifact name snippet '" + artifactId + "'."); } } @@ -168,8 +167,8 @@ public static SortedMap getVersionMap(final URL anURL) { // Stash this for later use. StringTokenizer tok = new StringTokenizer(trimmedLine, KEY_VALUE_SEPARATOR, false); - Validate.isTrue(tok.countTokens() == 2, "Found incorrect dependency.properties line [" - + aLine + "]"); + Validate.isTrue( + tok.countTokens() == 2, "Found incorrect dependency.properties line [" + aLine + "]"); final String key = tok.nextToken().trim(); final String value = tok.nextToken().trim(); @@ -208,9 +207,11 @@ public static SortedMap createDependencyInfoMap( if (currentKey.contains(VERSION_LINE_INDICATOR)) { final StringTokenizer tok = new StringTokenizer(currentKey, GROUP_ARTIFACT_SEPARATOR, false); - Validate.isTrue(tok.countTokens() == 3, "Expected key on the form [groupId]" - + GROUP_ARTIFACT_SEPARATOR + "[artifactId]" + VERSION_LINE_INDICATOR + ", but got [" - + currentKey + "]"); + Validate.isTrue( + tok.countTokens() == 3, + "Expected key on the form [groupId]" + + GROUP_ARTIFACT_SEPARATOR + "[artifactId]" + VERSION_LINE_INDICATOR + ", but got [" + + currentKey + "]"); final String groupId = tok.nextToken(); final String artifactId = tok.nextToken(); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/BufferingLog.java b/src/test/java/org/codehaus/mojo/jaxb2/BufferingLog.java index eb6275f7..aad0b8d9 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/BufferingLog.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/BufferingLog.java @@ -1,13 +1,13 @@ package org.codehaus.mojo.jaxb2; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.mojo.jaxb2.shared.Validate; - import java.text.NumberFormat; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; +import org.apache.maven.plugin.logging.Log; +import org.codehaus.mojo.jaxb2.shared.Validate; + /** * Trivial Maven Log implementation which stores all logged messages * within a SortedMap for later retrieval. @@ -97,7 +97,8 @@ public String getPrettyPrintedLog() { final Throwable error = current.getValue(); if (error != null) { - builder.append(" [" + error.getMessage() + "]: " + error.getClass().getSimpleName()); + builder.append( + " [" + error.getMessage() + "]: " + error.getClass().getSimpleName()); } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/AbstractJavadocExtractorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/AbstractJavadocExtractorTest.java index da51129f..14a84f93 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/AbstractJavadocExtractorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/AbstractJavadocExtractorTest.java @@ -1,5 +1,12 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; +import java.io.File; +import java.io.StringReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocExtractor; @@ -13,13 +20,6 @@ import org.w3c.dom.Document; import se.jguru.shared.algorithms.api.resources.PropertyResources; -import java.io.File; -import java.io.StringReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -71,12 +71,8 @@ protected SearchableDocumentation processSources() { // First, add all sources to the extractor for (File current : sourceRootDirectories) { - final List currentFiles = FileSystemUtilities.filterFiles(current, - null, - "", - log, - "JavaSources", - javaSourceExcludeFilter); + final List currentFiles = + FileSystemUtilities.filterFiles(current, null, "", log, "JavaSources", javaSourceExcludeFilter); // Add All source files found. extractor.addSourceFiles(currentFiles); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/DebugNodeProcessor.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/DebugNodeProcessor.java index ea46c493..a1d216e3 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/DebugNodeProcessor.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/DebugNodeProcessor.java @@ -1,52 +1,52 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; - -import org.w3c.dom.Node; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Lennart Jörelid - */ -public class DebugNodeProcessor implements NodeProcessor { - - // Internal state - private NodeProcessor delegate; - private List acceptedNodes = new ArrayList(); - - /** - * Creates a new DebugNodeProcessor, delegating all calls to the provided NodeProcessor. - * - * @param delegate The NodeProcessor to which all calls to this NodeProcessor - * will be delegated. - */ - public DebugNodeProcessor(NodeProcessor delegate) { - this.delegate = delegate; - } - - /** - * {@inheritDoc} - */ - public boolean accept(Node aNode) { - final boolean accepted = delegate.accept(aNode); - if (accepted) { - acceptedNodes.add(aNode); - } - - return accepted; - } - - /** - * {@inheritDoc} - */ - public void process(Node aNode) { - delegate.process(aNode); - } - - /** - * @return The ordered List of Nodes accepted by the delegate NodeProcessor. - */ - public List getAcceptedNodes() { - return acceptedNodes; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; + +import java.util.ArrayList; +import java.util.List; + +import org.w3c.dom.Node; + +/** + * @author Lennart Jörelid + */ +public class DebugNodeProcessor implements NodeProcessor { + + // Internal state + private NodeProcessor delegate; + private List acceptedNodes = new ArrayList(); + + /** + * Creates a new DebugNodeProcessor, delegating all calls to the provided NodeProcessor. + * + * @param delegate The NodeProcessor to which all calls to this NodeProcessor + * will be delegated. + */ + public DebugNodeProcessor(NodeProcessor delegate) { + this.delegate = delegate; + } + + /** + * {@inheritDoc} + */ + public boolean accept(Node aNode) { + final boolean accepted = delegate.accept(aNode); + if (accepted) { + acceptedNodes.add(aNode); + } + + return accepted; + } + + /** + * {@inheritDoc} + */ + public void process(Node aNode) { + delegate.process(aNode); + } + + /** + * @return The ordered List of Nodes accepted by the delegate NodeProcessor. + */ + public List getAcceptedNodes() { + return acceptedNodes; + } +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/XsdGeneratorHelperTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/XsdGeneratorHelperTest.java index 4d1b9501..ebf33d6a 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/XsdGeneratorHelperTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/XsdGeneratorHelperTest.java @@ -1,423 +1,392 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; - -import org.apache.maven.plugin.MojoExecutionException; -import org.codehaus.mojo.jaxb2.BufferingLog; -import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.AbstractSourceCodeAwareNodeProcessingTest; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocExtractor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.NoAuthorJavaDocRenderer; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SearchableDocumentation; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdAnnotationProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdEnumerationAnnotationProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeNamespacePrefixProcessor; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.SimpleNamespaceResolver; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.TransformSchema; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.codehaus.mojo.jaxb2.shared.filters.Filter; -import org.codehaus.mojo.jaxb2.shared.filters.Filters; -import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.ElementNameAndAttributeQualifier; -import org.custommonkey.xmlunit.XMLAssert; -import org.custommonkey.xmlunit.XMLUnit; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.w3c.dom.Document; -import se.jguru.shared.algorithms.api.resources.PropertyResources; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerFactory; -import java.io.File; -import java.io.StringReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.CodeSource; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * @author Lennart Jörelid - */ -public class XsdGeneratorHelperTest -{ - - private static TransformerFactory factory; - - @BeforeClass - public static void setupSharedState() - { - - // Configure XMLUnit. - XMLUnit.setIgnoreWhitespace( true ); - XMLUnit.setIgnoreAttributeOrder( true ); - - // Configure the TransformerFactory - try - { - - factory = TransformerFactory.newInstance(); - final CodeSource codeSource = factory.getClass().getProtectionDomain().getCodeSource(); - - final String location = codeSource == null ? "Unknown" : codeSource.getLocation().toString(); - System.out.println( - "-- Found TransformerFactory of type [" + factory.getClass().getName() + "] loaded from [" + location + "]" ); - - } - catch ( Exception ex ) - { - ex.printStackTrace(); - } - } - - @Test( expected = MojoExecutionException.class ) - public void validateExceptionThrownOnDuplicateURIs() throws MojoExecutionException - { - - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "foo", "foo", "foo" ); - final TransformSchema transformSchema2 = new TransformSchema( "foo", "bar", "bar" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - transformSchemas.add( transformSchema2 ); - - // Act & Assert - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "Two schemas with same URIs should yield a MojoExecutionException." ); - } - - @Test( expected = MojoExecutionException.class ) - public void validateExceptionThrownOnDuplicatePrefixes() throws MojoExecutionException - { - - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "foo", "foo", "foo" ); - final TransformSchema transformSchema2 = new TransformSchema( "bar", "foo", "bar" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - transformSchemas.add( transformSchema2 ); - - // Act & Assert - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "Two schemas with same Prefixes should yield a MojoExecutionException." ); - } - - @Test - public void validateNoExceptionThrownOnDuplicateNullPrefixes() - { - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "foo", null, "foo" ); - final TransformSchema transformSchema2 = new TransformSchema( "bar", null, "bar" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - transformSchemas.add( transformSchema2 ); - - // Act & Assert - try - { - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - } - catch ( MojoExecutionException e ) - { - Assert.fail( "Two schemas with null Prefix should not yield a MojoExecutionException." ); - } - } - - @Test - public void validateExceptionThrownOnDuplicateFiles() - { - - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "foo", "foo", "foo.xsd" ); - final TransformSchema transformSchema2 = new TransformSchema( "bar", "bar", "foo.xsd" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - transformSchemas.add( transformSchema2 ); - - // Act & Assert - try - { - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "Two schemas with same Files should yield a MojoExecutionException." ); - } - catch ( MojoExecutionException e ) - { - // Validate the error message. - String expectedMessage = "Misconfiguration detected: Duplicate 'file' property with value [foo.xsd] " + "found in plugin configuration. Correct schema elements index (0) and (1), " + "to ensure that all 'file' values are unique."; - Assert.assertEquals( expectedMessage, e.getLocalizedMessage() ); - } - } - - @Test( expected = MojoExecutionException.class ) - public void validateExceptionThrownOnOnlyUriGiven() throws MojoExecutionException - { - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "foo", null, "" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - - // Act & Assert - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "A schema definition with no prefix or file should yield a MojoExecutionException." ); - } - - @Test( expected = MojoExecutionException.class ) - public void validateExceptionThrownOnNullUri() throws MojoExecutionException - { - - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( null, "foo", "bar" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - - // Act & Assert - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "A schema definition with null URI should yield a MojoExecutionException." ); - } - - @Test( expected = MojoExecutionException.class ) - public void validateExceptionThrownOnEmptyUri() throws MojoExecutionException - { - - // Assemble - final TransformSchema transformSchema1 = new TransformSchema( "", "foo", "bar" ); - - final List transformSchemas = new ArrayList(); - transformSchemas.add( transformSchema1 ); - - // Act & Assert - XsdGeneratorHelper.validateSchemasInPluginConfiguration( transformSchemas ); - Assert.fail( "A schema definition with empty URI should yield a MojoExecutionException." ); - } - - @Test - public void validateProcessingNodes() - { - - // Assemble - final String newPrefix = "changedFoo"; - final String oldPrefix = "foo"; - final String originalXml = getXmlDocumentSample( oldPrefix ); - final String changedXml = getXmlDocumentSample( newPrefix ); - final NodeProcessor changeNamespacePrefixProcessor = new ChangeNamespacePrefixProcessor( oldPrefix, newPrefix ); - - // Act - final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( originalXml ) ); - XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, changeNamespacePrefixProcessor ); - - // Assert - final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( changedXml ) ); - final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() ); - diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() ); - - XMLAssert.assertXMLEqual( processedDocument, expectedDocument ); - } - - @Test - public void validateProcessingXSDsWithEnumerations() throws Exception - { - - // Assemble - final BufferingLog log = new BufferingLog(); - final JavaDocExtractor extractor = new JavaDocExtractor( log ); - extractor.setEncoding( "UTF-8" ); - - final String parentPath = "testdata/schemageneration/javadoc/enums/"; - final URL parentPathURL = getClass().getClassLoader().getResource( parentPath ); - Assert.assertNotNull( parentPathURL ); - - final File parentDir = new File( parentPathURL.getPath() ); - Assert.assertTrue( parentDir.exists() && parentDir.isDirectory() ); - - final List> excludeFilesMatching = new ArrayList>(); - excludeFilesMatching.add( new PatternFileFilter( Collections.singletonList( "\\.xsd" ) ) ); - Filters.initialize( log, excludeFilesMatching ); - - final List allSourceFiles = FileSystemUtilities.filterFiles( parentDir, null, parentDir.getAbsolutePath(), - log, "allJavaFiles", excludeFilesMatching ); - Assert.assertEquals( 3, allSourceFiles.size() ); - - final List urls = new ArrayList(); - for ( File current : allSourceFiles ) - { - try - { - urls.add( current.toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new IllegalArgumentException( - "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e ); - } - } - Assert.assertEquals( 3, urls.size() ); - - extractor.addSourceURLs( urls ); - final SearchableDocumentation docs = extractor.process(); - - // #1) The raw / un-processed XSD (containing the 'before' state) - // #2) The processed XSD (containing the 'expected' state) - final String rawEnumSchema = PropertyResources.readFully( parentPath + "rawEnumSchema.xsd" ); - final String processedEnumSchema = PropertyResources.readFully( parentPath + "processedEnumSchema.xsd" ); - final NodeProcessor enumProcessor = new XsdEnumerationAnnotationProcessor( docs, - new NoAuthorJavaDocRenderer() ); - - // Act - final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( rawEnumSchema ) ); - XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, enumProcessor ); - // System.out.println("Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument(processedDocument)); - - // Assert - final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( processedEnumSchema ) ); - final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() ); - diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() ); - - XMLAssert.assertXMLEqual( processedDocument, expectedDocument ); - } - - @Test - public void validateXmlDocumentationForWrappers() throws Exception - { - - // Assemble - final BufferingLog log = new BufferingLog(); - final JavaDocExtractor extractor = new JavaDocExtractor( log ); - extractor.setEncoding( "UTF-8" ); - - final String parentPath = "testdata/schemageneration/javadoc/xmlwrappers/"; - final URL parentPathURL = getClass().getClassLoader().getResource( parentPath ); - Assert.assertNotNull( parentPathURL ); - - final String schemaGenCreatedSchema = PropertyResources.readFully( parentPath + "expectedRawXmlWrappers.xsd" ); - - final File parentDir = new File( parentPathURL.getPath() ); - Assert.assertTrue( parentDir.exists() && parentDir.isDirectory() ); - - final List> excludeFilesMatching = new ArrayList>(); - excludeFilesMatching.add( new PatternFileFilter( Collections.singletonList( "\\.xsd" ) ) ); - Filters.initialize( log, excludeFilesMatching ); - - final List allSourceFiles = FileSystemUtilities.filterFiles( parentDir, null, parentDir.getAbsolutePath(), - log, "allJavaFiles", excludeFilesMatching ); - Assert.assertEquals( 2, allSourceFiles.size() ); - - final List urls = new ArrayList(); - for ( File current : allSourceFiles ) - { - try - { - urls.add( current.toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new IllegalArgumentException( - "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e ); - } - } - Assert.assertEquals( 2, urls.size() ); - - // Act - extractor.addSourceURLs( urls ); - final SearchableDocumentation docs = extractor.process(); - - final XsdAnnotationProcessor processor = new XsdAnnotationProcessor( docs, new NoAuthorJavaDocRenderer() ); - final Document schemaGenCreatedDocument = XsdGeneratorHelper.parseXmlStream( - new StringReader( schemaGenCreatedSchema ) ); - XsdGeneratorHelper.process( schemaGenCreatedDocument.getFirstChild(), true, processor ); - System.out.println( - "Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument( schemaGenCreatedDocument ) ); - - // Assert - } - - @Test - public void validateAcquiringFilenameToResolverMap() throws MojoExecutionException - { - - // Assemble - final String[] expectedFilenames = {"schema1.xsd", "schema2.xsd", "schema3.xsd"}; - final URL tmpUrl = getClass().getClassLoader().getResource( "generated/schema/schema1.xsd" ); - final File directory = new File( tmpUrl.getFile() ).getParentFile(); - - // Act - final Map fileNameToResolverMap = XsdGeneratorHelper.getFileNameToResolverMap( - directory ); - - // Assert - Assert.assertEquals( 3, fileNameToResolverMap.size() ); - for ( String current : expectedFilenames ) - { - Assert.assertTrue( fileNameToResolverMap.keySet().contains( current ) ); - } - - SimpleNamespaceResolver schema1Resolver = fileNameToResolverMap.get( "schema1.xsd" ); - Assert.assertEquals( "http://yet/another/namespace", schema1Resolver.getLocalNamespaceURI() ); - Assert.assertEquals( "schema1.xsd", schema1Resolver.getSourceFilename() ); - final Map schema1NamespaceURI2PrefixMap = schema1Resolver.getNamespaceURI2PrefixMap(); - Assert.assertEquals( 1, schema1NamespaceURI2PrefixMap.size() ); - Assert.assertEquals( "xs", schema1NamespaceURI2PrefixMap.get( "http://www.w3.org/2001/XMLSchema" ) ); - - SimpleNamespaceResolver schema2Resolver = fileNameToResolverMap.get( "schema2.xsd" ); - Assert.assertEquals( "http://some/namespace", schema2Resolver.getLocalNamespaceURI() ); - Assert.assertEquals( "schema2.xsd", schema2Resolver.getSourceFilename() ); - final Map schema2NamespaceURI2PrefixMap = schema2Resolver.getNamespaceURI2PrefixMap(); - Assert.assertEquals( 2, schema2NamespaceURI2PrefixMap.size() ); - Assert.assertEquals( "ns1", schema2NamespaceURI2PrefixMap.get( "http://another/namespace" ) ); - Assert.assertEquals( "xs", schema2NamespaceURI2PrefixMap.get( "http://www.w3.org/2001/XMLSchema" ) ); - - SimpleNamespaceResolver schema3Resolver = fileNameToResolverMap.get( "schema3.xsd" ); - Assert.assertEquals( "http://another/namespace", schema3Resolver.getLocalNamespaceURI() ); - Assert.assertEquals( "schema3.xsd", schema3Resolver.getSourceFilename() ); - final Map schema3NamespaceURI2PrefixMap = schema3Resolver.getNamespaceURI2PrefixMap(); - Assert.assertEquals( 3, schema3NamespaceURI2PrefixMap.size() ); - Assert.assertEquals( "ns2", schema3NamespaceURI2PrefixMap.get( "http://yet/another/namespace" ) ); - Assert.assertEquals( "ns1", schema3NamespaceURI2PrefixMap.get( "http://some/namespace" ) ); - Assert.assertEquals( "xs", schema3NamespaceURI2PrefixMap.get( "http://www.w3.org/2001/XMLSchema" ) ); - } - - // - // Private helpers - // - - private static DocumentBuilderFactory getDocumentBuilderFactory() - { - - final DocumentBuilderFactory toReturn = DocumentBuilderFactory.newInstance(); - toReturn.setNamespaceAware( true ); - return toReturn; - } - - private static DocumentBuilder getDocumentBuilder() - { - try - { - return getDocumentBuilderFactory().newDocumentBuilder(); - } - catch ( ParserConfigurationException e ) - { - throw new IllegalStateException( "Could not create DocumentBuilder", e ); - } - } - - private static Document createEmptyDocument( final DocumentBuilder builder ) - { - return builder.newDocument(); - } - - private String getXmlDocumentSample( final String namespace ) - { - return "\n" + "\n" + " \n" + " <" + namespace + ":aBar name=\"aFooElement\" />\n" + "\n"; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerFactory; + +import java.io.File; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.CodeSource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.maven.plugin.MojoExecutionException; +import org.codehaus.mojo.jaxb2.BufferingLog; +import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.AbstractSourceCodeAwareNodeProcessingTest; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocExtractor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.NoAuthorJavaDocRenderer; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SearchableDocumentation; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdAnnotationProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.XsdEnumerationAnnotationProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.ChangeNamespacePrefixProcessor; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.SimpleNamespaceResolver; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.TransformSchema; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.codehaus.mojo.jaxb2.shared.filters.Filter; +import org.codehaus.mojo.jaxb2.shared.filters.Filters; +import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.ElementNameAndAttributeQualifier; +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.w3c.dom.Document; +import se.jguru.shared.algorithms.api.resources.PropertyResources; + +/** + * @author Lennart Jörelid + */ +public class XsdGeneratorHelperTest { + + private static TransformerFactory factory; + + @BeforeClass + public static void setupSharedState() { + + // Configure XMLUnit. + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreAttributeOrder(true); + + // Configure the TransformerFactory + try { + + factory = TransformerFactory.newInstance(); + final CodeSource codeSource = + factory.getClass().getProtectionDomain().getCodeSource(); + + final String location = + codeSource == null ? "Unknown" : codeSource.getLocation().toString(); + System.out.println("-- Found TransformerFactory of type [" + + factory.getClass().getName() + "] loaded from [" + location + "]"); + + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + @Test(expected = MojoExecutionException.class) + public void validateExceptionThrownOnDuplicateURIs() throws MojoExecutionException { + + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("foo", "foo", "foo"); + final TransformSchema transformSchema2 = new TransformSchema("foo", "bar", "bar"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + transformSchemas.add(transformSchema2); + + // Act & Assert + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("Two schemas with same URIs should yield a MojoExecutionException."); + } + + @Test(expected = MojoExecutionException.class) + public void validateExceptionThrownOnDuplicatePrefixes() throws MojoExecutionException { + + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("foo", "foo", "foo"); + final TransformSchema transformSchema2 = new TransformSchema("bar", "foo", "bar"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + transformSchemas.add(transformSchema2); + + // Act & Assert + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("Two schemas with same Prefixes should yield a MojoExecutionException."); + } + + @Test + public void validateNoExceptionThrownOnDuplicateNullPrefixes() { + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("foo", null, "foo"); + final TransformSchema transformSchema2 = new TransformSchema("bar", null, "bar"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + transformSchemas.add(transformSchema2); + + // Act & Assert + try { + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + } catch (MojoExecutionException e) { + Assert.fail("Two schemas with null Prefix should not yield a MojoExecutionException."); + } + } + + @Test + public void validateExceptionThrownOnDuplicateFiles() { + + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("foo", "foo", "foo.xsd"); + final TransformSchema transformSchema2 = new TransformSchema("bar", "bar", "foo.xsd"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + transformSchemas.add(transformSchema2); + + // Act & Assert + try { + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("Two schemas with same Files should yield a MojoExecutionException."); + } catch (MojoExecutionException e) { + // Validate the error message. + String expectedMessage = "Misconfiguration detected: Duplicate 'file' property with value [foo.xsd] " + + "found in plugin configuration. Correct schema elements index (0) and (1), " + + "to ensure that all 'file' values are unique."; + Assert.assertEquals(expectedMessage, e.getLocalizedMessage()); + } + } + + @Test(expected = MojoExecutionException.class) + public void validateExceptionThrownOnOnlyUriGiven() throws MojoExecutionException { + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("foo", null, ""); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + + // Act & Assert + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("A schema definition with no prefix or file should yield a MojoExecutionException."); + } + + @Test(expected = MojoExecutionException.class) + public void validateExceptionThrownOnNullUri() throws MojoExecutionException { + + // Assemble + final TransformSchema transformSchema1 = new TransformSchema(null, "foo", "bar"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + + // Act & Assert + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("A schema definition with null URI should yield a MojoExecutionException."); + } + + @Test(expected = MojoExecutionException.class) + public void validateExceptionThrownOnEmptyUri() throws MojoExecutionException { + + // Assemble + final TransformSchema transformSchema1 = new TransformSchema("", "foo", "bar"); + + final List transformSchemas = new ArrayList(); + transformSchemas.add(transformSchema1); + + // Act & Assert + XsdGeneratorHelper.validateSchemasInPluginConfiguration(transformSchemas); + Assert.fail("A schema definition with empty URI should yield a MojoExecutionException."); + } + + @Test + public void validateProcessingNodes() { + + // Assemble + final String newPrefix = "changedFoo"; + final String oldPrefix = "foo"; + final String originalXml = getXmlDocumentSample(oldPrefix); + final String changedXml = getXmlDocumentSample(newPrefix); + final NodeProcessor changeNamespacePrefixProcessor = new ChangeNamespacePrefixProcessor(oldPrefix, newPrefix); + + // Act + final Document processedDocument = XsdGeneratorHelper.parseXmlStream(new StringReader(originalXml)); + XsdGeneratorHelper.process(processedDocument.getFirstChild(), true, changeNamespacePrefixProcessor); + + // Assert + final Document expectedDocument = XsdGeneratorHelper.parseXmlStream(new StringReader(changedXml)); + final Diff diff = new Diff(expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier()); + diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); + + XMLAssert.assertXMLEqual(processedDocument, expectedDocument); + } + + @Test + public void validateProcessingXSDsWithEnumerations() throws Exception { + + // Assemble + final BufferingLog log = new BufferingLog(); + final JavaDocExtractor extractor = new JavaDocExtractor(log); + extractor.setEncoding("UTF-8"); + + final String parentPath = "testdata/schemageneration/javadoc/enums/"; + final URL parentPathURL = getClass().getClassLoader().getResource(parentPath); + Assert.assertNotNull(parentPathURL); + + final File parentDir = new File(parentPathURL.getPath()); + Assert.assertTrue(parentDir.exists() && parentDir.isDirectory()); + + final List> excludeFilesMatching = new ArrayList>(); + excludeFilesMatching.add(new PatternFileFilter(Collections.singletonList("\\.xsd"))); + Filters.initialize(log, excludeFilesMatching); + + final List allSourceFiles = FileSystemUtilities.filterFiles( + parentDir, null, parentDir.getAbsolutePath(), log, "allJavaFiles", excludeFilesMatching); + Assert.assertEquals(3, allSourceFiles.size()); + + final List urls = new ArrayList(); + for (File current : allSourceFiles) { + try { + urls.add(current.toURI().toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException( + "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e); + } + } + Assert.assertEquals(3, urls.size()); + + extractor.addSourceURLs(urls); + final SearchableDocumentation docs = extractor.process(); + + // #1) The raw / un-processed XSD (containing the 'before' state) + // #2) The processed XSD (containing the 'expected' state) + final String rawEnumSchema = PropertyResources.readFully(parentPath + "rawEnumSchema.xsd"); + final String processedEnumSchema = PropertyResources.readFully(parentPath + "processedEnumSchema.xsd"); + final NodeProcessor enumProcessor = new XsdEnumerationAnnotationProcessor(docs, new NoAuthorJavaDocRenderer()); + + // Act + final Document processedDocument = XsdGeneratorHelper.parseXmlStream(new StringReader(rawEnumSchema)); + XsdGeneratorHelper.process(processedDocument.getFirstChild(), true, enumProcessor); + // System.out.println("Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument(processedDocument)); + + // Assert + final Document expectedDocument = XsdGeneratorHelper.parseXmlStream(new StringReader(processedEnumSchema)); + final Diff diff = new Diff(expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier()); + diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); + + XMLAssert.assertXMLEqual(processedDocument, expectedDocument); + } + + @Test + public void validateXmlDocumentationForWrappers() throws Exception { + + // Assemble + final BufferingLog log = new BufferingLog(); + final JavaDocExtractor extractor = new JavaDocExtractor(log); + extractor.setEncoding("UTF-8"); + + final String parentPath = "testdata/schemageneration/javadoc/xmlwrappers/"; + final URL parentPathURL = getClass().getClassLoader().getResource(parentPath); + Assert.assertNotNull(parentPathURL); + + final String schemaGenCreatedSchema = PropertyResources.readFully(parentPath + "expectedRawXmlWrappers.xsd"); + + final File parentDir = new File(parentPathURL.getPath()); + Assert.assertTrue(parentDir.exists() && parentDir.isDirectory()); + + final List> excludeFilesMatching = new ArrayList>(); + excludeFilesMatching.add(new PatternFileFilter(Collections.singletonList("\\.xsd"))); + Filters.initialize(log, excludeFilesMatching); + + final List allSourceFiles = FileSystemUtilities.filterFiles( + parentDir, null, parentDir.getAbsolutePath(), log, "allJavaFiles", excludeFilesMatching); + Assert.assertEquals(2, allSourceFiles.size()); + + final List urls = new ArrayList(); + for (File current : allSourceFiles) { + try { + urls.add(current.toURI().toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException( + "Could not convert file [" + current.getAbsolutePath() + "] to a URL", e); + } + } + Assert.assertEquals(2, urls.size()); + + // Act + extractor.addSourceURLs(urls); + final SearchableDocumentation docs = extractor.process(); + + final XsdAnnotationProcessor processor = new XsdAnnotationProcessor(docs, new NoAuthorJavaDocRenderer()); + final Document schemaGenCreatedDocument = + XsdGeneratorHelper.parseXmlStream(new StringReader(schemaGenCreatedSchema)); + XsdGeneratorHelper.process(schemaGenCreatedDocument.getFirstChild(), true, processor); + System.out.println("Got: " + AbstractSourceCodeAwareNodeProcessingTest.printDocument(schemaGenCreatedDocument)); + + // Assert + } + + @Test + public void validateAcquiringFilenameToResolverMap() throws MojoExecutionException { + + // Assemble + final String[] expectedFilenames = {"schema1.xsd", "schema2.xsd", "schema3.xsd"}; + final URL tmpUrl = getClass().getClassLoader().getResource("generated/schema/schema1.xsd"); + final File directory = new File(tmpUrl.getFile()).getParentFile(); + + // Act + final Map fileNameToResolverMap = + XsdGeneratorHelper.getFileNameToResolverMap(directory); + + // Assert + Assert.assertEquals(3, fileNameToResolverMap.size()); + for (String current : expectedFilenames) { + Assert.assertTrue(fileNameToResolverMap.keySet().contains(current)); + } + + SimpleNamespaceResolver schema1Resolver = fileNameToResolverMap.get("schema1.xsd"); + Assert.assertEquals("http://yet/another/namespace", schema1Resolver.getLocalNamespaceURI()); + Assert.assertEquals("schema1.xsd", schema1Resolver.getSourceFilename()); + final Map schema1NamespaceURI2PrefixMap = schema1Resolver.getNamespaceURI2PrefixMap(); + Assert.assertEquals(1, schema1NamespaceURI2PrefixMap.size()); + Assert.assertEquals("xs", schema1NamespaceURI2PrefixMap.get("http://www.w3.org/2001/XMLSchema")); + + SimpleNamespaceResolver schema2Resolver = fileNameToResolverMap.get("schema2.xsd"); + Assert.assertEquals("http://some/namespace", schema2Resolver.getLocalNamespaceURI()); + Assert.assertEquals("schema2.xsd", schema2Resolver.getSourceFilename()); + final Map schema2NamespaceURI2PrefixMap = schema2Resolver.getNamespaceURI2PrefixMap(); + Assert.assertEquals(2, schema2NamespaceURI2PrefixMap.size()); + Assert.assertEquals("ns1", schema2NamespaceURI2PrefixMap.get("http://another/namespace")); + Assert.assertEquals("xs", schema2NamespaceURI2PrefixMap.get("http://www.w3.org/2001/XMLSchema")); + + SimpleNamespaceResolver schema3Resolver = fileNameToResolverMap.get("schema3.xsd"); + Assert.assertEquals("http://another/namespace", schema3Resolver.getLocalNamespaceURI()); + Assert.assertEquals("schema3.xsd", schema3Resolver.getSourceFilename()); + final Map schema3NamespaceURI2PrefixMap = schema3Resolver.getNamespaceURI2PrefixMap(); + Assert.assertEquals(3, schema3NamespaceURI2PrefixMap.size()); + Assert.assertEquals("ns2", schema3NamespaceURI2PrefixMap.get("http://yet/another/namespace")); + Assert.assertEquals("ns1", schema3NamespaceURI2PrefixMap.get("http://some/namespace")); + Assert.assertEquals("xs", schema3NamespaceURI2PrefixMap.get("http://www.w3.org/2001/XMLSchema")); + } + + // + // Private helpers + // + + private static DocumentBuilderFactory getDocumentBuilderFactory() { + + final DocumentBuilderFactory toReturn = DocumentBuilderFactory.newInstance(); + toReturn.setNamespaceAware(true); + return toReturn; + } + + private static DocumentBuilder getDocumentBuilder() { + try { + return getDocumentBuilderFactory().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new IllegalStateException("Could not create DocumentBuilder", e); + } + } + + private static Document createEmptyDocument(final DocumentBuilder builder) { + return builder.newDocument(); + } + + private String getXmlDocumentSample(final String namespace) { + return "\n" + + "\n" + + " \n" + " <" + + namespace + ":aBar name=\"aFooElement\" />\n" + "\n"; + } +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/AbstractSourceCodeAwareNodeProcessingTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/AbstractSourceCodeAwareNodeProcessingTest.java index 26e7c5c1..ad33a09e 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/AbstractSourceCodeAwareNodeProcessingTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/AbstractSourceCodeAwareNodeProcessingTest.java @@ -1,23 +1,5 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.BufferingLog; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.codehaus.mojo.jaxb2.shared.Validate; -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.XMLUnit; -import org.junit.Assert; -import org.junit.Before; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.SchemaOutputResolver; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; @@ -25,6 +7,7 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -39,6 +22,24 @@ import java.util.SortedMap; import java.util.TreeMap; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.SchemaOutputResolver; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.BufferingLog; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.NodeProcessor; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.codehaus.mojo.jaxb2.shared.Validate; +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Before; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -101,8 +102,7 @@ public final void setupSharedState() throws Exception { try { jaxbContext.generateSchema(new SchemaOutputResolver() { @Override - public Result createOutput(final String namespaceUri, - final String suggestedFileName) + public Result createOutput(final String namespaceUri, final String suggestedFileName) throws IOException { // As put in the XmlBinding JAXB implementation of Nazgul Core: @@ -110,8 +110,8 @@ public Result createOutput(final String namespaceUri, // "The types should really be annotated with @XmlType(namespace = "... something ...") // to avoid using the default ("") namespace". if (namespaceUri.isEmpty()) { - xsdGenerationWarnings.add("Got empty namespaceUri for suggestedFileName [" - + suggestedFileName + "]."); + xsdGenerationWarnings.add( + "Got empty namespaceUri for suggestedFileName [" + suggestedFileName + "]."); } // Create the result Writer @@ -138,7 +138,8 @@ public Result createOutput(final String namespaceUri, // Store all generated XSDs for (Map.Entry current : tmpSchemaMap.entrySet()) { - namespace2GeneratedSchemaMap.put(current.getKey(), current.getValue().toString()); + namespace2GeneratedSchemaMap.put( + current.getKey(), current.getValue().toString()); } // Create XML Documents for all generated Schemas @@ -252,7 +253,7 @@ protected void onAcceptedNode(final Node aNode) { // name="firstName" final Node nameAttribute = aNode.getAttributes().getNamedItem("name"); - if(nameAttribute != null) { + if (nameAttribute != null) { final String nodeName = nameAttribute.getNodeValue(); log.info("Accepted node [" + aNode.getNodeName() + "] " + nodeName); @@ -286,8 +287,7 @@ protected static String readFully(final String path) { try { // Will produce a NPE if the path was not directed to a file. - final InputStream resource = AbstractSourceCodeAwareNodeProcessingTest - .class + final InputStream resource = AbstractSourceCodeAwareNodeProcessingTest.class .getClassLoader() .getResourceAsStream(path); final BufferedReader tmp = new BufferedReader(new InputStreamReader(resource)); @@ -312,8 +312,8 @@ protected static String readFully(final String path) { * @throws org.xml.sax.SAXException If a SAXException was raised during parsing of the two Documents. * @throws IOException If an I/O-related exception was raised while acquiring the data from the Readers. */ - protected static Diff compareXmlIgnoringWhitespace(final String expected, final String actual) throws SAXException, - IOException { + protected static Diff compareXmlIgnoringWhitespace(final String expected, final String actual) + throws SAXException, IOException { // Check sanity Validate.notNull(expected, "Cannot handle null expected argument."); @@ -344,7 +344,8 @@ private List resolveSourceFiles() { .replace("/", ".") .replace(File.separator, "."); - if (transmutedCanonicalPath.contains(currentClass.getPackage().getName())) { + if (transmutedCanonicalPath.contains( + currentClass.getPackage().getName())) { toReturn.add(current); } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelperTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelperTest.java index 79bd23bd..120341e9 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelperTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelperTest.java @@ -1,5 +1,11 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; import org.junit.Assert; import org.junit.Test; @@ -9,12 +15,6 @@ import org.w3c.dom.NodeList; import se.jguru.shared.algorithms.api.resources.PropertyResources; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -34,16 +34,17 @@ public void validateDomHelperAccessors() throws Exception { // Act final List enumElements = new ArrayList(); final NodeList childNodes = restrictionElement.getChildNodes(); - for(int i = 0; i < childNodes.getLength(); i++) { + for (int i = 0; i < childNodes.getLength(); i++) { final Node current = childNodes.item(i); - if(current.getNodeType() == Node.ELEMENT_NODE && current.getLocalName().equals("enumeration")) { + if (current.getNodeType() == Node.ELEMENT_NODE + && current.getLocalName().equals("enumeration")) { enumElements.add((Element) current); } } final Map xpath2ValueMap = new TreeMap(); - for(Element current : enumElements) { + for (Element current : enumElements) { final String currentXPath = DomHelper.getXPathFor(current); xpath2ValueMap.put(currentXPath, DomHelper.getValueAttribute(current)); } @@ -52,8 +53,8 @@ public void validateDomHelperAccessors() throws Exception { Assert.assertNotNull(xpath2ValueMap); Assert.assertEquals(3, xpath2ValueMap.size()); - final String prefix ="#document/xs:schema/xs:simpleType[@name='foodPreference']/" + - "xs:restriction/xs:enumeration[@value='"; + final String prefix = + "#document/xs:schema/xs:simpleType[@name='foodPreference']/" + "xs:restriction/xs:enumeration[@value='"; Assert.assertEquals("LACTO_VEGETARIAN", xpath2ValueMap.get(prefix + "LACTO_VEGETARIAN']")); Assert.assertEquals("NONE", xpath2ValueMap.get(prefix + "NONE']")); @@ -75,7 +76,7 @@ private Element getChildOf(final Element parent, final String localName, final S final String currentLocalName = current.getLocalName(); final String nameAttribute = DomHelper.getNameAttribute(current); - if(currentLocalName.equals(localName) && (name == null || name.equals(nameAttribute))) { + if (currentLocalName.equals(localName) && (name == null || name.equals(nameAttribute))) { return (Element) current; } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/FieldLocationTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/FieldLocationTest.java index 6841d75e..082b6c7f 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/FieldLocationTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/FieldLocationTest.java @@ -1,18 +1,18 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.TreeMap; + +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement.XmlNameAnnotatedClassWithFieldAccess; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlType; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.TreeMap; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -27,12 +27,11 @@ public void setupSharedState() { fieldName2MethodMap = new TreeMap(); theClass = XmlNameAnnotatedClassWithFieldAccess.class; - for(Field current : theClass.getDeclaredFields()) { + for (Field current : theClass.getDeclaredFields()) { final String currentName = current.getName(); fieldName2MethodMap.put(currentName, current); } - } @Test @@ -45,8 +44,10 @@ public void validateFieldLocationWithXmlName() throws Exception { final Field integerField = fieldName2MethodMap.get("integerField"); final Field stringField = fieldName2MethodMap.get("stringField"); - final String integerFieldXmlName = integerField.getAnnotation(XmlAttribute.class).name(); - final String stringFieldXmlName = stringField.getAnnotation(XmlElement.class).name(); + final String integerFieldXmlName = + integerField.getAnnotation(XmlAttribute.class).name(); + final String stringFieldXmlName = + stringField.getAnnotation(XmlElement.class).name(); final String expectedIntegerFieldPath = packageName + "." + classXmlName + "#" + integerFieldXmlName; final String expectedStringFieldPath = packageName + "." + classXmlName + "#" + stringFieldXmlName; @@ -57,18 +58,10 @@ public void validateFieldLocationWithXmlName() throws Exception { // Act final FieldLocation integerFieldLocation = new FieldLocation( - packageName, - theClass.getSimpleName(), - classXmlName, - integerField.getName(), - integerFieldXmlName); + packageName, theClass.getSimpleName(), classXmlName, integerField.getName(), integerFieldXmlName); final FieldLocation stringFieldLocation = new FieldLocation( - packageName, - theClass.getSimpleName(), - classXmlName, - stringField.getName(), - stringFieldXmlName); + packageName, theClass.getSimpleName(), classXmlName, stringField.getName(), stringFieldXmlName); // Assert Assert.assertEquals(expectedIntegerFieldPath, integerFieldLocation.getPath()); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java index 05348847..6c05b169 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java @@ -1,5 +1,15 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; @@ -12,18 +22,8 @@ import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; import org.junit.Assert; import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; import org.junit.Ignore; +import org.junit.Test; /** * @author Lennart Jörelid, jGuru Europe AB @@ -43,27 +43,21 @@ public void setupSharedState() { log = new BufferingLog(BufferingLog.LogLevel.DEBUG); // Find the desired directory - final URL dirURL = getClass() - .getClassLoader() - .getResource("testdata/schemageneration/javadoc/basic"); + final URL dirURL = getClass().getClassLoader().getResource("testdata/schemageneration/javadoc/basic"); this.javaDocBasicDir = new File(dirURL.getPath()); Assert.assertTrue(javaDocBasicDir.exists() && javaDocBasicDir.isDirectory()); - final URL annotatedDirURL = getClass() - .getClassLoader() - .getResource("testdata/schemageneration/javadoc/annotated"); + final URL annotatedDirURL = + getClass().getClassLoader().getResource("testdata/schemageneration/javadoc/annotated"); this.javaDocAnnotatedDir = new File(annotatedDirURL.getPath()); Assert.assertTrue(javaDocAnnotatedDir.exists() && javaDocAnnotatedDir.isDirectory()); - final URL enumsDirURL = getClass() - .getClassLoader() - .getResource("testdata/schemageneration/javadoc/enums"); + final URL enumsDirURL = getClass().getClassLoader().getResource("testdata/schemageneration/javadoc/enums"); this.javaDocEnumsDir = new File(enumsDirURL.getPath()); Assert.assertTrue(javaDocEnumsDir.exists() && javaDocEnumsDir.isDirectory()); - final URL wrappersDirURL = getClass() - .getClassLoader() - .getResource("testdata/schemageneration/javadoc/xmlwrappers"); + final URL wrappersDirURL = + getClass().getClassLoader().getResource("testdata/schemageneration/javadoc/xmlwrappers"); this.javaDocXmlWrappersDir = new File(wrappersDirURL.getPath()); Assert.assertTrue(javaDocXmlWrappersDir.exists() && javaDocXmlWrappersDir.isDirectory()); } @@ -96,14 +90,16 @@ public void validateLogStatementsDuringProcessing() { Assert.assertEquals("001: (INFO) Processing [1] java sources.", keys.get(1)); Assert.assertEquals("002: (DEBUG) Added package-level JavaDoc for [basic]", keys.get(2)); Assert.assertEquals("003: (DEBUG) Added class-level JavaDoc for [basic.NodeProcessor]", keys.get(3)); - Assert.assertEquals("004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)]", + Assert.assertEquals( + "004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)]", keys.get(4)); - Assert.assertEquals("005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]", + Assert.assertEquals( + "005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]", keys.get(5)); } @Test - @Ignore + @Ignore public void validateExtractingXmlAnnotatedName() throws Exception { // Assemble @@ -133,18 +129,26 @@ public void validateExtractingXmlAnnotatedName() throws Exception { Assert.assertEquals("annotatedStringField", stringFieldLocation.getAnnotationRenamedTo()); Assert.assertEquals("annotatedIntegerField", integerFieldLocation.getAnnotationRenamedTo()); - Assert.assertEquals(JavaDocData.NO_COMMENT, result.getJavaDoc(stringMethodLocation.getPath()).getComment()); - Assert.assertEquals(JavaDocData.NO_COMMENT, result.getJavaDoc(integerMethodLocation.getPath()).getComment()); - Assert.assertEquals("This is a string field.", result.getJavaDoc(stringFieldLocation.getPath()).getComment()); - Assert.assertEquals("This is an integer field.", + Assert.assertEquals( + JavaDocData.NO_COMMENT, + result.getJavaDoc(stringMethodLocation.getPath()).getComment()); + Assert.assertEquals( + JavaDocData.NO_COMMENT, + result.getJavaDoc(integerMethodLocation.getPath()).getComment()); + Assert.assertEquals( + "This is a string field.", + result.getJavaDoc(stringFieldLocation.getPath()).getComment()); + Assert.assertEquals( + "This is an integer field.", result.getJavaDoc(integerFieldLocation.getPath()).getComment()); // Secondly, check the method-annotated class. final SortableLocation stringFieldLocation2 = result.getLocation(methodAccessPrefix + "stringField"); final SortableLocation integerFieldLocation2 = result.getLocation(methodAccessPrefix + "integerField"); - final SortableLocation stringMethodLocation2 = result.getLocation(methodAccessPrefix + "annotatedStringMethod()"); - final SortableLocation integerMethodLocation2 = result.getLocation(methodAccessPrefix + - "annotatedIntegerMethod()"); + final SortableLocation stringMethodLocation2 = + result.getLocation(methodAccessPrefix + "annotatedStringMethod()"); + final SortableLocation integerMethodLocation2 = + result.getLocation(methodAccessPrefix + "annotatedIntegerMethod()"); Assert.assertTrue(stringFieldLocation2 instanceof FieldLocation); Assert.assertTrue(integerFieldLocation2 instanceof FieldLocation); @@ -156,13 +160,17 @@ public void validateExtractingXmlAnnotatedName() throws Exception { Assert.assertEquals("annotatedStringMethod", stringMethodLocation2.getAnnotationRenamedTo()); Assert.assertEquals("annotatedIntegerMethod", integerMethodLocation2.getAnnotationRenamedTo()); - Assert.assertEquals("Getter for the stringField.", + Assert.assertEquals( + "Getter for the stringField.", result.getJavaDoc(stringMethodLocation2.getPath()).getComment()); - Assert.assertEquals("Getter for the integerField.", + Assert.assertEquals( + "Getter for the integerField.", result.getJavaDoc(integerMethodLocation2.getPath()).getComment()); - Assert.assertEquals(JavaDocData.NO_COMMENT, + Assert.assertEquals( + JavaDocData.NO_COMMENT, result.getJavaDoc(stringFieldLocation2.getPath()).getComment()); - Assert.assertEquals(JavaDocData.NO_COMMENT, + Assert.assertEquals( + JavaDocData.NO_COMMENT, result.getJavaDoc(integerFieldLocation2.getPath()).getComment()); } @@ -174,9 +182,7 @@ public void validateJavaDocsForXmlEnumsAreCorrectlyApplied() { final JavaDocExtractor unitUnderTest = new JavaDocExtractor(log); // Act - final SearchableDocumentation result = getSearchableDocumentationFor(unitUnderTest, - 3, - javaDocEnumsDir); + final SearchableDocumentation result = getSearchableDocumentationFor(unitUnderTest, 3, javaDocEnumsDir); final MapWrapper mapWrapper = new MapWrapper(result); // Assert @@ -205,43 +211,32 @@ public void validateJavaDocsForXmlEnumsAreCorrectlyApplied() { "enums.FoodPreference#meatEater", "enums.FoodPreference#milkDrinker"); for (String current : paths) { - Assert.assertTrue("Required path [" + current + "] not found.", + Assert.assertTrue( + "Required path [" + current + "] not found.", mapWrapper.path2LocationMap.keySet().contains(current.trim())); } // Finally, validate that the injected XML document comments // match the expected/corresponding JavaDoc comments. mapWrapper.validateJavaDocCommentText( - "Simple enumeration example defining some Food preferences.", - "enums.FoodPreference"); + "Simple enumeration example defining some Food preferences.", "enums.FoodPreference"); mapWrapper.validateJavaDocCommentText( - "No special food preferences; eats everything.", - "enums.FoodPreference#NONE"); + "No special food preferences; eats everything.", "enums.FoodPreference#NONE"); mapWrapper.validateJavaDocCommentText( - "Vegan who will neither eat meats nor drink milk.", - "enums.FoodPreference#VEGAN"); + "Vegan who will neither eat meats nor drink milk.", "enums.FoodPreference#VEGAN"); mapWrapper.validateJavaDocCommentText( - "Vegetarian who will not eat meats, but drinks milk.", - "enums.FoodPreference#LACTO_VEGETARIAN"); + "Vegetarian who will not eat meats, but drinks milk.", "enums.FoodPreference#LACTO_VEGETARIAN"); - mapWrapper.validateJavaDocCommentText( - "A Penny, worth 1 cent.", - "enums.AmericanCoin#1"); + mapWrapper.validateJavaDocCommentText("A Penny, worth 1 cent.", "enums.AmericanCoin#1"); - mapWrapper.validateJavaDocCommentText( - "A Nickel, worth 5 cents.", - "enums.AmericanCoin#5"); + mapWrapper.validateJavaDocCommentText("A Nickel, worth 5 cents.", "enums.AmericanCoin#5"); - mapWrapper.validateJavaDocCommentText( - "A Dime, worth 10 cents.", - "enums.AmericanCoin#10"); + mapWrapper.validateJavaDocCommentText("A Dime, worth 10 cents.", "enums.AmericanCoin#10"); - mapWrapper.validateJavaDocCommentText( - "A Quarter, worth 25 cents.", - "enums.AmericanCoin#25"); + mapWrapper.validateJavaDocCommentText("A Quarter, worth 25 cents.", "enums.AmericanCoin#25"); } @Test @@ -260,7 +255,8 @@ public void validateJavaDocsForXmlWrapperAnnotatedFieldsAndMethodsAreCorrectlyAp final String packagePrefix = "org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.wrappers"; final List paths = new ArrayList(); - for (String current : Arrays.asList("", + for (String current : Arrays.asList( + "", ".ExampleXmlWrapperUsingFieldAccess", ".ExampleXmlWrapperUsingFieldAccess#foobar", ".ExampleXmlWrapperUsingFieldAccess#getIntegerSet()", @@ -275,20 +271,22 @@ public void validateJavaDocsForXmlWrapperAnnotatedFieldsAndMethodsAreCorrectlyAp } for (String current : paths) { - Assert.assertTrue("Required path [" + current + "] not found.", + Assert.assertTrue( + "Required path [" + current + "] not found.", mapWrapper.path2LocationMap.keySet().contains(current.trim())); } - mapWrapper.validateJavaDocCommentText("List containing some strings.", - packagePrefix + ".ExampleXmlWrapperUsingFieldAccess#foobar"); + mapWrapper.validateJavaDocCommentText( + "List containing some strings.", packagePrefix + ".ExampleXmlWrapperUsingFieldAccess#foobar"); - mapWrapper.validateJavaDocCommentText("SortedSet containing Integers.", - packagePrefix + ".ExampleXmlWrapperUsingFieldAccess#integerSet"); + mapWrapper.validateJavaDocCommentText( + "SortedSet containing Integers.", packagePrefix + ".ExampleXmlWrapperUsingFieldAccess#integerSet"); - mapWrapper.validateJavaDocCommentText("List containing some methodStrings.", - packagePrefix + ".ExampleXmlWrapperUsingMethodAccess#foobar()"); + mapWrapper.validateJavaDocCommentText( + "List containing some methodStrings.", packagePrefix + ".ExampleXmlWrapperUsingMethodAccess#foobar()"); - mapWrapper.validateJavaDocCommentText("SortedSet containing Integers.", + mapWrapper.validateJavaDocCommentText( + "SortedSet containing Integers.", packagePrefix + ".ExampleXmlWrapperUsingMethodAccess#getMethodIntegerSet()"); } @@ -302,7 +300,8 @@ public void validatePathsFromProcessing() { final SearchableDocumentation result = getSearchableDocumentationFor(unitUnderTest, 1, javaDocBasicDir); // Assert - final ArrayList sortableLocations = new ArrayList(result.getAll().keySet()); + final ArrayList sortableLocations = + new ArrayList(result.getAll().keySet()); Assert.assertEquals(4, sortableLocations.size()); final List paths = new ArrayList(result.getPaths()); @@ -332,11 +331,11 @@ public void validateJavaDocDataFromProcessing() { // Assert /* - +================= - | Comment: - | No JavaDoc tags. - +================= - */ + +================= + | Comment: + | No JavaDoc tags. + +================= + */ final SortableLocation packageLocation = result.getLocation(basicPackagePath); final JavaDocData basicPackageJavaDoc = result.getJavaDoc(basicPackagePath); Assert.assertTrue(packageLocation instanceof PackageLocation); @@ -347,13 +346,13 @@ public void validateJavaDocDataFromProcessing() { Assert.assertEquals(0, basicPackageJavaDoc.getTag2ValueMap().size()); /* - +================= - | Comment: Processor/visitor pattern specification for DOM Nodes. - | 2 JavaDoc tags ... - | author: Lennart Jörelid, Mr. Foo - | see: org.w3c.dom.Node - +================= - */ + +================= + | Comment: Processor/visitor pattern specification for DOM Nodes. + | 2 JavaDoc tags ... + | author: Lennart Jörelid, Mr. Foo + | see: org.w3c.dom.Node + +================= + */ final SortableLocation classLocation = result.getLocation(nodeProcessorClassPath); final JavaDocData nodeProcessorClassJavaDoc = result.getJavaDoc(nodeProcessorClassPath); Assert.assertTrue(classLocation instanceof ClassLocation); @@ -361,24 +360,23 @@ public void validateJavaDocDataFromProcessing() { final ClassLocation castClassLocation = (ClassLocation) classLocation; Assert.assertEquals("basic", castClassLocation.getPackageName()); Assert.assertEquals("NodeProcessor", castClassLocation.getClassName()); - Assert.assertEquals("Processor/visitor pattern specification for DOM Nodes.", - nodeProcessorClassJavaDoc.getComment()); - + Assert.assertEquals( + "Processor/visitor pattern specification for DOM Nodes.", nodeProcessorClassJavaDoc.getComment()); final SortedMap classTag2ValueMap = nodeProcessorClassJavaDoc.getTag2ValueMap(); Assert.assertEquals(2, classTag2ValueMap.size()); Assert.assertEquals("org.w3c.dom.Node", classTag2ValueMap.get("see")); - Assert.assertEquals("Lennart Jörelid, Mr. Foo", - classTag2ValueMap.get("author")); + Assert.assertEquals( + "Lennart Jörelid, Mr. Foo", classTag2ValueMap.get("author")); /* - +================= - | Comment: Defines if this visitor should process the provided node. - | 2 JavaDoc tags ... - | param: aNode The DOM node to process. - | return: true if the provided Node should be processed by this NodeProcessor. - +================= - */ + +================= + | Comment: Defines if this visitor should process the provided node. + | 2 JavaDoc tags ... + | param: aNode The DOM node to process. + | return: true if the provided Node should be processed by this NodeProcessor. + +================= + */ final SortableLocation acceptMethodLocation = result.getLocation(acceptMethodPath); final JavaDocData acceptMethodClassJavaDoc = result.getJavaDoc(acceptMethodPath); Assert.assertTrue(acceptMethodLocation instanceof MethodLocation); @@ -387,13 +385,14 @@ public void validateJavaDocDataFromProcessing() { Assert.assertEquals("basic", castMethodLocation.getPackageName()); Assert.assertEquals("NodeProcessor", castMethodLocation.getClassName()); Assert.assertEquals("(org.w3c.dom.Node)", castMethodLocation.getParametersAsString()); - Assert.assertEquals("Defines if this visitor should process the provided node.", - acceptMethodClassJavaDoc.getComment()); + Assert.assertEquals( + "Defines if this visitor should process the provided node.", acceptMethodClassJavaDoc.getComment()); final SortedMap methodTag2ValueMap = acceptMethodClassJavaDoc.getTag2ValueMap(); Assert.assertEquals(2, methodTag2ValueMap.size()); Assert.assertEquals("aNode The DOM node to process.", methodTag2ValueMap.get("param")); - Assert.assertEquals("true if the provided Node should be processed by this NodeProcessor.", + Assert.assertEquals( + "true if the provided Node should be processed by this NodeProcessor.", methodTag2ValueMap.get("return")); } @@ -445,10 +444,7 @@ public void validateJavaDocCommentText(final String expected, final String path) } } - private void validateJavaDocCommentText( - final MapWrapper wrapper, - final String expected, - final String path) { + private void validateJavaDocCommentText(final MapWrapper wrapper, final String expected, final String path) { final SortableLocation sortableLocation = wrapper.path2LocationMap.get(path); final JavaDocData xmlWrapperJavaDocData = wrapper.sortableLocations2JavaDocDataMap.get(sortableLocation); @@ -457,9 +453,10 @@ private void validateJavaDocCommentText( Assert.assertEquals(expected, xmlWrapperJavaDocData.getComment()); } - private SearchableDocumentation getSearchableDocumentationFor(final JavaDocExtractor unitUnderTest, - final int expectedNumberOfFiles, - final File... sourceFileDirectories) { + private SearchableDocumentation getSearchableDocumentationFor( + final JavaDocExtractor unitUnderTest, + final int expectedNumberOfFiles, + final File... sourceFileDirectories) { // Ensure that the encoding is correctly set unitUnderTest.setEncoding("UTF-8"); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SemiDocumentedClass.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SemiDocumentedClass.java index 657f0426..b0da547c 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SemiDocumentedClass.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SemiDocumentedClass.java @@ -31,7 +31,9 @@ * @author Lennart Jörelid, jGuru Europe AB */ @XmlRootElement -@XmlType(namespace = SomewhatNamedPerson.NAMESPACE, propOrder = {"documented", "unDocumented"}) +@XmlType( + namespace = SomewhatNamedPerson.NAMESPACE, + propOrder = {"documented", "unDocumented"}) @XmlAccessorType(XmlAccessType.FIELD) public class SemiDocumentedClass { @@ -52,8 +54,7 @@ public class SemiDocumentedClass { /** * JAXB-friendly constructor. */ - public SemiDocumentedClass() { - } + public SemiDocumentedClass() {} public String getDocumented() { return documented; diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SomewhatNamedPerson.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SomewhatNamedPerson.java index 94f62924..b61b7ed7 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SomewhatNamedPerson.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/SomewhatNamedPerson.java @@ -19,14 +19,13 @@ * under the License. */ -import org.codehaus.mojo.jaxb2.shared.Validate; - import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; +import org.codehaus.mojo.jaxb2.shared.Validate; /** * Definition of a person with lastName and age, and optionally a firstName as well... @@ -35,7 +34,9 @@ * @since Some version. */ @XmlRootElement -@XmlType(namespace = SomewhatNamedPerson.NAMESPACE, propOrder = {"firstName", "lastName", "age"}) +@XmlType( + namespace = SomewhatNamedPerson.NAMESPACE, + propOrder = {"firstName", "lastName", "age"}) @XmlAccessorType(XmlAccessType.FIELD) public class SomewhatNamedPerson { @@ -65,8 +66,7 @@ public class SomewhatNamedPerson { /** * JAXB-friendly constructor. */ - public SomewhatNamedPerson() { - } + public SomewhatNamedPerson() {} /** * Creates a SomewhatNamedPerson wrapping the supplied data. diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorSemiDocumentedTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorSemiDocumentedTest.java index f64bf218..b2984531 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorSemiDocumentedTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorSemiDocumentedTest.java @@ -1,13 +1,13 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.util.Arrays; +import java.util.List; + import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; -import java.util.Arrays; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorTest.java index fe981bef..29a7125f 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdAnnotationProcessorTest.java @@ -1,14 +1,14 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.util.Arrays; +import java.util.List; + import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.wrappers.ExampleXmlWrapper; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; -import java.util.Arrays; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessorTest.java index f474edcf..a51e09fb 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/XsdEnumerationAnnotationProcessorTest.java @@ -1,5 +1,8 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; +import java.util.Arrays; +import java.util.List; + import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums.AmericanCoin; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums.ExampleEnumHolder; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums.FoodPreference; @@ -8,9 +11,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Node; -import java.util.Arrays; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -25,7 +25,7 @@ public void validateProcessingNodesInVanillaXSD() throws Exception { // Assemble final String path = "testdata/schemageneration/javadoc/enums/expectedTransformedExampleEnumHolder.xsd"; final String expected = readFully(path); - + final Document xsdGeneratedFromClassesInMethod = namespace2DocumentMap.get(SomewhatNamedPerson.NAMESPACE); final Node rootNode = xsdGeneratedFromClassesInMethod.getFirstChild(); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/AmericanCoin.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/AmericanCoin.java index dc509f68..94bea67d 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/AmericanCoin.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/AmericanCoin.java @@ -1,12 +1,11 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; - import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlEnum; import jakarta.xml.bind.annotation.XmlEnumValue; import jakarta.xml.bind.annotation.XmlType; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; /** * Simple enumeration example defining standard US coins. @@ -21,18 +20,22 @@ public enum AmericanCoin { /** * A Penny, worth 1 cent. */ - @XmlEnumValue("1") PENNY(1), + @XmlEnumValue("1") + PENNY(1), /** * A Nickel, worth 5 cents. */ - @XmlEnumValue("5") NICKEL(5), + @XmlEnumValue("5") + NICKEL(5), /** * A Nickel, worth 5 cents. */ - @XmlEnumValue("10") DIME(10), - @XmlEnumValue("25") QUARTER(25); + @XmlEnumValue("10") + DIME(10), + @XmlEnumValue("25") + QUARTER(25); // Internal state private int value; diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/County.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/County.java index 019fb0e5..3614bd6c 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/County.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/County.java @@ -1,11 +1,11 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; +import java.io.Serializable; import jakarta.xml.bind.annotation.XmlEnum; import jakarta.xml.bind.annotation.XmlEnumValue; import jakarta.xml.bind.annotation.XmlType; -import java.io.Serializable; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; /** * Swedish County ("län") enumeration. @@ -15,28 +15,48 @@ @XmlType(namespace = SomewhatNamedPerson.NAMESPACE) @XmlEnum public enum County implements Serializable { - - @XmlEnumValue("1")stockholm(1, "AB", true, "Stockholm"), - @XmlEnumValue("3")uppsala(3, "C", false, "Uppsala"), - @XmlEnumValue("4")sodermanland(4, "D", true, "Södermanland"), - @XmlEnumValue("5")ostergotland(5, "E", true, "Östergötland"), - @XmlEnumValue("6")jonkoping(6, "F", true, "Jönköping"), - @XmlEnumValue("7")kronoberg(7, "G", true, "Kronoberg"), - @XmlEnumValue("8")kalmar(8, "H", false, "Kalmar"), - @XmlEnumValue("9")gotland(9, "I", true, "Gotland"), - @XmlEnumValue("10")blekinge(10, "K", false, "Blekinge"), - @XmlEnumValue("12")skane(12, "M", false, "Skåne"), - @XmlEnumValue("13")halland(13, "N", true, "Halland"), - @XmlEnumValue("14")vastra_gotaland(14, "O", true, "Västra Götaland"), - @XmlEnumValue("17")varmland(17, "S", true, "Värmland"), - @XmlEnumValue("18")orebro(18, "T", false, "Örebro"), - @XmlEnumValue("19")vastmanland(19, "U", true, "Västmanland"), - @XmlEnumValue("20")dalarna(20, "W", true, "Dalarna"), - @XmlEnumValue("21")gavleborg(21, "X", true, "Gävleborg"), - @XmlEnumValue("22")vasternorrland(22, "Y", true, "Västernorrland"), - @XmlEnumValue("23")jamtland(23, "Z", true, "Jämtland"), - @XmlEnumValue("24")vasterbotten(24, "AC", true, "Västerbotten"), - @XmlEnumValue("25")norrbotten(25, "BD", true, "Norrbotten"); + @XmlEnumValue("1") + stockholm(1, "AB", true, "Stockholm"), + @XmlEnumValue("3") + uppsala(3, "C", false, "Uppsala"), + @XmlEnumValue("4") + sodermanland(4, "D", true, "Södermanland"), + @XmlEnumValue("5") + ostergotland(5, "E", true, "Östergötland"), + @XmlEnumValue("6") + jonkoping(6, "F", true, "Jönköping"), + @XmlEnumValue("7") + kronoberg(7, "G", true, "Kronoberg"), + @XmlEnumValue("8") + kalmar(8, "H", false, "Kalmar"), + @XmlEnumValue("9") + gotland(9, "I", true, "Gotland"), + @XmlEnumValue("10") + blekinge(10, "K", false, "Blekinge"), + @XmlEnumValue("12") + skane(12, "M", false, "Skåne"), + @XmlEnumValue("13") + halland(13, "N", true, "Halland"), + @XmlEnumValue("14") + vastra_gotaland(14, "O", true, "Västra Götaland"), + @XmlEnumValue("17") + varmland(17, "S", true, "Värmland"), + @XmlEnumValue("18") + orebro(18, "T", false, "Örebro"), + @XmlEnumValue("19") + vastmanland(19, "U", true, "Västmanland"), + @XmlEnumValue("20") + dalarna(20, "W", true, "Dalarna"), + @XmlEnumValue("21") + gavleborg(21, "X", true, "Gävleborg"), + @XmlEnumValue("22") + vasternorrland(22, "Y", true, "Västernorrland"), + @XmlEnumValue("23") + jamtland(23, "Z", true, "Jämtland"), + @XmlEnumValue("24") + vasterbotten(24, "AC", true, "Västerbotten"), + @XmlEnumValue("25") + norrbotten(25, "BD", true, "Norrbotten"); // Internal state private int countyId; @@ -54,10 +74,7 @@ public enum County implements Serializable { * {@code Stockholms län} (note the extra 's')). * @param countyName The name of this County. */ - County(final int countyId, - final String letterCode, - final boolean injectFormalNameS, - final String countyName) { + County(final int countyId, final String letterCode, final boolean injectFormalNameS, final String countyName) { this.letterCode = letterCode; this.countyId = countyId; @@ -110,4 +127,4 @@ public static County getCountyById(final int countyId) { throw new IllegalArgumentException("No County had countyID [" + countyId + "]"); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/ExampleEnumHolder.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/ExampleEnumHolder.java index b0d2b6ad..6d6e47e2 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/ExampleEnumHolder.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/ExampleEnumHolder.java @@ -1,6 +1,10 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; @@ -8,11 +12,7 @@ import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; /** * Trivial transport object type for Enums with different representations. @@ -20,7 +20,9 @@ * @author Lennart Jörelid, jGuru Europe AB */ @XmlRootElement(namespace = SomewhatNamedPerson.NAMESPACE) -@XmlType(namespace = SomewhatNamedPerson.NAMESPACE, propOrder = {"coins", "foodPreferences"}) +@XmlType( + namespace = SomewhatNamedPerson.NAMESPACE, + propOrder = {"coins", "foodPreferences"}) @XmlAccessorType(XmlAccessType.FIELD) public class ExampleEnumHolder implements Serializable { @@ -38,7 +40,6 @@ public class ExampleEnumHolder implements Serializable { @XmlElement(name = "preference") private SortedSet foodPreferences; - public ExampleEnumHolder() { this.coins = new ArrayList(); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/FoodPreference.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/FoodPreference.java index 7cfd5c7e..eff65d1a 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/FoodPreference.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/FoodPreference.java @@ -1,12 +1,11 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; - import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlEnum; import jakarta.xml.bind.annotation.XmlType; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; /** * Simple enumeration example defining some Food preferences. diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Municipality.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Municipality.java index e9d3cdf2..366a1fd8 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Municipality.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Municipality.java @@ -1,16 +1,15 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; - -import org.codehaus.mojo.jaxb2.shared.Validate; +import java.io.Serializable; +import java.text.DecimalFormat; +import java.util.SortedSet; +import java.util.TreeSet; import jakarta.xml.bind.annotation.XmlEnum; import jakarta.xml.bind.annotation.XmlEnumValue; import jakarta.xml.bind.annotation.XmlSeeAlso; import jakarta.xml.bind.annotation.XmlType; -import java.io.Serializable; -import java.text.DecimalFormat; -import java.util.SortedSet; -import java.util.TreeSet; +import org.codehaus.mojo.jaxb2.shared.Validate; /** *

Enumeration of Swedish Municipalities. The enumeration name of each municipality is synthesized from the @@ -29,336 +28,626 @@ public enum Municipality implements Serializable { // Stockholm municipalities - @XmlEnumValue("0114")upplands_vasby(1, 114, "Upplands Väsby"), - @XmlEnumValue("0115")vallentuna(1, 115, "Vallentuna"), - @XmlEnumValue("0117")osteraker(1, 117, "Österåker"), - @XmlEnumValue("0120")varmdo(1, 120, "Värmdö"), - @XmlEnumValue("0123")jarfalla(1, 123, "Järfälla"), - @XmlEnumValue("0125")ekero(1, 125, "Ekerö"), - @XmlEnumValue("0126")huddinge(1, 126, "Huddinge"), - @XmlEnumValue("0127")botkyrka(1, 127, "Botkyrka"), - @XmlEnumValue("0128")salem(1, 128, "Salem"), - @XmlEnumValue("0136")haninge(1, 136, "Haninge"), - @XmlEnumValue("0138")tyreso(1, 138, "Tyresö"), - @XmlEnumValue("0139")upplands_bro(1, 139, "Upplands-Bro"), - @XmlEnumValue("0140")nykvarn(1, 140, "Nykvarn"), - @XmlEnumValue("0160")taby(1, 160, "Täby"), - @XmlEnumValue("0162")danderyd(1, 162, "Danderyd"), - @XmlEnumValue("0163")sollentuna(1, 163, "Sollentuna"), - @XmlEnumValue("0180")stockholm(1, 180, "Stockholm"), - @XmlEnumValue("0181")sodertalje(1, 181, "Södertälje"), - @XmlEnumValue("0182")nacka(1, 182, "Nacka"), - @XmlEnumValue("0183")sundbyberg(1, 183, "Sundbyberg"), - @XmlEnumValue("0184")solna(1, 184, "Solna"), - @XmlEnumValue("0186")lidingo(1, 186, "Lidingö"), - @XmlEnumValue("0187")vaxholm(1, 187, "Vaxholm"), - @XmlEnumValue("0188")norrtalje(1, 188, "Norrtälje"), - @XmlEnumValue("0191")sigtuna(1, 191, "Sigtuna"), - @XmlEnumValue("0192")nynashamn(1, 192, "Nynäshamn"), + @XmlEnumValue("0114") + upplands_vasby(1, 114, "Upplands Väsby"), + @XmlEnumValue("0115") + vallentuna(1, 115, "Vallentuna"), + @XmlEnumValue("0117") + osteraker(1, 117, "Österåker"), + @XmlEnumValue("0120") + varmdo(1, 120, "Värmdö"), + @XmlEnumValue("0123") + jarfalla(1, 123, "Järfälla"), + @XmlEnumValue("0125") + ekero(1, 125, "Ekerö"), + @XmlEnumValue("0126") + huddinge(1, 126, "Huddinge"), + @XmlEnumValue("0127") + botkyrka(1, 127, "Botkyrka"), + @XmlEnumValue("0128") + salem(1, 128, "Salem"), + @XmlEnumValue("0136") + haninge(1, 136, "Haninge"), + @XmlEnumValue("0138") + tyreso(1, 138, "Tyresö"), + @XmlEnumValue("0139") + upplands_bro(1, 139, "Upplands-Bro"), + @XmlEnumValue("0140") + nykvarn(1, 140, "Nykvarn"), + @XmlEnumValue("0160") + taby(1, 160, "Täby"), + @XmlEnumValue("0162") + danderyd(1, 162, "Danderyd"), + @XmlEnumValue("0163") + sollentuna(1, 163, "Sollentuna"), + @XmlEnumValue("0180") + stockholm(1, 180, "Stockholm"), + @XmlEnumValue("0181") + sodertalje(1, 181, "Södertälje"), + @XmlEnumValue("0182") + nacka(1, 182, "Nacka"), + @XmlEnumValue("0183") + sundbyberg(1, 183, "Sundbyberg"), + @XmlEnumValue("0184") + solna(1, 184, "Solna"), + @XmlEnumValue("0186") + lidingo(1, 186, "Lidingö"), + @XmlEnumValue("0187") + vaxholm(1, 187, "Vaxholm"), + @XmlEnumValue("0188") + norrtalje(1, 188, "Norrtälje"), + @XmlEnumValue("0191") + sigtuna(1, 191, "Sigtuna"), + @XmlEnumValue("0192") + nynashamn(1, 192, "Nynäshamn"), // Uppsala municipalities - @XmlEnumValue("0305")habo_uppsala(3, 305, "Håbo"), - @XmlEnumValue("0319")alvkarleby(3, 319, "Älvkarleby"), - @XmlEnumValue("0330")knivsta(3, 330, "Knivsta"), - @XmlEnumValue("0331")heby(3, 331, "Heby"), - @XmlEnumValue("0360")tierp(3, 360, "Tierp"), - @XmlEnumValue("0380")uppsala(3, 380, "Uppsala"), - @XmlEnumValue("0381")enkoping(3, 381, "Enköping"), - @XmlEnumValue("0382")osthammar(3, 382, "Östhammar"), + @XmlEnumValue("0305") + habo_uppsala(3, 305, "Håbo"), + @XmlEnumValue("0319") + alvkarleby(3, 319, "Älvkarleby"), + @XmlEnumValue("0330") + knivsta(3, 330, "Knivsta"), + @XmlEnumValue("0331") + heby(3, 331, "Heby"), + @XmlEnumValue("0360") + tierp(3, 360, "Tierp"), + @XmlEnumValue("0380") + uppsala(3, 380, "Uppsala"), + @XmlEnumValue("0381") + enkoping(3, 381, "Enköping"), + @XmlEnumValue("0382") + osthammar(3, 382, "Östhammar"), // Södermanland municipalities - @XmlEnumValue("0428")vingaker(4, 428, "Vingåker"), - @XmlEnumValue("0461")gnesta(4, 461, "Gnesta"), - @XmlEnumValue("0480")nykoping(4, 480, "Nyköping"), - @XmlEnumValue("0481")oxelosund(4, 481, "Oxelösund"), - @XmlEnumValue("0482")flen(4, 482, "Flen"), - @XmlEnumValue("0483")katrineholm(4, 483, "Katrineholm"), - @XmlEnumValue("0484")eskilstuna(4, 484, "Eskilstuna"), - @XmlEnumValue("0486")strangnas(4, 486, "Strängnäs"), - @XmlEnumValue("0488")trosa(4, 488, "Trosa"), + @XmlEnumValue("0428") + vingaker(4, 428, "Vingåker"), + @XmlEnumValue("0461") + gnesta(4, 461, "Gnesta"), + @XmlEnumValue("0480") + nykoping(4, 480, "Nyköping"), + @XmlEnumValue("0481") + oxelosund(4, 481, "Oxelösund"), + @XmlEnumValue("0482") + flen(4, 482, "Flen"), + @XmlEnumValue("0483") + katrineholm(4, 483, "Katrineholm"), + @XmlEnumValue("0484") + eskilstuna(4, 484, "Eskilstuna"), + @XmlEnumValue("0486") + strangnas(4, 486, "Strängnäs"), + @XmlEnumValue("0488") + trosa(4, 488, "Trosa"), // Östergötland municipalities - @XmlEnumValue("0509")odeshog(5, 509, "Ödeshög"), - @XmlEnumValue("0512")ydre(5, 512, "Ydre"), - @XmlEnumValue("0513")kinda(5, 513, "Kinda"), - @XmlEnumValue("0560")boxholm(5, 560, "Boxholm"), - @XmlEnumValue("0561")atvidaberg(5, 561, "Åtvidaberg"), - @XmlEnumValue("0562")finspang(5, 562, "Finspång"), - @XmlEnumValue("0563")valdemarsvik(5, 563, "Valdemarsvik"), - @XmlEnumValue("0580")linkoping(5, 580, "Linköping"), - @XmlEnumValue("0581")norrkoping(5, 581, "Norrköping"), - @XmlEnumValue("0582")soderkoping(5, 582, "Söderköping"), - @XmlEnumValue("0583")motala(5, 583, "Motala"), - @XmlEnumValue("0584")vadstena(5, 584, "Vadstena"), - @XmlEnumValue("0586")mjolby(5, 586, "Mjölby"), + @XmlEnumValue("0509") + odeshog(5, 509, "Ödeshög"), + @XmlEnumValue("0512") + ydre(5, 512, "Ydre"), + @XmlEnumValue("0513") + kinda(5, 513, "Kinda"), + @XmlEnumValue("0560") + boxholm(5, 560, "Boxholm"), + @XmlEnumValue("0561") + atvidaberg(5, 561, "Åtvidaberg"), + @XmlEnumValue("0562") + finspang(5, 562, "Finspång"), + @XmlEnumValue("0563") + valdemarsvik(5, 563, "Valdemarsvik"), + @XmlEnumValue("0580") + linkoping(5, 580, "Linköping"), + @XmlEnumValue("0581") + norrkoping(5, 581, "Norrköping"), + @XmlEnumValue("0582") + soderkoping(5, 582, "Söderköping"), + @XmlEnumValue("0583") + motala(5, 583, "Motala"), + @XmlEnumValue("0584") + vadstena(5, 584, "Vadstena"), + @XmlEnumValue("0586") + mjolby(5, 586, "Mjölby"), // Jönköping municipalities - @XmlEnumValue("0604")aneby(6, 604, "Aneby"), - @XmlEnumValue("0617")gnosjo(6, 617, "Gnosjö"), - @XmlEnumValue("0642")mullsjo(6, 642, "Mullsjö"), - @XmlEnumValue("0643")habo_jonkoping(6, 643, "Habo"), - @XmlEnumValue("0662")gislaved(6, 662, "Gislaved"), - @XmlEnumValue("0665")vaggeryd(6, 665, "Vaggeryd"), - @XmlEnumValue("0680")jonkoping(6, 680, "Jönköping"), - @XmlEnumValue("0682")nassjo(6, 682, "Nässjö"), - @XmlEnumValue("0683")varnamo(6, 683, "Värnamo"), - @XmlEnumValue("0684")savsjo(6, 684, "Sävsjö"), - @XmlEnumValue("0685")vetlanda(6, 685, "Vetlanda"), - @XmlEnumValue("0686")eksjo(6, 686, "Eksjö"), - @XmlEnumValue("0687")tranas(6, 687, "Tranås"), + @XmlEnumValue("0604") + aneby(6, 604, "Aneby"), + @XmlEnumValue("0617") + gnosjo(6, 617, "Gnosjö"), + @XmlEnumValue("0642") + mullsjo(6, 642, "Mullsjö"), + @XmlEnumValue("0643") + habo_jonkoping(6, 643, "Habo"), + @XmlEnumValue("0662") + gislaved(6, 662, "Gislaved"), + @XmlEnumValue("0665") + vaggeryd(6, 665, "Vaggeryd"), + @XmlEnumValue("0680") + jonkoping(6, 680, "Jönköping"), + @XmlEnumValue("0682") + nassjo(6, 682, "Nässjö"), + @XmlEnumValue("0683") + varnamo(6, 683, "Värnamo"), + @XmlEnumValue("0684") + savsjo(6, 684, "Sävsjö"), + @XmlEnumValue("0685") + vetlanda(6, 685, "Vetlanda"), + @XmlEnumValue("0686") + eksjo(6, 686, "Eksjö"), + @XmlEnumValue("0687") + tranas(6, 687, "Tranås"), // Kronoberg municipalities - @XmlEnumValue("0760")uppvidinge(7, 760, "Uppvidinge"), - @XmlEnumValue("0761")lessebo(7, 761, "Lessebo"), - @XmlEnumValue("0763")tingsryd(7, 763, "Tingsryd"), - @XmlEnumValue("0764")alvesta(7, 764, "Alvesta"), - @XmlEnumValue("0765")almhult(7, 765, "Älmhult"), - @XmlEnumValue("0767")markaryd(7, 767, "Markaryd"), - @XmlEnumValue("0780")vaxjo(7, 780, "Växjö"), - @XmlEnumValue("0781")ljungby(7, 781, "Ljungby"), + @XmlEnumValue("0760") + uppvidinge(7, 760, "Uppvidinge"), + @XmlEnumValue("0761") + lessebo(7, 761, "Lessebo"), + @XmlEnumValue("0763") + tingsryd(7, 763, "Tingsryd"), + @XmlEnumValue("0764") + alvesta(7, 764, "Alvesta"), + @XmlEnumValue("0765") + almhult(7, 765, "Älmhult"), + @XmlEnumValue("0767") + markaryd(7, 767, "Markaryd"), + @XmlEnumValue("0780") + vaxjo(7, 780, "Växjö"), + @XmlEnumValue("0781") + ljungby(7, 781, "Ljungby"), // Kalmar municipalities - @XmlEnumValue("0821")hogsby(8, 821, "Högsby"), - @XmlEnumValue("0834")torsas(8, 834, "Torsås"), - @XmlEnumValue("0830")morbylanga(8, 840, "Mörbylånga"), - @XmlEnumValue("0860")hultsfred(8, 860, "Hultsfred"), - @XmlEnumValue("0861")monsteras(8, 861, "Mönsterås"), - @XmlEnumValue("0862")emmaboda(8, 862, "Emmaboda"), - @XmlEnumValue("0880")kalmar(8, 880, "Kalmar"), - @XmlEnumValue("0881")nybro(8, 881, "Nybro"), - @XmlEnumValue("0882")oskarshamn(8, 882, "Oskarshamn"), - @XmlEnumValue("0883")vastervik(8, 883, "Västervik"), - @XmlEnumValue("0884")vimmerby(8, 884, "Vimmerby"), - @XmlEnumValue("0885")borgholm(8, 885, "Borgholm"), + @XmlEnumValue("0821") + hogsby(8, 821, "Högsby"), + @XmlEnumValue("0834") + torsas(8, 834, "Torsås"), + @XmlEnumValue("0830") + morbylanga(8, 840, "Mörbylånga"), + @XmlEnumValue("0860") + hultsfred(8, 860, "Hultsfred"), + @XmlEnumValue("0861") + monsteras(8, 861, "Mönsterås"), + @XmlEnumValue("0862") + emmaboda(8, 862, "Emmaboda"), + @XmlEnumValue("0880") + kalmar(8, 880, "Kalmar"), + @XmlEnumValue("0881") + nybro(8, 881, "Nybro"), + @XmlEnumValue("0882") + oskarshamn(8, 882, "Oskarshamn"), + @XmlEnumValue("0883") + vastervik(8, 883, "Västervik"), + @XmlEnumValue("0884") + vimmerby(8, 884, "Vimmerby"), + @XmlEnumValue("0885") + borgholm(8, 885, "Borgholm"), // Gotland municipality - @XmlEnumValue("0980")gotland(9, 980, "Gotland"), + @XmlEnumValue("0980") + gotland(9, 980, "Gotland"), // Blekinge municipalities - @XmlEnumValue("1060")olofstrom(10, 1060, "Olofström"), - @XmlEnumValue("1080")karlskrona(10, 1080, "Karlskrona"), - @XmlEnumValue("1081")ronneby(10, 1081, "Ronneby"), - @XmlEnumValue("1082")karlshamn(10, 1082, "Karlshamn"), - @XmlEnumValue("1083")solvesborg(10, 1083, "Sölvesborg"), + @XmlEnumValue("1060") + olofstrom(10, 1060, "Olofström"), + @XmlEnumValue("1080") + karlskrona(10, 1080, "Karlskrona"), + @XmlEnumValue("1081") + ronneby(10, 1081, "Ronneby"), + @XmlEnumValue("1082") + karlshamn(10, 1082, "Karlshamn"), + @XmlEnumValue("1083") + solvesborg(10, 1083, "Sölvesborg"), // Skåne municipalities - @XmlEnumValue("1214")svalov(12, 1214, "Svalöv"), - @XmlEnumValue("1230")staffanstorp(12, 1230, "Staffanstorp"), - @XmlEnumValue("1231")bjurlov(12, 1231, "Burlöv"), - @XmlEnumValue("1233")vellinge(12, 1233, "Vellinge"), - @XmlEnumValue("1256")ostra_goinge(12, 1256, "Östra Göinge"), - @XmlEnumValue("1257")orkelljunga(12, 1257, "Örkelljunga"), - @XmlEnumValue("1260")bjuv(12, 1260, "Bjuv"), - @XmlEnumValue("1261")kavlinge(12, 1261, "Kävlinge"), - @XmlEnumValue("1262")lomma(12, 1262, "Lomma"), - @XmlEnumValue("1263")svedala(12, 1263, "Svedala"), - @XmlEnumValue("1264")skurup(12, 1264, "Skurup"), - @XmlEnumValue("1265")sjobo(12, 1265, "Sjöbo"), - @XmlEnumValue("1266")horby(12, 1266, "Hörby"), - @XmlEnumValue("1267")hoor(12, 1267, "Höör"), - @XmlEnumValue("1270")tomelilla(12, 1270, "Tomelilla"), - @XmlEnumValue("1272")bromolla(12, 1272, "Bromölla"), - @XmlEnumValue("1273")osby(12, 1273, "Osby"), - @XmlEnumValue("1275")perstorp(12, 1275, "Perstorp"), - @XmlEnumValue("1276")klippan(12, 1276, "Klippan"), - @XmlEnumValue("1277")astorp(12, 1277, "Åstorp"), - @XmlEnumValue("1278")bastad(12, 1278, "Båstad"), - @XmlEnumValue("1280")malmo(12, 1280, "Malmö"), - @XmlEnumValue("1281")lund(12, 1281, "Lund"), - @XmlEnumValue("1282")landskrona(12, 1282, "Landskrona"), - @XmlEnumValue("1283")helsingborg(12, 1283, "Helsingborg"), - @XmlEnumValue("1284")hoganas(12, 1284, "Höganäs"), - @XmlEnumValue("1285")eslov(12, 1285, "Eslöv"), - @XmlEnumValue("1286")ystad(12, 1286, "Ystad"), - @XmlEnumValue("1287")trelleborg(12, 1287, "Trelleborg"), - @XmlEnumValue("1290")kristianstad(12, 1290, "Kristianstad"), - @XmlEnumValue("1291")simrishamn(12, 1291, "Simrishamn"), - @XmlEnumValue("1292")angelholm(12, 1292, "Ängelholm"), - @XmlEnumValue("1293")hassleholm(12, 1293, "Hässleholm"), + @XmlEnumValue("1214") + svalov(12, 1214, "Svalöv"), + @XmlEnumValue("1230") + staffanstorp(12, 1230, "Staffanstorp"), + @XmlEnumValue("1231") + bjurlov(12, 1231, "Burlöv"), + @XmlEnumValue("1233") + vellinge(12, 1233, "Vellinge"), + @XmlEnumValue("1256") + ostra_goinge(12, 1256, "Östra Göinge"), + @XmlEnumValue("1257") + orkelljunga(12, 1257, "Örkelljunga"), + @XmlEnumValue("1260") + bjuv(12, 1260, "Bjuv"), + @XmlEnumValue("1261") + kavlinge(12, 1261, "Kävlinge"), + @XmlEnumValue("1262") + lomma(12, 1262, "Lomma"), + @XmlEnumValue("1263") + svedala(12, 1263, "Svedala"), + @XmlEnumValue("1264") + skurup(12, 1264, "Skurup"), + @XmlEnumValue("1265") + sjobo(12, 1265, "Sjöbo"), + @XmlEnumValue("1266") + horby(12, 1266, "Hörby"), + @XmlEnumValue("1267") + hoor(12, 1267, "Höör"), + @XmlEnumValue("1270") + tomelilla(12, 1270, "Tomelilla"), + @XmlEnumValue("1272") + bromolla(12, 1272, "Bromölla"), + @XmlEnumValue("1273") + osby(12, 1273, "Osby"), + @XmlEnumValue("1275") + perstorp(12, 1275, "Perstorp"), + @XmlEnumValue("1276") + klippan(12, 1276, "Klippan"), + @XmlEnumValue("1277") + astorp(12, 1277, "Åstorp"), + @XmlEnumValue("1278") + bastad(12, 1278, "Båstad"), + @XmlEnumValue("1280") + malmo(12, 1280, "Malmö"), + @XmlEnumValue("1281") + lund(12, 1281, "Lund"), + @XmlEnumValue("1282") + landskrona(12, 1282, "Landskrona"), + @XmlEnumValue("1283") + helsingborg(12, 1283, "Helsingborg"), + @XmlEnumValue("1284") + hoganas(12, 1284, "Höganäs"), + @XmlEnumValue("1285") + eslov(12, 1285, "Eslöv"), + @XmlEnumValue("1286") + ystad(12, 1286, "Ystad"), + @XmlEnumValue("1287") + trelleborg(12, 1287, "Trelleborg"), + @XmlEnumValue("1290") + kristianstad(12, 1290, "Kristianstad"), + @XmlEnumValue("1291") + simrishamn(12, 1291, "Simrishamn"), + @XmlEnumValue("1292") + angelholm(12, 1292, "Ängelholm"), + @XmlEnumValue("1293") + hassleholm(12, 1293, "Hässleholm"), // Halland municipalities - @XmlEnumValue("1315")hylte(13, 1315, "Hylte"), - @XmlEnumValue("1380")halmstad(13, 1380, "Halmstad"), - @XmlEnumValue("1381")laholm(13, 1381, "Laholm"), - @XmlEnumValue("1382")falkenberg(13, 1382, "Falkenberg"), - @XmlEnumValue("1383")varberg(13, 1383, "Varberg"), - @XmlEnumValue("1384")kungsbacka(13, 1384, "Kungsbacka"), + @XmlEnumValue("1315") + hylte(13, 1315, "Hylte"), + @XmlEnumValue("1380") + halmstad(13, 1380, "Halmstad"), + @XmlEnumValue("1381") + laholm(13, 1381, "Laholm"), + @XmlEnumValue("1382") + falkenberg(13, 1382, "Falkenberg"), + @XmlEnumValue("1383") + varberg(13, 1383, "Varberg"), + @XmlEnumValue("1384") + kungsbacka(13, 1384, "Kungsbacka"), // Västra Götaland municipalities - @XmlEnumValue("1401")harryda(14, 1401, "Härryda"), - @XmlEnumValue("1402")partille(14, 1402, "Partille"), - @XmlEnumValue("1407")ockero(14, 1407, "Öckerö"), - @XmlEnumValue("1415")stenungsund(14, 1415, "Stenungsund"), - @XmlEnumValue("1419")tjorn(14, 1419, "Tjörn"), - @XmlEnumValue("1421")orust(14, 1421, "Orust"), - @XmlEnumValue("1427")sotenas(14, 1427, "Sotenäs"), - @XmlEnumValue("1430")munkedal(14, 1430, "Munkedal"), - @XmlEnumValue("1435")tanum(14, 1435, "Tanum"), - @XmlEnumValue("1438")dals_ed(14, 1438, "Dals-Ed"), - @XmlEnumValue("1439")fargelanda(14, 1439, "Färgelanda"), - @XmlEnumValue("1440")ale(14, 1440, "Ale"), - @XmlEnumValue("1441")lerum(14, 1441, "Lerum"), - @XmlEnumValue("1442")vargarda(14, 1442, "Vårgårda"), - @XmlEnumValue("1443")bollebygd(14, 1443, "Bollebygd"), - @XmlEnumValue("1444")grastorp(14, 1444, "Grästorp"), - @XmlEnumValue("1445")essunga(14, 1445, "Essunga"), - @XmlEnumValue("1446")karlsborg(14, 1446, "Karlsborg"), - @XmlEnumValue("1447")gullspang(14, 1447, "Gullspång"), - @XmlEnumValue("1452")tranemo(14, 1452, "Tranemo"), - @XmlEnumValue("1460")bengtsfors(14, 1460, "Bengtsfors"), - @XmlEnumValue("1461")mellerud(14, 1461, "Mellerud"), - @XmlEnumValue("1462")lilla_edet(14, 1462, "Lilla Edet"), - @XmlEnumValue("1463")mark(14, 1463, "Mark"), - @XmlEnumValue("1465")svenljunga(14, 1465, "Svenljunga"), - @XmlEnumValue("1466")herrljunga(14, 1466, "Herrljunga"), - @XmlEnumValue("1470")vara(14, 1470, "Vara"), - @XmlEnumValue("1471")gotene(14, 1471, "Götene"), - @XmlEnumValue("1472")tibro(14, 1472, "Tibro"), - @XmlEnumValue("1473")toreboda(14, 1473, "Töreboda"), - @XmlEnumValue("1480")goteborg(14, 1480, "Göteborg"), - @XmlEnumValue("1481")molndal(14, 1481, "Mölndal"), - @XmlEnumValue("1482")kungalv(14, 1482, "Kungälv"), - @XmlEnumValue("1484")lysekil(14, 1484, "Lysekil"), - @XmlEnumValue("1485")uddevalla(14, 1485, "Uddevalla"), - @XmlEnumValue("1486")stromstad(14, 1486, "Strömstad"), - @XmlEnumValue("1487")vanersborg(14, 1487, "Vänersborg"), - @XmlEnumValue("1488")trollhattan(14, 1488, "Trollhättan"), - @XmlEnumValue("1489")alingsas(14, 1489, "Alingsås"), - @XmlEnumValue("1490")boras(14, 1490, "Borås"), - @XmlEnumValue("1491")ulricehamn(14, 1491, "Ulricehamn"), - @XmlEnumValue("1492")amal(14, 1492, "Åmål"), - @XmlEnumValue("1493")mariestad(14, 1493, "Mariestad"), - @XmlEnumValue("1494")lidkoping(14, 1494, "Lidköping"), - @XmlEnumValue("1495")skara(14, 1495, "Skara"), - @XmlEnumValue("1496")skovde(14, 1496, "Skövde"), - @XmlEnumValue("1497")hjo(14, 1497, "Hjo"), - @XmlEnumValue("1498")tidaholm(14, 1498, "Tidaholm"), - @XmlEnumValue("1499")falkoping(14, 1499, "Falköping"), + @XmlEnumValue("1401") + harryda(14, 1401, "Härryda"), + @XmlEnumValue("1402") + partille(14, 1402, "Partille"), + @XmlEnumValue("1407") + ockero(14, 1407, "Öckerö"), + @XmlEnumValue("1415") + stenungsund(14, 1415, "Stenungsund"), + @XmlEnumValue("1419") + tjorn(14, 1419, "Tjörn"), + @XmlEnumValue("1421") + orust(14, 1421, "Orust"), + @XmlEnumValue("1427") + sotenas(14, 1427, "Sotenäs"), + @XmlEnumValue("1430") + munkedal(14, 1430, "Munkedal"), + @XmlEnumValue("1435") + tanum(14, 1435, "Tanum"), + @XmlEnumValue("1438") + dals_ed(14, 1438, "Dals-Ed"), + @XmlEnumValue("1439") + fargelanda(14, 1439, "Färgelanda"), + @XmlEnumValue("1440") + ale(14, 1440, "Ale"), + @XmlEnumValue("1441") + lerum(14, 1441, "Lerum"), + @XmlEnumValue("1442") + vargarda(14, 1442, "Vårgårda"), + @XmlEnumValue("1443") + bollebygd(14, 1443, "Bollebygd"), + @XmlEnumValue("1444") + grastorp(14, 1444, "Grästorp"), + @XmlEnumValue("1445") + essunga(14, 1445, "Essunga"), + @XmlEnumValue("1446") + karlsborg(14, 1446, "Karlsborg"), + @XmlEnumValue("1447") + gullspang(14, 1447, "Gullspång"), + @XmlEnumValue("1452") + tranemo(14, 1452, "Tranemo"), + @XmlEnumValue("1460") + bengtsfors(14, 1460, "Bengtsfors"), + @XmlEnumValue("1461") + mellerud(14, 1461, "Mellerud"), + @XmlEnumValue("1462") + lilla_edet(14, 1462, "Lilla Edet"), + @XmlEnumValue("1463") + mark(14, 1463, "Mark"), + @XmlEnumValue("1465") + svenljunga(14, 1465, "Svenljunga"), + @XmlEnumValue("1466") + herrljunga(14, 1466, "Herrljunga"), + @XmlEnumValue("1470") + vara(14, 1470, "Vara"), + @XmlEnumValue("1471") + gotene(14, 1471, "Götene"), + @XmlEnumValue("1472") + tibro(14, 1472, "Tibro"), + @XmlEnumValue("1473") + toreboda(14, 1473, "Töreboda"), + @XmlEnumValue("1480") + goteborg(14, 1480, "Göteborg"), + @XmlEnumValue("1481") + molndal(14, 1481, "Mölndal"), + @XmlEnumValue("1482") + kungalv(14, 1482, "Kungälv"), + @XmlEnumValue("1484") + lysekil(14, 1484, "Lysekil"), + @XmlEnumValue("1485") + uddevalla(14, 1485, "Uddevalla"), + @XmlEnumValue("1486") + stromstad(14, 1486, "Strömstad"), + @XmlEnumValue("1487") + vanersborg(14, 1487, "Vänersborg"), + @XmlEnumValue("1488") + trollhattan(14, 1488, "Trollhättan"), + @XmlEnumValue("1489") + alingsas(14, 1489, "Alingsås"), + @XmlEnumValue("1490") + boras(14, 1490, "Borås"), + @XmlEnumValue("1491") + ulricehamn(14, 1491, "Ulricehamn"), + @XmlEnumValue("1492") + amal(14, 1492, "Åmål"), + @XmlEnumValue("1493") + mariestad(14, 1493, "Mariestad"), + @XmlEnumValue("1494") + lidkoping(14, 1494, "Lidköping"), + @XmlEnumValue("1495") + skara(14, 1495, "Skara"), + @XmlEnumValue("1496") + skovde(14, 1496, "Skövde"), + @XmlEnumValue("1497") + hjo(14, 1497, "Hjo"), + @XmlEnumValue("1498") + tidaholm(14, 1498, "Tidaholm"), + @XmlEnumValue("1499") + falkoping(14, 1499, "Falköping"), // Värmland municipalities - @XmlEnumValue("1715")kil(17, 1715, "Kil"), - @XmlEnumValue("1730")eda(17, 1730, "Eda"), - @XmlEnumValue("1737")torsby(17, 1737, "Torsby"), - @XmlEnumValue("1760")storfors(17, 1760, "Storfors"), - @XmlEnumValue("1761")hammaro(17, 1761, "Hammarö"), - @XmlEnumValue("1762")munkfors(17, 1762, "Munkfors"), - @XmlEnumValue("1763")forshaga(17, 1763, "Forshaga"), - @XmlEnumValue("1764")grums(17, 1764, "Grums"), - @XmlEnumValue("1765")arjang(17, 1765, "Årjäng"), - @XmlEnumValue("1766")sunne(17, 1766, "Sunne"), - @XmlEnumValue("1780")karlstad(17, 1780, "Karlstad"), - @XmlEnumValue("1781")kristinehamn(17, 1781, "Kristinehamn"), - @XmlEnumValue("1782")filipstad(17, 1782, "Filipstad"), - @XmlEnumValue("1783")hagfors(17, 1783, "Hagfors"), - @XmlEnumValue("1784")arvika(17, 1784, "Arvika"), - @XmlEnumValue("1785")saffle(17, 1785, "Säffle"), + @XmlEnumValue("1715") + kil(17, 1715, "Kil"), + @XmlEnumValue("1730") + eda(17, 1730, "Eda"), + @XmlEnumValue("1737") + torsby(17, 1737, "Torsby"), + @XmlEnumValue("1760") + storfors(17, 1760, "Storfors"), + @XmlEnumValue("1761") + hammaro(17, 1761, "Hammarö"), + @XmlEnumValue("1762") + munkfors(17, 1762, "Munkfors"), + @XmlEnumValue("1763") + forshaga(17, 1763, "Forshaga"), + @XmlEnumValue("1764") + grums(17, 1764, "Grums"), + @XmlEnumValue("1765") + arjang(17, 1765, "Årjäng"), + @XmlEnumValue("1766") + sunne(17, 1766, "Sunne"), + @XmlEnumValue("1780") + karlstad(17, 1780, "Karlstad"), + @XmlEnumValue("1781") + kristinehamn(17, 1781, "Kristinehamn"), + @XmlEnumValue("1782") + filipstad(17, 1782, "Filipstad"), + @XmlEnumValue("1783") + hagfors(17, 1783, "Hagfors"), + @XmlEnumValue("1784") + arvika(17, 1784, "Arvika"), + @XmlEnumValue("1785") + saffle(17, 1785, "Säffle"), // Örebro municipalities - @XmlEnumValue("1814")lekeberg(18, 1814, "Lekeberg"), - @XmlEnumValue("1860")laxa(18, 1860, "Laxå"), - @XmlEnumValue("1861")hallsberg(18, 1861, "Hallsberg"), - @XmlEnumValue("1862")degerfors(18, 1862, "Degerfors"), - @XmlEnumValue("1863")hallefors(18, 1863, "Hällefors"), - @XmlEnumValue("1864")ljusnarsberg(18, 1864, "Ljusnarsberg"), - @XmlEnumValue("1880")orebro(18, 1880, "Örebro"), - @XmlEnumValue("1881")kumla(18, 1881, "Kumla"), - @XmlEnumValue("1882")askersund(18, 1882, "Askersund"), - @XmlEnumValue("1883")karlskoga(18, 1883, "Karlskoga"), - @XmlEnumValue("1884")nora(18, 1884, "Nora"), - @XmlEnumValue("1885")lindesberg(18, 1885, "Lindesberg"), + @XmlEnumValue("1814") + lekeberg(18, 1814, "Lekeberg"), + @XmlEnumValue("1860") + laxa(18, 1860, "Laxå"), + @XmlEnumValue("1861") + hallsberg(18, 1861, "Hallsberg"), + @XmlEnumValue("1862") + degerfors(18, 1862, "Degerfors"), + @XmlEnumValue("1863") + hallefors(18, 1863, "Hällefors"), + @XmlEnumValue("1864") + ljusnarsberg(18, 1864, "Ljusnarsberg"), + @XmlEnumValue("1880") + orebro(18, 1880, "Örebro"), + @XmlEnumValue("1881") + kumla(18, 1881, "Kumla"), + @XmlEnumValue("1882") + askersund(18, 1882, "Askersund"), + @XmlEnumValue("1883") + karlskoga(18, 1883, "Karlskoga"), + @XmlEnumValue("1884") + nora(18, 1884, "Nora"), + @XmlEnumValue("1885") + lindesberg(18, 1885, "Lindesberg"), // Västmanland municipalities - @XmlEnumValue("1904")skinskatteberg(19, 1904, "Skinnskatteberg"), - @XmlEnumValue("1907")surahammar(19, 1907, "Surahammar"), - @XmlEnumValue("1960")kungsor(19, 1960, "Kungsör"), - @XmlEnumValue("1961")hallstahammar(19, 1961, "Hallstahammar"), - @XmlEnumValue("1962")norberg(19, 1962, "Norberg"), - @XmlEnumValue("1980")vasteras(19, 1980, "Västerås"), - @XmlEnumValue("1981")sala(19, 1981, "Sala"), - @XmlEnumValue("1982")fagersta(19, 1982, "Fagersta"), - @XmlEnumValue("1983")koping(19, 1983, "Köping"), - @XmlEnumValue("1984")arboga(19, 1984, "Arboga"), + @XmlEnumValue("1904") + skinskatteberg(19, 1904, "Skinnskatteberg"), + @XmlEnumValue("1907") + surahammar(19, 1907, "Surahammar"), + @XmlEnumValue("1960") + kungsor(19, 1960, "Kungsör"), + @XmlEnumValue("1961") + hallstahammar(19, 1961, "Hallstahammar"), + @XmlEnumValue("1962") + norberg(19, 1962, "Norberg"), + @XmlEnumValue("1980") + vasteras(19, 1980, "Västerås"), + @XmlEnumValue("1981") + sala(19, 1981, "Sala"), + @XmlEnumValue("1982") + fagersta(19, 1982, "Fagersta"), + @XmlEnumValue("1983") + koping(19, 1983, "Köping"), + @XmlEnumValue("1984") + arboga(19, 1984, "Arboga"), // Dalarna municipalities - @XmlEnumValue("2021")vansbro(20, 2021, "Vansbro"), - @XmlEnumValue("2023")malung_salen(20, 2023, "Malung-Sälen"), - @XmlEnumValue("2026")gagnef(20, 2026, "Gagnef"), - @XmlEnumValue("2029")leksand(20, 2029, "Leksand"), - @XmlEnumValue("2031")rattvik(20, 2031, "Rättvik"), - @XmlEnumValue("2034")orsa(20, 2034, "Orsa"), - @XmlEnumValue("2039")alvdalen(20, 2039, "Älvdalen"), - @XmlEnumValue("2061")smedjebacken(20, 2061, "Smedjebacken"), - @XmlEnumValue("2062")mora(20, 2062, "Mora"), - @XmlEnumValue("2080")falun(20, 2080, "Falun"), - @XmlEnumValue("2081")borlange(20, 2081, "Borlänge"), - @XmlEnumValue("2082")sater(20, 2082, "Säter"), - @XmlEnumValue("2083")hedemora(20, 2083, "Hedemora"), - @XmlEnumValue("2084")avesta(20, 2084, "Avesta"), - @XmlEnumValue("2085")ludvika(20, 2085, "Ludvika"), + @XmlEnumValue("2021") + vansbro(20, 2021, "Vansbro"), + @XmlEnumValue("2023") + malung_salen(20, 2023, "Malung-Sälen"), + @XmlEnumValue("2026") + gagnef(20, 2026, "Gagnef"), + @XmlEnumValue("2029") + leksand(20, 2029, "Leksand"), + @XmlEnumValue("2031") + rattvik(20, 2031, "Rättvik"), + @XmlEnumValue("2034") + orsa(20, 2034, "Orsa"), + @XmlEnumValue("2039") + alvdalen(20, 2039, "Älvdalen"), + @XmlEnumValue("2061") + smedjebacken(20, 2061, "Smedjebacken"), + @XmlEnumValue("2062") + mora(20, 2062, "Mora"), + @XmlEnumValue("2080") + falun(20, 2080, "Falun"), + @XmlEnumValue("2081") + borlange(20, 2081, "Borlänge"), + @XmlEnumValue("2082") + sater(20, 2082, "Säter"), + @XmlEnumValue("2083") + hedemora(20, 2083, "Hedemora"), + @XmlEnumValue("2084") + avesta(20, 2084, "Avesta"), + @XmlEnumValue("2085") + ludvika(20, 2085, "Ludvika"), // Gävleborg municipalities - @XmlEnumValue("2101")ockelbo(21, 2101, "Ockelbo"), - @XmlEnumValue("2104")hofors(21, 2104, "Hofors"), - @XmlEnumValue("2121")ovanaker(21, 2121, "Ovanåker"), - @XmlEnumValue("2132")nordanstig(21, 2132, "Nordanstig"), - @XmlEnumValue("2161")ljusdal(21, 2161, "Ljusdal"), - @XmlEnumValue("2180")gavle(21, 2180, "Gävle"), - @XmlEnumValue("2181")sandviken(21, 2181, "Sandviken"), - @XmlEnumValue("2182")soderhamn(21, 2182, "Söderhamn"), - @XmlEnumValue("2183")bollnas(21, 2183, "Bollnäs"), - @XmlEnumValue("2184")hudiksvall(21, 2184, "Hudiksvall"), + @XmlEnumValue("2101") + ockelbo(21, 2101, "Ockelbo"), + @XmlEnumValue("2104") + hofors(21, 2104, "Hofors"), + @XmlEnumValue("2121") + ovanaker(21, 2121, "Ovanåker"), + @XmlEnumValue("2132") + nordanstig(21, 2132, "Nordanstig"), + @XmlEnumValue("2161") + ljusdal(21, 2161, "Ljusdal"), + @XmlEnumValue("2180") + gavle(21, 2180, "Gävle"), + @XmlEnumValue("2181") + sandviken(21, 2181, "Sandviken"), + @XmlEnumValue("2182") + soderhamn(21, 2182, "Söderhamn"), + @XmlEnumValue("2183") + bollnas(21, 2183, "Bollnäs"), + @XmlEnumValue("2184") + hudiksvall(21, 2184, "Hudiksvall"), // Västernorrland municipalities - @XmlEnumValue("2260")ange(22, 2260, "Ånge"), - @XmlEnumValue("2262")timra(22, 2262, "Timrå"), - @XmlEnumValue("2280")harnosand(22, 2280, "Härnösand"), - @XmlEnumValue("2280")sundsvall(22, 2281, "Sundsvall"), - @XmlEnumValue("2282")kramfors(22, 2282, "Kramfors"), - @XmlEnumValue("2283")solleftea(22, 2283, "Sollefteå"), - @XmlEnumValue("2283")ornskoldsvik(22, 2284, "Örnsköldsvik"), + @XmlEnumValue("2260") + ange(22, 2260, "Ånge"), + @XmlEnumValue("2262") + timra(22, 2262, "Timrå"), + @XmlEnumValue("2280") + harnosand(22, 2280, "Härnösand"), + @XmlEnumValue("2280") + sundsvall(22, 2281, "Sundsvall"), + @XmlEnumValue("2282") + kramfors(22, 2282, "Kramfors"), + @XmlEnumValue("2283") + solleftea(22, 2283, "Sollefteå"), + @XmlEnumValue("2283") + ornskoldsvik(22, 2284, "Örnsköldsvik"), // Jämtland municipalities - @XmlEnumValue("2303")ragunda(23, 2303, "Ragunda"), - @XmlEnumValue("2305")bracke(23, 2305, "Bräcke"), - @XmlEnumValue("2319")krokom(23, 2309, "Krokom"), - @XmlEnumValue("2313")stromsund(23, 2313, "Strömsund"), - @XmlEnumValue("2321")are(23, 2321, "Åre"), - @XmlEnumValue("2326")berg(23, 2326, "Berg"), - @XmlEnumValue("2361")harjedalen(23, 2361, "Härjedalen"), - @XmlEnumValue("2380")ostersund(23, 2380, "Östersund"), + @XmlEnumValue("2303") + ragunda(23, 2303, "Ragunda"), + @XmlEnumValue("2305") + bracke(23, 2305, "Bräcke"), + @XmlEnumValue("2319") + krokom(23, 2309, "Krokom"), + @XmlEnumValue("2313") + stromsund(23, 2313, "Strömsund"), + @XmlEnumValue("2321") + are(23, 2321, "Åre"), + @XmlEnumValue("2326") + berg(23, 2326, "Berg"), + @XmlEnumValue("2361") + harjedalen(23, 2361, "Härjedalen"), + @XmlEnumValue("2380") + ostersund(23, 2380, "Östersund"), // Västerbotten municipalities - @XmlEnumValue("2401")nordmaling(24, 2401, "Nordmaling"), - @XmlEnumValue("2403")bjurholm(24, 2403, "Bjurholm"), - @XmlEnumValue("2404")vindeln(24, 2404, "Vindeln"), - @XmlEnumValue("2409")robertsfors(24, 2409, "Robertsfors"), - @XmlEnumValue("2417")nordsjo(24, 2417, "Norsjö"), - @XmlEnumValue("2418")mala(24, 2418, "Malå"), - @XmlEnumValue("2421")storuman(24, 2421, "Storuman"), - @XmlEnumValue("2422")sorsele(24, 2422, "Sorsele"), - @XmlEnumValue("2425")dorotea(24, 2425, "Dorotea"), - @XmlEnumValue("2460")vannas(24, 2460, "Vännäs"), - @XmlEnumValue("2462")vilhelmina(24, 2462, "Vilhelmina"), - @XmlEnumValue("2463")asele(24, 2463, "Åsele"), - @XmlEnumValue("2480")umea(24, 2480, "Umeå"), - @XmlEnumValue("2481")lycksele(24, 2481, "Lycksele"), - @XmlEnumValue("2482")skelleftea(24, 2482, "Skellefteå"), + @XmlEnumValue("2401") + nordmaling(24, 2401, "Nordmaling"), + @XmlEnumValue("2403") + bjurholm(24, 2403, "Bjurholm"), + @XmlEnumValue("2404") + vindeln(24, 2404, "Vindeln"), + @XmlEnumValue("2409") + robertsfors(24, 2409, "Robertsfors"), + @XmlEnumValue("2417") + nordsjo(24, 2417, "Norsjö"), + @XmlEnumValue("2418") + mala(24, 2418, "Malå"), + @XmlEnumValue("2421") + storuman(24, 2421, "Storuman"), + @XmlEnumValue("2422") + sorsele(24, 2422, "Sorsele"), + @XmlEnumValue("2425") + dorotea(24, 2425, "Dorotea"), + @XmlEnumValue("2460") + vannas(24, 2460, "Vännäs"), + @XmlEnumValue("2462") + vilhelmina(24, 2462, "Vilhelmina"), + @XmlEnumValue("2463") + asele(24, 2463, "Åsele"), + @XmlEnumValue("2480") + umea(24, 2480, "Umeå"), + @XmlEnumValue("2481") + lycksele(24, 2481, "Lycksele"), + @XmlEnumValue("2482") + skelleftea(24, 2482, "Skellefteå"), // Norrbotten municipalities - @XmlEnumValue("2505")arvidsjaur(25, 2505, "Arvidsjaur"), - @XmlEnumValue("2506")arjeplog(25, 2506, "Arjeplog"), - @XmlEnumValue("2510")jokkmokk(25, 2510, "Jokkmokk"), - @XmlEnumValue("2513")overkalix(25, 2513, "Överkalix"), - @XmlEnumValue("2514")kalix(25, 2514, "Kalix"), - @XmlEnumValue("2518")overtornea(25, 2518, "Övertorneå"), - @XmlEnumValue("2521")pajala(25, 2521, "Pajala"), - @XmlEnumValue("2523")gallivare(25, 2523, "Gällivare"), - @XmlEnumValue("2560")alvsbyn(25, 2560, "Älvsbyn"), - @XmlEnumValue("2580")lulea(25, 2580, "Luleå"), - @XmlEnumValue("2581")pitea(25, 2581, "Piteå"), - @XmlEnumValue("2582")boden(25, 2582, "Boden"), - @XmlEnumValue("2583")haparanda(25, 2583, "Haparanda"), - @XmlEnumValue("2584")kiruna(25, 2584, "Kiruna"); + @XmlEnumValue("2505") + arvidsjaur(25, 2505, "Arvidsjaur"), + @XmlEnumValue("2506") + arjeplog(25, 2506, "Arjeplog"), + @XmlEnumValue("2510") + jokkmokk(25, 2510, "Jokkmokk"), + @XmlEnumValue("2513") + overkalix(25, 2513, "Överkalix"), + @XmlEnumValue("2514") + kalix(25, 2514, "Kalix"), + @XmlEnumValue("2518") + overtornea(25, 2518, "Övertorneå"), + @XmlEnumValue("2521") + pajala(25, 2521, "Pajala"), + @XmlEnumValue("2523") + gallivare(25, 2523, "Gällivare"), + @XmlEnumValue("2560") + alvsbyn(25, 2560, "Älvsbyn"), + @XmlEnumValue("2580") + lulea(25, 2580, "Luleå"), + @XmlEnumValue("2581") + pitea(25, 2581, "Piteå"), + @XmlEnumValue("2582") + boden(25, 2582, "Boden"), + @XmlEnumValue("2583") + haparanda(25, 2583, "Haparanda"), + @XmlEnumValue("2584") + kiruna(25, 2584, "Kiruna"); // Internal state private static final DecimalFormat FOUR_DIGIT_FORMAT = new DecimalFormat("####"); @@ -366,9 +655,7 @@ public enum Municipality implements Serializable { private County county; private String municipalityName; - Municipality(final int countyId, - final int municipalityId, - final String municipalityName) { + Municipality(final int countyId, final int municipalityId, final String municipalityName) { // Assign internal state this.municipalityId = municipalityId; @@ -428,4 +715,4 @@ public static SortedSet getMunicipalitiesIn(final County county) { // All done. return toReturn; } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Regions.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Regions.java index 525a6e15..c67809c0 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Regions.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/Regions.java @@ -1,6 +1,7 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; +import java.util.Set; +import java.util.TreeSet; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; @@ -8,14 +9,15 @@ import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; -import java.util.Set; -import java.util.TreeSet; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.SomewhatNamedPerson; /** * @author Lennart Jörelid, jGuru Europe AB */ @XmlRootElement(namespace = SomewhatNamedPerson.NAMESPACE) -@XmlType(namespace = SomewhatNamedPerson.NAMESPACE, propOrder = {"counties", "municipalities"}) +@XmlType( + namespace = SomewhatNamedPerson.NAMESPACE, + propOrder = {"counties", "municipalities"}) @XmlAccessorType(XmlAccessType.FIELD) public class Regions { diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/XsdAnnotationProcessorAndEnumsTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/XsdAnnotationProcessorAndEnumsTest.java index 4b572191..25ff3b0f 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/XsdAnnotationProcessorAndEnumsTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/enums/XsdAnnotationProcessorAndEnumsTest.java @@ -1,5 +1,12 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.enums; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.Marshaller; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.AbstractSourceCodeAwareNodeProcessingTest; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.JavaDocRenderer; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.NoAuthorJavaDocRenderer; @@ -13,67 +20,59 @@ import org.xmlunit.diff.Diff; import se.jguru.shared.algorithms.api.resources.PropertyResources; -import jakarta.xml.bind.JAXBContext; -import jakarta.xml.bind.Marshaller; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ -public class XsdAnnotationProcessorAndEnumsTest extends AbstractSourceCodeAwareNodeProcessingTest -{ +public class XsdAnnotationProcessorAndEnumsTest extends AbstractSourceCodeAwareNodeProcessingTest { // Shared state private JavaDocRenderer renderer = new NoAuthorJavaDocRenderer(); @Test - public void validateGeneratedXmlForEnums() throws Exception - { + public void validateGeneratedXmlForEnums() throws Exception { // Assemble - final String expected = PropertyResources.readFully( - "testdata/schemageneration/javadoc/expectedRawExampleEnumHolder.xml" ); + final String expected = + PropertyResources.readFully("testdata/schemageneration/javadoc/expectedRawExampleEnumHolder.xml"); final ExampleEnumHolder exampleEnumHolder = new ExampleEnumHolder(); - exampleEnumHolder.getCoins().addAll( Arrays.asList( AmericanCoin.values() ) ); - exampleEnumHolder.getFoodPreferences().addAll( Arrays.asList( FoodPreference.values() ) ); + exampleEnumHolder.getCoins().addAll(Arrays.asList(AmericanCoin.values())); + exampleEnumHolder.getFoodPreferences().addAll(Arrays.asList(FoodPreference.values())); final StringWriter out = new StringWriter(); // Act - final JAXBContext context = JAXBContext.newInstance( FoodPreference.class, ExampleEnumHolder.class ); + final JAXBContext context = JAXBContext.newInstance(FoodPreference.class, ExampleEnumHolder.class); final Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true ); - marshaller.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" ); - marshaller.marshal( exampleEnumHolder, out ); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + marshaller.marshal(exampleEnumHolder, out); out.close(); // Assert - final Diff diff = DiffBuilder.compare( expected ).withTest( - out.toString() ).ignoreWhitespace().ignoreComments().build(); - Assert.assertFalse( diff.hasDifferences() ); + final Diff diff = DiffBuilder.compare(expected) + .withTest(out.toString()) + .ignoreWhitespace() + .ignoreComments() + .build(); + Assert.assertFalse(diff.hasDifferences()); // XmlTestUtils.compareXmlIgnoringWhitespace( expected, out.toString() ); } @Test - public void validateHandlingXmlElementWrapperDocumentation() throws Exception - { + public void validateHandlingXmlElementWrapperDocumentation() throws Exception { // Assmeble - final Document document = namespace2DocumentMap.get( SomewhatNamedPerson.NAMESPACE ); + final Document document = namespace2DocumentMap.get(SomewhatNamedPerson.NAMESPACE); final Node rootNode = document.getFirstChild(); - final XsdAnnotationProcessor unitUnderTest = new XsdAnnotationProcessor( docs, renderer ); + final XsdAnnotationProcessor unitUnderTest = new XsdAnnotationProcessor(docs, renderer); // Act - process( rootNode, true, unitUnderTest ); + process(rootNode, true, unitUnderTest); // Assert - final String processed = printDocument( document ); - System.out.println( "Got: " + processed ); - + final String processed = printDocument(document); + System.out.println("Got: " + processed); // Act @@ -83,15 +82,13 @@ public void validateHandlingXmlElementWrapperDocumentation() throws Exception /** * {@inheritDoc} */ - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - protected List> getJaxbAnnotatedClassesForJaxbContext() - { + protected List> getJaxbAnnotatedClassesForJaxbContext() { final List> toReturn = new ArrayList>(); - for ( Class current : Arrays.asList( FoodPreference.class, ExampleEnumHolder.class, AmericanCoin.class ) ) - { - toReturn.add( current ); + for (Class current : Arrays.asList(FoodPreference.class, ExampleEnumHolder.class, AmericanCoin.class)) { + toReturn.add(current); } return toReturn; diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWapperUsingJavaBeanAccessors.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWapperUsingJavaBeanAccessors.java index b02deab4..9083b312 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWapperUsingJavaBeanAccessors.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWapperUsingJavaBeanAccessors.java @@ -1,24 +1,23 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.wrappers; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlElementWrapper; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlElementWrapper; + /** * @author Lennart Jörelid, jGuru Europe AB */ -public class ExampleXmlWapperUsingJavaBeanAccessors implements Serializable -{ +public class ExampleXmlWapperUsingJavaBeanAccessors implements Serializable { private List strings; private SortedSet integerSet; - public ExampleXmlWapperUsingJavaBeanAccessors() - { + public ExampleXmlWapperUsingJavaBeanAccessors() { this.strings = new ArrayList(); this.integerSet = new TreeSet(); @@ -27,10 +26,9 @@ public ExampleXmlWapperUsingJavaBeanAccessors() /** * JavaBean getter for a List containing some strings. */ - @XmlElementWrapper( name = "foobar" ) - @XmlElement( name = "aString" ) - public List getStrings() - { + @XmlElementWrapper(name = "foobar") + @XmlElement(name = "aString") + public List getStrings() { return strings; } @@ -38,9 +36,8 @@ public List getStrings() * JavaBean getter for a SortedSet containing Integers. */ @XmlElementWrapper - @XmlElement( name = "anInteger" ) - public SortedSet getIntegerSet() - { + @XmlElement(name = "anInteger") + public SortedSet getIntegerSet() { return integerSet; } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWrapper.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWrapper.java index fca04a5f..620c3bba 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWrapper.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/wrappers/ExampleXmlWrapper.java @@ -1,16 +1,17 @@ package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.wrappers; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; /** * Trivial transport object type for collections. @@ -18,7 +19,9 @@ * @author Lennart Jörelid, jGuru Europe AB */ @XmlRootElement(namespace = "http://jaxb.mojohaus.org/wrappers") -@XmlType(namespace = "http://jaxb.mojohaus.org/wrappers", propOrder = {"strings", "integerSet"}) +@XmlType( + namespace = "http://jaxb.mojohaus.org/wrappers", + propOrder = {"strings", "integerSet"}) @XmlAccessorType(XmlAccessType.FIELD) public class ExampleXmlWrapper implements Serializable { @@ -36,7 +39,6 @@ public class ExampleXmlWrapper implements Serializable { @XmlElement(name = "anInteger") private SortedSet integerSet; - public ExampleXmlWrapper() { this.strings = new ArrayList(); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessorTest.java index af3038d8..e81d5aaf 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeFilenameProcessorTest.java @@ -1,69 +1,69 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.DebugNodeProcessor; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import java.io.StringReader; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** @author Lennart Jörelid */ -public class ChangeFilenameProcessorTest { - - @Test - public void validateAcceptCriteria() { - - // Assemble - final String oldFileName = "foo"; - final String newFileName = "bar"; - final String xmlStream = getXmlDocumentSample(oldFileName); - final String namespaceToBeRelocated = "http://another/namespace"; - - final Map namespaceUriToNewFilenameMap = new TreeMap(); - namespaceUriToNewFilenameMap.put(namespaceToBeRelocated, newFileName); - - final ChangeFilenameProcessor unitUnderTest = new ChangeFilenameProcessor(namespaceUriToNewFilenameMap); - final DebugNodeProcessor debugNodeProcessor = new DebugNodeProcessor(unitUnderTest); - - // Act - final Document document = XsdGeneratorHelper.parseXmlStream(new StringReader(xmlStream)); - XsdGeneratorHelper.process(document.getFirstChild(), true, debugNodeProcessor); - - // Assert - final List acceptedNodes = debugNodeProcessor.getAcceptedNodes(); - Assert.assertEquals(1, acceptedNodes.size()); - Assert.assertEquals("schemaLocation", acceptedNodes.get(0).getNodeName()); - Assert.assertEquals(newFileName, acceptedNodes.get(0).getNodeValue()); - } - - // - // Private helpers - // - - private String getXmlDocumentSample(String fileName) { - return "\n" - + "\n" - + "\n" - + " \n" - + " \n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "\n"; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +import java.io.StringReader; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.DebugNodeProcessor; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** @author Lennart Jörelid */ +public class ChangeFilenameProcessorTest { + + @Test + public void validateAcceptCriteria() { + + // Assemble + final String oldFileName = "foo"; + final String newFileName = "bar"; + final String xmlStream = getXmlDocumentSample(oldFileName); + final String namespaceToBeRelocated = "http://another/namespace"; + + final Map namespaceUriToNewFilenameMap = new TreeMap(); + namespaceUriToNewFilenameMap.put(namespaceToBeRelocated, newFileName); + + final ChangeFilenameProcessor unitUnderTest = new ChangeFilenameProcessor(namespaceUriToNewFilenameMap); + final DebugNodeProcessor debugNodeProcessor = new DebugNodeProcessor(unitUnderTest); + + // Act + final Document document = XsdGeneratorHelper.parseXmlStream(new StringReader(xmlStream)); + XsdGeneratorHelper.process(document.getFirstChild(), true, debugNodeProcessor); + + // Assert + final List acceptedNodes = debugNodeProcessor.getAcceptedNodes(); + Assert.assertEquals(1, acceptedNodes.size()); + Assert.assertEquals("schemaLocation", acceptedNodes.get(0).getNodeName()); + Assert.assertEquals(newFileName, acceptedNodes.get(0).getNodeValue()); + } + + // + // Private helpers + // + + private String getXmlDocumentSample(String fileName) { + return "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + } +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessorTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessorTest.java index 30f105d7..03100787 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessorTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/ChangeNamespacePrefixProcessorTest.java @@ -1,88 +1,85 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; -import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.DebugNodeProcessor; -import org.junit.Assert; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import java.io.StringReader; -import java.util.List; - -/** - * @author Lennart Jörelid - */ -public class ChangeNamespacePrefixProcessorTest -{ - @Test - public void validateAcceptCriteria() - { - // Assemble - final String oldNamespacePrefix = "oldNamespacePrefix"; - final String newNamespacePrefix = "newNamespacePrefix"; - final String namespaceURI = "http://another/namespace"; - final String xmlStream = getXmlDocumentSample( oldNamespacePrefix, namespaceURI ); - - final ChangeNamespacePrefixProcessor unitUnderTest = - new ChangeNamespacePrefixProcessor( oldNamespacePrefix, newNamespacePrefix ); - final DebugNodeProcessor debugNodeProcessor = new DebugNodeProcessor( unitUnderTest ); - - // Act - final Document document = XsdGeneratorHelper.parseXmlStream(new StringReader(xmlStream)); - XsdGeneratorHelper.process(document.getFirstChild(), true, debugNodeProcessor); - - // Assert - final List acceptedNodes = debugNodeProcessor.getAcceptedNodes(); - Assert.assertEquals( 3, acceptedNodes.size() ); - - // Note that the DebugNodeProcessor acquires the node *before* it is actually - // processed - implying that the nodeName is not yet changed. - Node namespaceDefinitionAttribute = acceptedNodes.get( 0 ); - Assert.assertEquals( "xmlns:" + oldNamespacePrefix, namespaceDefinitionAttribute.getNodeName() ); - Assert.assertEquals( namespaceURI, namespaceDefinitionAttribute.getNodeValue() ); - - Node elementReferenceAttribute = acceptedNodes.get( 1 ); - Assert.assertEquals( "ref", elementReferenceAttribute.getNodeName() ); - Assert.assertEquals( newNamespacePrefix + ":aRequiredElementInAnotherNamespace", - elementReferenceAttribute.getNodeValue() ); - - Node extensionAttribute = acceptedNodes.get( 2 ); - Assert.assertEquals( "base", extensionAttribute.getNodeName() ); - Assert.assertEquals( newNamespacePrefix + ":aBaseType", extensionAttribute.getNodeValue() ); - } - - // - // Private helpers - // - - private String getXmlDocumentSample( String namespacePrefix, String namespaceURI ) - { - return "\n" - + "\n" - + "\n" - + " \n" - + "\n" - + " \n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "\n"; - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +import java.io.StringReader; +import java.util.List; + +import org.codehaus.mojo.jaxb2.schemageneration.XsdGeneratorHelper; +import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.DebugNodeProcessor; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * @author Lennart Jörelid + */ +public class ChangeNamespacePrefixProcessorTest { + @Test + public void validateAcceptCriteria() { + // Assemble + final String oldNamespacePrefix = "oldNamespacePrefix"; + final String newNamespacePrefix = "newNamespacePrefix"; + final String namespaceURI = "http://another/namespace"; + final String xmlStream = getXmlDocumentSample(oldNamespacePrefix, namespaceURI); + + final ChangeNamespacePrefixProcessor unitUnderTest = + new ChangeNamespacePrefixProcessor(oldNamespacePrefix, newNamespacePrefix); + final DebugNodeProcessor debugNodeProcessor = new DebugNodeProcessor(unitUnderTest); + + // Act + final Document document = XsdGeneratorHelper.parseXmlStream(new StringReader(xmlStream)); + XsdGeneratorHelper.process(document.getFirstChild(), true, debugNodeProcessor); + + // Assert + final List acceptedNodes = debugNodeProcessor.getAcceptedNodes(); + Assert.assertEquals(3, acceptedNodes.size()); + + // Note that the DebugNodeProcessor acquires the node *before* it is actually + // processed - implying that the nodeName is not yet changed. + Node namespaceDefinitionAttribute = acceptedNodes.get(0); + Assert.assertEquals("xmlns:" + oldNamespacePrefix, namespaceDefinitionAttribute.getNodeName()); + Assert.assertEquals(namespaceURI, namespaceDefinitionAttribute.getNodeValue()); + + Node elementReferenceAttribute = acceptedNodes.get(1); + Assert.assertEquals("ref", elementReferenceAttribute.getNodeName()); + Assert.assertEquals( + newNamespacePrefix + ":aRequiredElementInAnotherNamespace", elementReferenceAttribute.getNodeValue()); + + Node extensionAttribute = acceptedNodes.get(2); + Assert.assertEquals("base", extensionAttribute.getNodeName()); + Assert.assertEquals(newNamespacePrefix + ":aBaseType", extensionAttribute.getNodeValue()); + } + + // + // Private helpers + // + + private String getXmlDocumentSample(String namespacePrefix, String namespaceURI) { + return "\n" + + "\n" + + "\n" + + " \n" + + "\n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + } +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolverTest.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolverTest.java index c63045d7..ab512655 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolverTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/SimpleNamespaceResolverTest.java @@ -1,150 +1,158 @@ -package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; - -import org.codehaus.plexus.util.FileUtils; -import org.junit.Assert; -import org.junit.Test; - -import javax.xml.XMLConstants; -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * @author Lennart Jörelid - */ -public class SimpleNamespaceResolverTest { - - public static final String SCHEMA_DIR = "/org/codehaus/mojo/jaxb2/helpers/"; - - private File getSchemaFile(String resource) { - return FileUtils.toFile(this.getClass().getResource(resource)); - } - - @Test - public void validateCollectingSchemaInfoForSingleNamespaceSchemaFile() { - // Assemble - final String schemaFile = "yetAnotherSchema.xsd"; - final File resolvedSchemaFile = getSchemaFile(SCHEMA_DIR + schemaFile); - final SimpleNamespaceResolver unitUnderTest = new SimpleNamespaceResolver(resolvedSchemaFile); - - // Act - final Map namespaceURI2PrefixMap = unitUnderTest.getNamespaceURI2PrefixMap(); - - // Assert - Assert.assertEquals(schemaFile, unitUnderTest.getSourceFilename()); - Assert.assertEquals("http://yet/another/namespace", unitUnderTest.getLocalNamespaceURI()); - - Assert.assertEquals(1, namespaceURI2PrefixMap.size()); - Assert.assertEquals("xs", namespaceURI2PrefixMap.get(XMLConstants.W3C_XML_SCHEMA_NS_URI)); - - Assert.assertEquals(XMLConstants.W3C_XML_SCHEMA_NS_URI, unitUnderTest.getNamespaceURI("xs")); - } - - @Test - public void validateCollectingSchemaInfoForMultipleNamespaceSchemaFile() { - // Assemble - final String schemaFile = "anotherSchema.xsd"; - final SimpleNamespaceResolver unitUnderTest = new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); - - // Act - final Map namespaceURI2PrefixMap = unitUnderTest.getNamespaceURI2PrefixMap(); - - // Assert - Assert.assertEquals(schemaFile, unitUnderTest.getSourceFilename()); - Assert.assertEquals("http://another/namespace", unitUnderTest.getLocalNamespaceURI()); - - Assert.assertEquals(3, namespaceURI2PrefixMap.size()); - Assert.assertEquals("xs", namespaceURI2PrefixMap.get(XMLConstants.W3C_XML_SCHEMA_NS_URI)); - Assert.assertEquals("yetAnother", namespaceURI2PrefixMap.get("http://yet/another/namespace")); - Assert.assertEquals("some", namespaceURI2PrefixMap.get("http://some/namespace")); - - for (String current : namespaceURI2PrefixMap.keySet()) { - final String currentPrefix = namespaceURI2PrefixMap.get(current); - Assert.assertEquals(currentPrefix, unitUnderTest.getPrefix(current)); - } - } - - @Test(expected = IllegalArgumentException.class) - public void validateExceptionOnEmptyRelativePathToXmlFile() { - // Assemble - final String incorrectEmpty = ""; - - // Act & Assert - new SimpleNamespaceResolver(getSchemaFile(incorrectEmpty)); - Assert.fail( - "Creating a SimpleNamespaceResolver with empty argument " + "should yield an IllegalArgumentException."); - } - - @Test - public void validateExceptionOnNonexistentXmlSchemaFile() { - // Assemble - final String nonExistentPath = "this/file/does/not/exist.xml"; - final File nonExistent = new File(nonExistentPath); - - // Act & Assert - try { - new SimpleNamespaceResolver(nonExistent); - Assert.fail("Creating a SimpleNamespaceResolver connected to a nonexistent file " - + "should yield an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // Expected - } catch (Exception e) { - Assert.fail("Expected IllegalArgumentException, but received [" + e.getClass().getName() + "]"); - } - } - - @Test - public void validateJaxbNamespaceResolverComplianceInThrowingExceptionOnNullNamespaceResolverArguments() { - // Assemble - final String schemaFile = "yetAnotherSchema.xsd"; - final SimpleNamespaceResolver unitUnderTest = new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); - final String incorrectNull = null; - - // Act & Assert - try { - unitUnderTest.getPrefix(incorrectNull); - Assert.fail("Running getPrefix with a null argument should yield an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // Expected - } catch (Exception e) { - Assert.fail("Expected IllegalArgumentException, but received [" + e.getClass().getName() + "]"); - } - - try { - unitUnderTest.getNamespaceURI(incorrectNull); - Assert.fail("Running getNamespaceURI with a null argument should yield an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // Expected - } catch (Exception e) { - Assert.fail("Expected IllegalArgumentException, but received [" + e.getClass().getName() + "]"); - } - - try { - unitUnderTest.getPrefixes(incorrectNull); - Assert.fail("Running getPrefixes with a null argument should yield an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - // Expected - } catch (Exception e) { - Assert.fail("Expected IllegalArgumentException, but received [" + e.getClass().getName() + "]"); - } - } - - @Test - public void validatePrefixesIterator() { - // Assemble - final String schemaFile = "yetAnotherSchema.xsd"; - final SimpleNamespaceResolver unitUnderTest = new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); - - // Act - List prefixesList = new ArrayList(); - for (Iterator it = unitUnderTest.getPrefixes(XMLConstants.W3C_XML_SCHEMA_NS_URI); it.hasNext(); ) { - prefixesList.add(it.next()); - } - - // Assert - Assert.assertEquals(1, prefixesList.size()); - Assert.assertEquals("xs", prefixesList.get(0)); - } -} \ No newline at end of file +package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.schemaenhancement; + +import javax.xml.XMLConstants; + +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.codehaus.plexus.util.FileUtils; +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Lennart Jörelid + */ +public class SimpleNamespaceResolverTest { + + public static final String SCHEMA_DIR = "/org/codehaus/mojo/jaxb2/helpers/"; + + private File getSchemaFile(String resource) { + return FileUtils.toFile(this.getClass().getResource(resource)); + } + + @Test + public void validateCollectingSchemaInfoForSingleNamespaceSchemaFile() { + // Assemble + final String schemaFile = "yetAnotherSchema.xsd"; + final File resolvedSchemaFile = getSchemaFile(SCHEMA_DIR + schemaFile); + final SimpleNamespaceResolver unitUnderTest = new SimpleNamespaceResolver(resolvedSchemaFile); + + // Act + final Map namespaceURI2PrefixMap = unitUnderTest.getNamespaceURI2PrefixMap(); + + // Assert + Assert.assertEquals(schemaFile, unitUnderTest.getSourceFilename()); + Assert.assertEquals("http://yet/another/namespace", unitUnderTest.getLocalNamespaceURI()); + + Assert.assertEquals(1, namespaceURI2PrefixMap.size()); + Assert.assertEquals("xs", namespaceURI2PrefixMap.get(XMLConstants.W3C_XML_SCHEMA_NS_URI)); + + Assert.assertEquals(XMLConstants.W3C_XML_SCHEMA_NS_URI, unitUnderTest.getNamespaceURI("xs")); + } + + @Test + public void validateCollectingSchemaInfoForMultipleNamespaceSchemaFile() { + // Assemble + final String schemaFile = "anotherSchema.xsd"; + final SimpleNamespaceResolver unitUnderTest = + new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); + + // Act + final Map namespaceURI2PrefixMap = unitUnderTest.getNamespaceURI2PrefixMap(); + + // Assert + Assert.assertEquals(schemaFile, unitUnderTest.getSourceFilename()); + Assert.assertEquals("http://another/namespace", unitUnderTest.getLocalNamespaceURI()); + + Assert.assertEquals(3, namespaceURI2PrefixMap.size()); + Assert.assertEquals("xs", namespaceURI2PrefixMap.get(XMLConstants.W3C_XML_SCHEMA_NS_URI)); + Assert.assertEquals("yetAnother", namespaceURI2PrefixMap.get("http://yet/another/namespace")); + Assert.assertEquals("some", namespaceURI2PrefixMap.get("http://some/namespace")); + + for (String current : namespaceURI2PrefixMap.keySet()) { + final String currentPrefix = namespaceURI2PrefixMap.get(current); + Assert.assertEquals(currentPrefix, unitUnderTest.getPrefix(current)); + } + } + + @Test(expected = IllegalArgumentException.class) + public void validateExceptionOnEmptyRelativePathToXmlFile() { + // Assemble + final String incorrectEmpty = ""; + + // Act & Assert + new SimpleNamespaceResolver(getSchemaFile(incorrectEmpty)); + Assert.fail("Creating a SimpleNamespaceResolver with empty argument " + + "should yield an IllegalArgumentException."); + } + + @Test + public void validateExceptionOnNonexistentXmlSchemaFile() { + // Assemble + final String nonExistentPath = "this/file/does/not/exist.xml"; + final File nonExistent = new File(nonExistentPath); + + // Act & Assert + try { + new SimpleNamespaceResolver(nonExistent); + Assert.fail("Creating a SimpleNamespaceResolver connected to a nonexistent file " + + "should yield an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // Expected + } catch (Exception e) { + Assert.fail("Expected IllegalArgumentException, but received [" + + e.getClass().getName() + "]"); + } + } + + @Test + public void validateJaxbNamespaceResolverComplianceInThrowingExceptionOnNullNamespaceResolverArguments() { + // Assemble + final String schemaFile = "yetAnotherSchema.xsd"; + final SimpleNamespaceResolver unitUnderTest = + new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); + final String incorrectNull = null; + + // Act & Assert + try { + unitUnderTest.getPrefix(incorrectNull); + Assert.fail("Running getPrefix with a null argument should yield an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // Expected + } catch (Exception e) { + Assert.fail("Expected IllegalArgumentException, but received [" + + e.getClass().getName() + "]"); + } + + try { + unitUnderTest.getNamespaceURI(incorrectNull); + Assert.fail("Running getNamespaceURI with a null argument should yield an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // Expected + } catch (Exception e) { + Assert.fail("Expected IllegalArgumentException, but received [" + + e.getClass().getName() + "]"); + } + + try { + unitUnderTest.getPrefixes(incorrectNull); + Assert.fail("Running getPrefixes with a null argument should yield an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + // Expected + } catch (Exception e) { + Assert.fail("Expected IllegalArgumentException, but received [" + + e.getClass().getName() + "]"); + } + } + + @Test + public void validatePrefixesIterator() { + // Assemble + final String schemaFile = "yetAnotherSchema.xsd"; + final SimpleNamespaceResolver unitUnderTest = + new SimpleNamespaceResolver(getSchemaFile(SCHEMA_DIR + schemaFile)); + + // Act + List prefixesList = new ArrayList(); + for (Iterator it = unitUnderTest.getPrefixes(XMLConstants.W3C_XML_SCHEMA_NS_URI); it.hasNext(); ) { + prefixesList.add(it.next()); + } + + // Assert + Assert.assertEquals(1, prefixesList.size()); + Assert.assertEquals("xs", prefixesList.get(0)); + } +} diff --git a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/XmlNameAnnotatedClassWithFieldAccess.java b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/XmlNameAnnotatedClassWithFieldAccess.java index e43f344d..86a1f04a 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/XmlNameAnnotatedClassWithFieldAccess.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/schemaenhancement/XmlNameAnnotatedClassWithFieldAccess.java @@ -29,8 +29,7 @@ public class XmlNameAnnotatedClassWithFieldAccess { @XmlAttribute(name = "annotatedIntegerField") private Integer integerField; - public XmlNameAnnotatedClassWithFieldAccess() { - } + public XmlNameAnnotatedClassWithFieldAccess() {} public XmlNameAnnotatedClassWithFieldAccess(final String stringField, final Integer integerField) { this.stringField = stringField; diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilitiesTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilitiesTest.java index 7166b735..2f23ba32 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilitiesTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/FileSystemUtilitiesTest.java @@ -1,15 +1,5 @@ package org.codehaus.mojo.jaxb2.shared; -import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; -import org.codehaus.mojo.jaxb2.BufferingLog; -import org.codehaus.mojo.jaxb2.shared.filters.Filter; -import org.codehaus.mojo.jaxb2.shared.filters.Filters; -import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import se.jguru.shared.algorithms.api.resources.PropertyResources; - import java.io.File; import java.net.URL; import java.net.URLDecoder; @@ -21,12 +11,21 @@ import java.util.SortedMap; import java.util.TreeMap; +import org.codehaus.mojo.jaxb2.AbstractJaxbMojo; +import org.codehaus.mojo.jaxb2.BufferingLog; +import org.codehaus.mojo.jaxb2.shared.filters.Filter; +import org.codehaus.mojo.jaxb2.shared.filters.Filters; +import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import se.jguru.shared.algorithms.api.resources.PropertyResources; + /** * @author Lennart Jörelid, jGuru Europe AB * @since 2.0 */ -public class FileSystemUtilitiesTest -{ +public class FileSystemUtilitiesTest { // Shared state private File fsUtilitiesDirectory; @@ -37,429 +36,411 @@ public class FileSystemUtilitiesTest private BufferingLog log; @Before - public void setupSharedState() - { + public void setupSharedState() { - this.log = new BufferingLog( BufferingLog.LogLevel.DEBUG ); + this.log = new BufferingLog(BufferingLog.LogLevel.DEBUG); - final URL fsUtilitiesDirUrl = getClass().getClassLoader().getResource( "testdata/shared/filesystemutilities" ); - fsUtilitiesDirectory = new File( fsUtilitiesDirUrl.getPath() ); - canonicalsDirectory = new File( fsUtilitiesDirectory, "canonicals" ); + final URL fsUtilitiesDirUrl = getClass().getClassLoader().getResource("testdata/shared/filesystemutilities"); + fsUtilitiesDirectory = new File(fsUtilitiesDirUrl.getPath()); + canonicalsDirectory = new File(fsUtilitiesDirectory, "canonicals"); - Assert.assertTrue( FileSystemUtilities.EXISTING_DIRECTORY.accept( fsUtilitiesDirectory ) ); - Assert.assertTrue( FileSystemUtilities.EXISTING_DIRECTORY.accept( canonicalsDirectory ) ); + Assert.assertTrue(FileSystemUtilities.EXISTING_DIRECTORY.accept(fsUtilitiesDirectory)); + Assert.assertTrue(FileSystemUtilities.EXISTING_DIRECTORY.accept(canonicalsDirectory)); - testFile2 = new File( fsUtilitiesDirectory, "TestFile2.txt" ); - testFile1 = new File( canonicalsDirectory, "TestFile1.txt" ); + testFile2 = new File(fsUtilitiesDirectory, "TestFile2.txt"); + testFile1 = new File(canonicalsDirectory, "TestFile1.txt"); - Assert.assertTrue( FileSystemUtilities.EXISTING_FILE.accept( testFile1 ) ); - Assert.assertTrue( FileSystemUtilities.EXISTING_FILE.accept( testFile2 ) ); + Assert.assertTrue(FileSystemUtilities.EXISTING_FILE.accept(testFile1)); + Assert.assertTrue(FileSystemUtilities.EXISTING_FILE.accept(testFile2)); - final URL testdataDir = getClass().getClassLoader().getResource( "testdata" ); - srcTestResources = new File( testdataDir.getPath() ).getParentFile(); - Assert.assertTrue( FileSystemUtilities.EXISTING_DIRECTORY.accept( srcTestResources ) ); + final URL testdataDir = getClass().getClassLoader().getResource("testdata"); + srcTestResources = new File(testdataDir.getPath()).getParentFile(); + Assert.assertTrue(FileSystemUtilities.EXISTING_DIRECTORY.accept(srcTestResources)); } @Test - public void validateGettingUrlForFile() - { + public void validateGettingUrlForFile() { // Assemble final String relativePath = "testdata/shared/filesystemutilities/canonicals/TestFile1.txt"; - final URL expected = getClass().getClassLoader().getResource( relativePath ); + final URL expected = getClass().getClassLoader().getResource(relativePath); // Act - final URL result = FileSystemUtilities.getUrlFor( testFile1 ); + final URL result = FileSystemUtilities.getUrlFor(testFile1); // Assert - Assert.assertEquals( expected, result ); + Assert.assertEquals(expected, result); } @Test - public void validateCanonicalFileAndPath() - { + public void validateCanonicalFileAndPath() { // Assemble - final File unitUnderTest = new File( canonicalsDirectory, "../TestFile2.txt" ); + final File unitUnderTest = new File(canonicalsDirectory, "../TestFile2.txt"); // Act - final String cPath1 = FileSystemUtilities.getCanonicalPath( unitUnderTest ); - final String cPath2 = FileSystemUtilities.getCanonicalPath( testFile2 ); + final String cPath1 = FileSystemUtilities.getCanonicalPath(unitUnderTest); + final String cPath2 = FileSystemUtilities.getCanonicalPath(testFile2); - final File cFile1 = FileSystemUtilities.getCanonicalFile( unitUnderTest ); - final File cFile2 = FileSystemUtilities.getCanonicalFile( testFile2 ); + final File cFile1 = FileSystemUtilities.getCanonicalFile(unitUnderTest); + final File cFile2 = FileSystemUtilities.getCanonicalFile(testFile2); // Assert - Assert.assertEquals( cPath1, cPath2 ); - Assert.assertEquals( cFile1, cFile2 ); + Assert.assertEquals(cPath1, cPath2); + Assert.assertEquals(cFile1, cFile2); } - @Test( expected = NullPointerException.class ) - public void validateExceptionOnGettingExistingFileWithRelativePathAndNullBasedir() - { + @Test(expected = NullPointerException.class) + public void validateExceptionOnGettingExistingFileWithRelativePathAndNullBasedir() { // Assemble final String relativePath = "testdata/shared/filesystemutilities/TestFile2.txt"; final File incorrectNullBaseDir = null; // Act & Assert - FileSystemUtilities.getExistingFile( relativePath, incorrectNullBaseDir ); + FileSystemUtilities.getExistingFile(relativePath, incorrectNullBaseDir); } @Test - public void validateSimplifiedFileExistenceRetrieval() - { + public void validateSimplifiedFileExistenceRetrieval() { // Assemble - final String absolutePath = FileSystemUtilities.getCanonicalPath( testFile2 ); - final String aNonExistentAbsolutePath = new File( canonicalsDirectory, "nonExistent.txt" ).getAbsolutePath(); + final String absolutePath = FileSystemUtilities.getCanonicalPath(testFile2); + final String aNonExistentAbsolutePath = new File(canonicalsDirectory, "nonExistent.txt").getAbsolutePath(); final String relativePath = "canonicals/TestFile1.txt"; final String aNonExistentRelativePath = "canonicals/doesNotExist.pdf"; // Act - final File absoluteFile = FileSystemUtilities.getExistingFile( absolutePath, null ); - final File nonExistentAbsoluteFile = FileSystemUtilities.getExistingFile( aNonExistentAbsolutePath, null ); + final File absoluteFile = FileSystemUtilities.getExistingFile(absolutePath, null); + final File nonExistentAbsoluteFile = FileSystemUtilities.getExistingFile(aNonExistentAbsolutePath, null); - final File relativeFile = FileSystemUtilities.getExistingFile( relativePath, fsUtilitiesDirectory ); - final File nonExistentRelativeFile = FileSystemUtilities.getExistingFile( aNonExistentRelativePath, - fsUtilitiesDirectory ); + final File relativeFile = FileSystemUtilities.getExistingFile(relativePath, fsUtilitiesDirectory); + final File nonExistentRelativeFile = + FileSystemUtilities.getExistingFile(aNonExistentRelativePath, fsUtilitiesDirectory); // Assert - Assert.assertNotNull( absoluteFile ); - Assert.assertNull( nonExistentAbsoluteFile ); - Assert.assertNotNull( relativeFile ); - Assert.assertNull( nonExistentRelativeFile ); + Assert.assertNotNull(absoluteFile); + Assert.assertNull(nonExistentAbsoluteFile); + Assert.assertNotNull(relativeFile); + Assert.assertNull(nonExistentRelativeFile); } - @Test( expected = NullPointerException.class ) - public void validateExceptionOnNullFileListWhenResolvingFilesAndRemovingExclusions() - { + @Test(expected = NullPointerException.class) + public void validateExceptionOnNullFileListWhenResolvingFilesAndRemovingExclusions() { // Assemble final List incorrectNullFileList = null; // Act & Assert - FileSystemUtilities.resolveRecursively( incorrectNullFileList, null, log ); + FileSystemUtilities.resolveRecursively(incorrectNullFileList, null, log); } @Test - public void validateFilteredDirectoryListingUsingIncludeFilters() - { + public void validateFilteredDirectoryListingUsingIncludeFilters() { // Assemble - final URL aDirURL = getClass().getClassLoader().getResource( "testdata/shared/filefilter/exclusion" ); - final File dir = new File( aDirURL.getPath() ); + final URL aDirURL = getClass().getClassLoader().getResource("testdata/shared/filefilter/exclusion"); + final File dir = new File(aDirURL.getPath()); - final List> textFiles = PatternFileFilter.createIncludeFilterList( log, "\\.txt" ); - final List> xmlFiles = PatternFileFilter.createIncludeFilterList( log, "\\.xml" ); - final List> allFiles = PatternFileFilter.createIncludeFilterList( log, "\\.*" ); + final List> textFiles = PatternFileFilter.createIncludeFilterList(log, "\\.txt"); + final List> xmlFiles = PatternFileFilter.createIncludeFilterList(log, "\\.xml"); + final List> allFiles = PatternFileFilter.createIncludeFilterList(log, "\\.*"); // Act & Assert - Assert.assertEquals( 2, FileSystemUtilities.listFiles( dir, allFiles, log ).size() ); + Assert.assertEquals(2, FileSystemUtilities.listFiles(dir, allFiles, log).size()); - final List textFilesList = FileSystemUtilities.listFiles( dir, textFiles, log ); - Assert.assertEquals( 1, textFilesList.size() ); - Assert.assertEquals( "TextFile.txt", textFilesList.get( 0 ).getName() ); + final List textFilesList = FileSystemUtilities.listFiles(dir, textFiles, log); + Assert.assertEquals(1, textFilesList.size()); + Assert.assertEquals("TextFile.txt", textFilesList.get(0).getName()); - final List xmlFilesList = FileSystemUtilities.listFiles( dir, xmlFiles, log ); - Assert.assertEquals( 1, xmlFilesList.size() ); - Assert.assertEquals( "AnXmlFile.xml", xmlFilesList.get( 0 ).getName() ); + final List xmlFilesList = FileSystemUtilities.listFiles(dir, xmlFiles, log); + Assert.assertEquals(1, xmlFilesList.size()); + Assert.assertEquals("AnXmlFile.xml", xmlFilesList.get(0).getName()); } @Test - @SuppressWarnings( "all" ) - public void validateFilteredDirectoryListingUsingExcludeFilters() - { + @SuppressWarnings("all") + public void validateFilteredDirectoryListingUsingExcludeFilters() { // Assemble - final URL aDirURL = getClass().getClassLoader().getResource( "testdata/shared/filefilter/exclusion" ); - final File exclusionDir = new File( aDirURL.getPath() ); + final URL aDirURL = getClass().getClassLoader().getResource("testdata/shared/filefilter/exclusion"); + final File exclusionDir = new File(aDirURL.getPath()); - final List> noTextFiles = PatternFileFilter.createExcludeFilterList( log, "\\.txt" ); - final List> noXmlFiles = PatternFileFilter.createExcludeFilterList( log, "\\.xml" ); - final List> noFiles = PatternFileFilter.createExcludeFilterList( log, "\\.*" ); + final List> noTextFiles = PatternFileFilter.createExcludeFilterList(log, "\\.txt"); + final List> noXmlFiles = PatternFileFilter.createExcludeFilterList(log, "\\.xml"); + final List> noFiles = PatternFileFilter.createExcludeFilterList(log, "\\.*"); // Act & Assert - Assert.assertEquals( 0, FileSystemUtilities.listFiles( exclusionDir, noFiles, log ).size() ); + Assert.assertEquals( + 0, FileSystemUtilities.listFiles(exclusionDir, noFiles, log).size()); - final List noXmlFilesList = FileSystemUtilities.listFiles( exclusionDir, noXmlFiles, log ); - Assert.assertEquals( 1, noXmlFilesList.size() ); - Assert.assertEquals( "TextFile.txt", noXmlFilesList.get( 0 ).getName() ); + final List noXmlFilesList = FileSystemUtilities.listFiles(exclusionDir, noXmlFiles, log); + Assert.assertEquals(1, noXmlFilesList.size()); + Assert.assertEquals("TextFile.txt", noXmlFilesList.get(0).getName()); - final List noTextFilesList = FileSystemUtilities.listFiles( exclusionDir, noTextFiles, log ); - Assert.assertEquals( 1, noTextFilesList.size() ); - Assert.assertEquals( "AnXmlFile.xml", noTextFilesList.get( 0 ).getName() ); + final List noTextFilesList = FileSystemUtilities.listFiles(exclusionDir, noTextFiles, log); + Assert.assertEquals(1, noTextFilesList.size()); + Assert.assertEquals("AnXmlFile.xml", noTextFilesList.get(0).getName()); } @Test - public void validateResolveRecursively() - { + public void validateResolveRecursively() { // Assemble - final URL fileFilterDirUrl = getClass().getClassLoader().getResource( "testdata/shared/filefilter" ); - final File fileFilterDir = new File( fileFilterDirUrl.getPath() ); + final URL fileFilterDirUrl = getClass().getClassLoader().getResource("testdata/shared/filefilter"); + final File fileFilterDir = new File(fileFilterDirUrl.getPath()); final List fileList = new ArrayList(); - fileList.add( fsUtilitiesDirectory ); - fileList.add( fileFilterDir ); + fileList.add(fsUtilitiesDirectory); + fileList.add(fileFilterDir); - final List> noTextFilesPattern = PatternFileFilter.createIncludeFilterList( log, "\\.txt" ); + final List> noTextFilesPattern = PatternFileFilter.createIncludeFilterList(log, "\\.txt"); // Act - final List result = FileSystemUtilities.resolveRecursively( fileList, noTextFilesPattern, log ); + final List result = FileSystemUtilities.resolveRecursively(fileList, noTextFilesPattern, log); // Assert - Assert.assertEquals( 1, result.size() ); - Assert.assertEquals( "AnXmlFile.xml", result.get( 0 ).getName() ); + Assert.assertEquals(1, result.size()); + Assert.assertEquals("AnXmlFile.xml", result.get(0).getName()); } @Test - public void validateDefaultExclusionsIncludeDotDirectories() - { + public void validateDefaultExclusionsIncludeDotDirectories() { // Assemble - final URL fileFilterDirUrl = getClass().getClassLoader().getResource( "testdata/shared/standard/exclusions" ); - final File fileFilterDir = new File( fileFilterDirUrl.getPath() ); + final URL fileFilterDirUrl = getClass().getClassLoader().getResource("testdata/shared/standard/exclusions"); + final File fileFilterDir = new File(fileFilterDirUrl.getPath()); final List fileList = new ArrayList(); - fileList.add( fileFilterDir ); + fileList.add(fileFilterDir); final List> standardExcludeFilters = AbstractJaxbMojo.STANDARD_EXCLUDE_FILTERS; - Filters.initialize( log, standardExcludeFilters ); + Filters.initialize(log, standardExcludeFilters); // Act - final List result = FileSystemUtilities.resolveRecursively( fileList, standardExcludeFilters, log ); + final List result = FileSystemUtilities.resolveRecursively(fileList, standardExcludeFilters, log); // Assert final StringBuilder builder = new StringBuilder(); - for ( File current : result ) - { - builder.append( current.getPath() + ", " ); + for (File current : result) { + builder.append(current.getPath() + ", "); } - Assert.assertEquals( 1, result.size() ); - Assert.assertEquals( "someFile.log", result.get( 0 ).getName() ); + Assert.assertEquals(1, result.size()); + Assert.assertEquals("someFile.log", result.get(0).getName()); } @Test - public void validateResolvingFilesAndRemovingExclusions() - { + public void validateResolvingFilesAndRemovingExclusions() { // Assemble - final URL fileFilterDirUrl = getClass().getClassLoader().getResource( "testdata/shared/filefilter" ); - final File fileFilterDir = new File( fileFilterDirUrl.getPath() ); - final File depsPropertiesFile = new File( fileFilterDir.getParentFile(), "deps1.properties" ); + final URL fileFilterDirUrl = getClass().getClassLoader().getResource("testdata/shared/filefilter"); + final File fileFilterDir = new File(fileFilterDirUrl.getPath()); + final File depsPropertiesFile = new File(fileFilterDir.getParentFile(), "deps1.properties"); final List fileList = new ArrayList(); - fileList.add( fsUtilitiesDirectory ); - fileList.add( fileFilterDir ); - fileList.add( depsPropertiesFile ); + fileList.add(fsUtilitiesDirectory); + fileList.add(fileFilterDir); + fileList.add(depsPropertiesFile); - final List> matchTextFiles = PatternFileFilter.createIncludeFilterList( log, "\\.txt" ); - final List> matchXmlFiles = PatternFileFilter.createIncludeFilterList( log, "\\.xml" ); - final List> matchNonexistentFiles = PatternFileFilter.createIncludeFilterList( log, - "\\.nonexistent" ); + final List> matchTextFiles = PatternFileFilter.createIncludeFilterList(log, "\\.txt"); + final List> matchXmlFiles = PatternFileFilter.createIncludeFilterList(log, "\\.xml"); + final List> matchNonexistentFiles = + PatternFileFilter.createIncludeFilterList(log, "\\.nonexistent"); // Act - final List noTextFiles = FileSystemUtilities.resolveRecursively( fileList, matchTextFiles, log ); - final List noXmlFiles = FileSystemUtilities.resolveRecursively( fileList, matchXmlFiles, log ); - final List allFiles = FileSystemUtilities.resolveRecursively( fileList, matchNonexistentFiles, log ); - final List noFilterFiles = FileSystemUtilities.resolveRecursively( fileList, null, log ); + final List noTextFiles = FileSystemUtilities.resolveRecursively(fileList, matchTextFiles, log); + final List noXmlFiles = FileSystemUtilities.resolveRecursively(fileList, matchXmlFiles, log); + final List allFiles = FileSystemUtilities.resolveRecursively(fileList, matchNonexistentFiles, log); + final List noFilterFiles = FileSystemUtilities.resolveRecursively(fileList, null, log); // Assert - Assert.assertEquals( 2, noTextFiles.size() ); - Assert.assertEquals( 4, noXmlFiles.size() ); - Assert.assertEquals( 5, allFiles.size() ); - Assert.assertEquals( 5, noFilterFiles.size() ); - - final List canonicalPathsForExplicitlyAddedFiles = getRelativeCanonicalPaths( noFilterFiles, - depsPropertiesFile.getParentFile() ); - Assert.assertTrue( canonicalPathsForExplicitlyAddedFiles.contains( "/deps1.properties" ) ); - - final List canonicalPathsForNoTextFiles = getRelativeCanonicalPaths( noTextFiles, - depsPropertiesFile.getParentFile() ); - Assert.assertTrue( canonicalPathsForNoTextFiles.contains( "/deps1.properties" ) ); - Assert.assertTrue( canonicalPathsForNoTextFiles.contains( "/filefilter/exclusion/AnXmlFile.xml" ) ); - - final List canonicalPathsForNoXmlFiles = getRelativeCanonicalPaths( noXmlFiles, - depsPropertiesFile.getParentFile() ); - Assert.assertTrue( canonicalPathsForNoXmlFiles.contains( "/deps1.properties" ) ); - Assert.assertTrue( canonicalPathsForNoXmlFiles.contains( "/filefilter/exclusion/TextFile.txt" ) ); - Assert.assertTrue( canonicalPathsForNoXmlFiles.contains( "/filesystemutilities/TestFile2.txt" ) ); - Assert.assertTrue( canonicalPathsForNoXmlFiles.contains( "/filesystemutilities/canonicals/TestFile1.txt" ) ); - - final List canonicalPathsForAllFiles = getRelativeCanonicalPaths( allFiles, - depsPropertiesFile.getParentFile() ); - Assert.assertTrue( canonicalPathsForAllFiles.contains( "/deps1.properties" ) ); - Assert.assertTrue( canonicalPathsForAllFiles.contains( "/filefilter/exclusion/TextFile.txt" ) ); - Assert.assertTrue( canonicalPathsForAllFiles.contains( "/filesystemutilities/TestFile2.txt" ) ); - Assert.assertTrue( canonicalPathsForAllFiles.contains( "/filesystemutilities/canonicals/TestFile1.txt" ) ); - Assert.assertTrue( canonicalPathsForAllFiles.contains( "/filefilter/exclusion/AnXmlFile.xml" ) ); + Assert.assertEquals(2, noTextFiles.size()); + Assert.assertEquals(4, noXmlFiles.size()); + Assert.assertEquals(5, allFiles.size()); + Assert.assertEquals(5, noFilterFiles.size()); + + final List canonicalPathsForExplicitlyAddedFiles = + getRelativeCanonicalPaths(noFilterFiles, depsPropertiesFile.getParentFile()); + Assert.assertTrue(canonicalPathsForExplicitlyAddedFiles.contains("/deps1.properties")); + + final List canonicalPathsForNoTextFiles = + getRelativeCanonicalPaths(noTextFiles, depsPropertiesFile.getParentFile()); + Assert.assertTrue(canonicalPathsForNoTextFiles.contains("/deps1.properties")); + Assert.assertTrue(canonicalPathsForNoTextFiles.contains("/filefilter/exclusion/AnXmlFile.xml")); + + final List canonicalPathsForNoXmlFiles = + getRelativeCanonicalPaths(noXmlFiles, depsPropertiesFile.getParentFile()); + Assert.assertTrue(canonicalPathsForNoXmlFiles.contains("/deps1.properties")); + Assert.assertTrue(canonicalPathsForNoXmlFiles.contains("/filefilter/exclusion/TextFile.txt")); + Assert.assertTrue(canonicalPathsForNoXmlFiles.contains("/filesystemutilities/TestFile2.txt")); + Assert.assertTrue(canonicalPathsForNoXmlFiles.contains("/filesystemutilities/canonicals/TestFile1.txt")); + + final List canonicalPathsForAllFiles = + getRelativeCanonicalPaths(allFiles, depsPropertiesFile.getParentFile()); + Assert.assertTrue(canonicalPathsForAllFiles.contains("/deps1.properties")); + Assert.assertTrue(canonicalPathsForAllFiles.contains("/filefilter/exclusion/TextFile.txt")); + Assert.assertTrue(canonicalPathsForAllFiles.contains("/filesystemutilities/TestFile2.txt")); + Assert.assertTrue(canonicalPathsForAllFiles.contains("/filesystemutilities/canonicals/TestFile1.txt")); + Assert.assertTrue(canonicalPathsForAllFiles.contains("/filefilter/exclusion/AnXmlFile.xml")); } @Test - public void validateBufferingLog() - { + public void validateBufferingLog() { // Assemble - final BufferingLog log = new BufferingLog( BufferingLog.LogLevel.INFO ); + final BufferingLog log = new BufferingLog(BufferingLog.LogLevel.INFO); // Act - log.debug( "debug" ); - log.info( "info", new NullPointerException( "Blah!" ) ); - log.warn( "warn" ); - log.error( new IllegalArgumentException( "Gnat" ) ); + log.debug("debug"); + log.info("info", new NullPointerException("Blah!")); + log.warn("warn"); + log.error(new IllegalArgumentException("Gnat")); // Assert final SortedMap logBuffer = log.getLogBuffer(); - final List keys = new ArrayList( logBuffer.keySet() ); + final List keys = new ArrayList(logBuffer.keySet()); - Assert.assertEquals( 3, keys.size() ); + Assert.assertEquals(3, keys.size()); - Assert.assertEquals( "000: (INFO) info", keys.get( 0 ) ); - Assert.assertEquals( "001: (WARN) warn", keys.get( 1 ) ); - Assert.assertEquals( "002: (ERROR) ", keys.get( 2 ) ); + Assert.assertEquals("000: (INFO) info", keys.get(0)); + Assert.assertEquals("001: (WARN) warn", keys.get(1)); + Assert.assertEquals("002: (ERROR) ", keys.get(2)); - Assert.assertEquals( "Blah!", logBuffer.get( keys.get( 0 ) ).getMessage() ); - Assert.assertNull( logBuffer.get( keys.get( 1 ) ) ); - Assert.assertTrue( logBuffer.get( keys.get( 2 ) ) instanceof IllegalArgumentException ); + Assert.assertEquals("Blah!", logBuffer.get(keys.get(0)).getMessage()); + Assert.assertNull(logBuffer.get(keys.get(1))); + Assert.assertTrue(logBuffer.get(keys.get(2)) instanceof IllegalArgumentException); } @Test - public void validateFilteringFiles() - { + public void validateFilteringFiles() { // Assemble - final BufferingLog log = new BufferingLog( BufferingLog.LogLevel.DEBUG ); - final URL sharedDirUrl = getClass().getClassLoader().getResource( "testdata/shared" ); - final File basedir = new File( sharedDirUrl.getPath() ); - final List> excludeTextFiles = PatternFileFilter.createIncludeFilterList( log, "txt" ); + final BufferingLog log = new BufferingLog(BufferingLog.LogLevel.DEBUG); + final URL sharedDirUrl = getClass().getClassLoader().getResource("testdata/shared"); + final File basedir = new File(sharedDirUrl.getPath()); + final List> excludeTextFiles = PatternFileFilter.createIncludeFilterList(log, "txt"); // Act - final List result = FileSystemUtilities.filterFiles( basedir, null, "filefilter/exclusion", log, - "testFiles", excludeTextFiles ); + final List result = FileSystemUtilities.filterFiles( + basedir, null, "filefilter/exclusion", log, "testFiles", excludeTextFiles); // Assert - Assert.assertEquals( 1, result.size() ); + Assert.assertEquals(1, result.size()); - final File theFile = result.get( 0 ); - Assert.assertEquals( "AnXmlFile.xml", theFile.getName() ); + final File theFile = result.get(0); + Assert.assertEquals("AnXmlFile.xml", theFile.getName()); } @Test - public void validateFilterFilesWithSuppliedSourcesAndExcludePatterns() - { + public void validateFilterFilesWithSuppliedSourcesAndExcludePatterns() { // Assemble - final BufferingLog log = new BufferingLog( BufferingLog.LogLevel.DEBUG ); - final List sources = Arrays.asList( "filefilter/exclusion/AnXmlFile.xml", - "filefilter/exclusion/TextFile.txt" ); - final URL sharedDirUrl = getClass().getClassLoader().getResource( "testdata/shared" ); - final File basedir = new File( sharedDirUrl.getPath() ); - final List> excludeTextFiles = PatternFileFilter.createIncludeFilterList( log, "\\.txt" ); + final BufferingLog log = new BufferingLog(BufferingLog.LogLevel.DEBUG); + final List sources = + Arrays.asList("filefilter/exclusion/AnXmlFile.xml", "filefilter/exclusion/TextFile.txt"); + final URL sharedDirUrl = getClass().getClassLoader().getResource("testdata/shared"); + final File basedir = new File(sharedDirUrl.getPath()); + final List> excludeTextFiles = PatternFileFilter.createIncludeFilterList(log, "\\.txt"); // Act - final List result = FileSystemUtilities.filterFiles( basedir, sources, "filefilter/exclusion", log, - "testFiles", excludeTextFiles ); + final List result = FileSystemUtilities.filterFiles( + basedir, sources, "filefilter/exclusion", log, "testFiles", excludeTextFiles); // Assert - Assert.assertEquals( 1, result.size() ); + Assert.assertEquals(1, result.size()); - final File theFile = result.get( 0 ); - Assert.assertEquals( "AnXmlFile.xml", theFile.getName() ); + final File theFile = result.get(0); + Assert.assertEquals("AnXmlFile.xml", theFile.getName()); } @Test - public void validateGettingFileForJar() - { + public void validateGettingFileForJar() { // Assemble final String jarPath = "testdata/shared/nazgul-tools-validation-aspect-4.0.1.jar"; - final URL resource = getClass().getClassLoader().getResource( jarPath ); - Assert.assertNotNull( resource ); + final URL resource = getClass().getClassLoader().getResource(jarPath); + Assert.assertNotNull(resource); // Act - final File jarFile = FileSystemUtilities.getFileFor( resource, "UTF-8" ); - final String relativized = FileSystemUtilities.relativize( jarFile.getPath(), srcTestResources, true ); + final File jarFile = FileSystemUtilities.getFileFor(resource, "UTF-8"); + final String relativized = FileSystemUtilities.relativize(jarFile.getPath(), srcTestResources, true); // Assert - Assert.assertTrue( jarFile.exists() ); - Assert.assertTrue( jarFile.isFile() ); - Assert.assertEquals( jarPath.replace( "/", File.separator ), relativized ); + Assert.assertTrue(jarFile.exists()); + Assert.assertTrue(jarFile.isFile()); + Assert.assertEquals(jarPath.replace("/", File.separator), relativized); } @Test - public void validateGettingFileForClassURL() - { + public void validateGettingFileForClassURL() { // Assemble - final URL streamingDhURL = PropertyResources.class.getProtectionDomain().getCodeSource().getLocation(); - Assert.assertNotNull( streamingDhURL ); + final URL streamingDhURL = + PropertyResources.class.getProtectionDomain().getCodeSource().getLocation(); + Assert.assertNotNull(streamingDhURL); // Act - final File jarFile = FileSystemUtilities.getFileFor( streamingDhURL, "UTF-8" ); + final File jarFile = FileSystemUtilities.getFileFor(streamingDhURL, "UTF-8"); // Assert - Assert.assertTrue( jarFile.exists() ); - Assert.assertTrue( jarFile.isFile() ); + Assert.assertTrue(jarFile.exists()); + Assert.assertTrue(jarFile.isFile()); } @Test - public void validateGettingFileForClassResourceURL() - { + public void validateGettingFileForClassResourceURL() { // Assemble - final String classResource = PropertyResources.class.getName().replace( ".", "/" ) + ".class"; - final URL resource = getClass().getClassLoader().getResource( classResource ); - Assert.assertNotNull( resource ); + final String classResource = PropertyResources.class.getName().replace(".", "/") + ".class"; + final URL resource = getClass().getClassLoader().getResource(classResource); + Assert.assertNotNull(resource); // Act - final File jarFile = FileSystemUtilities.getFileFor( resource, "UTF-8" ); + final File jarFile = FileSystemUtilities.getFileFor(resource, "UTF-8"); // Assert - Assert.assertTrue( jarFile.exists() ); - Assert.assertTrue( jarFile.isFile() ); + Assert.assertTrue(jarFile.exists()); + Assert.assertTrue(jarFile.isFile()); } @Test - public void validateUrlEncodingAndDecoding() throws Exception - { + public void validateUrlEncodingAndDecoding() throws Exception { // Assemble final String resourcePath = "testdata/shared/urlhandling/file with spaces.txt"; - final URL dirUrl = getClass().getClassLoader().getResource( resourcePath ); - Assert.assertNotNull( dirUrl ); + final URL dirUrl = getClass().getClassLoader().getResource(resourcePath); + Assert.assertNotNull(dirUrl); // Act final String normalizedPath = dirUrl.toURI().normalize().toURL().getPath(); - final String decoded = URLDecoder.decode( normalizedPath, "UTF-8" ); + final String decoded = URLDecoder.decode(normalizedPath, "UTF-8"); // Assert - Assert.assertTrue( normalizedPath.endsWith( "file%20with%20spaces.txt" ) ); - Assert.assertTrue( decoded.endsWith( "file with spaces.txt" ) ); + Assert.assertTrue(normalizedPath.endsWith("file%20with%20spaces.txt")); + Assert.assertTrue(decoded.endsWith("file with spaces.txt")); } @Test - public void validateRelativizingPaths() throws Exception - { + public void validateRelativizingPaths() throws Exception { // Assemble final String path = "/project/backend/foobar/my-schema.xsd"; final SortedMap parentDir2Expected = new TreeMap<>(); - parentDir2Expected.put( "/", "project/backend/foobar/my-schema.xsd" ); - parentDir2Expected.put( "", "project/backend/foobar/my-schema.xsd" ); - parentDir2Expected.put( "/project", "backend/foobar/my-schema.xsd" ); - parentDir2Expected.put( "/not/a/path", "project/backend/foobar/my-schema.xsd" ); - parentDir2Expected.put( "/project/", "backend/foobar/my-schema.xsd" ); + parentDir2Expected.put("/", "project/backend/foobar/my-schema.xsd"); + parentDir2Expected.put("", "project/backend/foobar/my-schema.xsd"); + parentDir2Expected.put("/project", "backend/foobar/my-schema.xsd"); + parentDir2Expected.put("/not/a/path", "project/backend/foobar/my-schema.xsd"); + parentDir2Expected.put("/project/", "backend/foobar/my-schema.xsd"); // Act & Assert - for ( Map.Entry current : parentDir2Expected.entrySet() ) - { + for (Map.Entry current : parentDir2Expected.entrySet()) { - final String expectedMessage = "Given parent dir [" + current.getKey() + "], expected [" + current.getValue() + "] from [" + path + "] but found: "; + final String expectedMessage = "Given parent dir [" + current.getKey() + "], expected [" + + current.getValue() + "] from [" + path + "] but found: "; - final String result = FileSystemUtilities.relativize( path, new File( current.getKey() ), true ); + final String result = FileSystemUtilities.relativize(path, new File(current.getKey()), true); - Assert.assertEquals( expectedMessage + result, current.getValue(), result ); + Assert.assertEquals(expectedMessage + result, current.getValue(), result); } } @@ -467,25 +448,22 @@ public void validateRelativizingPaths() throws Exception // Private helpers // - private List getRelativeCanonicalPaths( final List fileList, final File cutoff ) - { + private List getRelativeCanonicalPaths(final List fileList, final File cutoff) { - final String cutoffPath = FileSystemUtilities.getCanonicalPath( cutoff ).replace( File.separator, "/" ); + final String cutoffPath = FileSystemUtilities.getCanonicalPath(cutoff).replace(File.separator, "/"); final List toReturn = new ArrayList(); - for ( File current : fileList ) - { + for (File current : fileList) { - final String canPath = FileSystemUtilities.getCanonicalPath( current ).replace( File.separator, "/" ); - if ( !canPath.startsWith( cutoffPath ) ) - { - throw new IllegalArgumentException( - "Illegal cutoff provided. Cutoff: [" + cutoffPath + "] must be a parent to CanonicalPath [" + canPath + "]" ); + final String canPath = FileSystemUtilities.getCanonicalPath(current).replace(File.separator, "/"); + if (!canPath.startsWith(cutoffPath)) { + throw new IllegalArgumentException("Illegal cutoff provided. Cutoff: [" + cutoffPath + + "] must be a parent to CanonicalPath [" + canPath + "]"); } - toReturn.add( canPath.substring( cutoffPath.length() ) ); + toReturn.add(canPath.substring(cutoffPath.length())); } - Collections.sort( toReturn ); + Collections.sort(toReturn); return toReturn; } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilderTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilderTest.java index 0739fc1f..5984859f 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilderTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/arguments/ArgumentBuilderTest.java @@ -55,10 +55,8 @@ public void validateArgumentOrder() { final ArgumentBuilder unitUnderTest = new ArgumentBuilder(); // Act - final String[] result = unitUnderTest - .withFlag(true, "flag1") - .withFlag(true, "-flag2") - .build(); + final String[] result = + unitUnderTest.withFlag(true, "flag1").withFlag(true, "-flag2").build(); // Assert Assert.assertEquals(2, result.length); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/classloader/ThreadContextClassLoaderBuilderTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/classloader/ThreadContextClassLoaderBuilderTest.java index d22b945c..f98e6205 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/classloader/ThreadContextClassLoaderBuilderTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/classloader/ThreadContextClassLoaderBuilderTest.java @@ -1,5 +1,11 @@ package org.codehaus.mojo.jaxb2.shared.classloader; +import java.io.File; +import java.net.URL; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; import org.codehaus.mojo.jaxb2.shared.JavaVersion; @@ -8,20 +14,13 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; import org.junit.Ignore; +import org.junit.Test; /** * @author Lennart Jörelid, jGuru Europe AB */ -public class ThreadContextClassLoaderBuilderTest -{ +public class ThreadContextClassLoaderBuilderTest { // Shared state private ThreadContextClassLoaderHolder holder; private URL extraClassLoaderDirURL; @@ -31,52 +30,46 @@ public class ThreadContextClassLoaderBuilderTest private String encoding = "UTF-8"; @Before - public void setupSharedState() - { + public void setupSharedState() { - log = new BufferingLog( BufferingLog.LogLevel.DEBUG ); + log = new BufferingLog(BufferingLog.LogLevel.DEBUG); final String extraPath = "testdata/shared/classloader"; - extraClassLoaderDirURL = getClass().getClassLoader().getResource( extraPath ); - Assert.assertNotNull( extraClassLoaderDirURL ); + extraClassLoaderDirURL = getClass().getClassLoader().getResource(extraPath); + Assert.assertNotNull(extraClassLoaderDirURL); - extraClassLoaderDirFile = new File( extraClassLoaderDirURL.getPath() ); - Assert.assertTrue( extraClassLoaderDirFile.exists() && extraClassLoaderDirFile.isDirectory() ); + extraClassLoaderDirFile = new File(extraClassLoaderDirURL.getPath()); + Assert.assertTrue(extraClassLoaderDirFile.exists() && extraClassLoaderDirFile.isDirectory()); // Stash the original ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); } @After - public void teardownSharedState() - { - if ( holder != null ) - { + public void teardownSharedState() { + if (holder != null) { holder.restoreClassLoaderAndReleaseThread(); - } - else - { - Thread.currentThread().setContextClassLoader( originalClassLoader ); + } else { + Thread.currentThread().setContextClassLoader(originalClassLoader); } } @Test @Ignore - public void validateAddingURLsToThreadContextClassLoader() throws Exception - { + public void validateAddingURLsToThreadContextClassLoader() throws Exception { // Assemble final int numExpectedResources = JavaVersion.isJdk8OrLower() ? 3 : 6; - holder = ThreadContextClassLoaderBuilder.createFor( originalClassLoader, log, encoding ).addURL( - extraClassLoaderDirURL ).buildAndSet(); + holder = ThreadContextClassLoaderBuilder.createFor(originalClassLoader, log, encoding) + .addURL(extraClassLoaderDirURL) + .buildAndSet(); // Act final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader(); - final List resources = Collections.list( ctxClassLoader.getResources( "" ) ); + final List resources = Collections.list(ctxClassLoader.getResources("")); - for ( int i = 0; i < resources.size(); i++ ) - { - System.out.println( " Resource [" + i + "]: " + resources.get( i ).toString() ); + for (int i = 0; i < resources.size(); i++) { + System.out.println(" Resource [" + i + "]: " + resources.get(i).toString()); } /* @@ -103,109 +96,102 @@ public void validateAddingURLsToThreadContextClassLoader() throws Exception // Assert Assert.assertEquals( - "Expected [" + numExpectedResources + "] resources but got [" + resources.size() + "]: " + getNewLineSeparated( - resources ), numExpectedResources, resources.size() ); + "Expected [" + numExpectedResources + "] resources but got [" + resources.size() + "]: " + + getNewLineSeparated(resources), + numExpectedResources, + resources.size()); // validateContains(resources, "target/classes"); - validateContains( resources, "target/test-classes" ); - validateContains( resources, "target/test-classes/testdata/shared/classloader" ); + validateContains(resources, "target/test-classes"); + validateContains(resources, "target/test-classes/testdata/shared/classloader"); - for ( URL current : resources ) - { + for (URL current : resources) { - if ( current.getProtocol().equalsIgnoreCase( "file" ) ) - { + if (current.getProtocol().equalsIgnoreCase("file")) { - final File aFile = new File( current.getPath() ); - Assert.assertTrue( aFile.exists() && aFile.isDirectory() ); + final File aFile = new File(current.getPath()); + Assert.assertTrue(aFile.exists() && aFile.isDirectory()); - } - else if ( current.getProtocol().equalsIgnoreCase( "jar" ) ) - { + } else if (current.getProtocol().equalsIgnoreCase("jar")) { // This happens in JDK 9 - Assert.assertTrue( current.toString().contains( "!/META-INF/versions/" ) ); + Assert.assertTrue(current.toString().contains("!/META-INF/versions/")); } } } @Test - public void validateResourceAccessInAugmentedClassLoader() - { + public void validateResourceAccessInAugmentedClassLoader() { // Assemble - holder = ThreadContextClassLoaderBuilder.createFor( originalClassLoader, log, encoding ).addURL( - extraClassLoaderDirURL ).buildAndSet(); + holder = ThreadContextClassLoaderBuilder.createFor(originalClassLoader, log, encoding) + .addURL(extraClassLoaderDirURL) + .buildAndSet(); // Act final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader(); - final URL immediateResource = ctxClassLoader.getResource( "ImmediateTestResource.txt" ); - final URL subResource = ctxClassLoader.getResource( "subdirectory/SubdirectoryTestResource.txt" ); + final URL immediateResource = ctxClassLoader.getResource("ImmediateTestResource.txt"); + final URL subResource = ctxClassLoader.getResource("subdirectory/SubdirectoryTestResource.txt"); // Assert - Assert.assertNotNull( immediateResource ); - Assert.assertNotNull( subResource ); + Assert.assertNotNull(immediateResource); + Assert.assertNotNull(subResource); - final File immediateFile = new File( immediateResource.getPath() ); - final File subFile = new File( subResource.getPath() ); + final File immediateFile = new File(immediateResource.getPath()); + final File subFile = new File(subResource.getPath()); - Assert.assertTrue( immediateFile.exists() && immediateFile.isFile() ); - Assert.assertTrue( subFile.exists() && subFile.isFile() ); + Assert.assertTrue(immediateFile.exists() && immediateFile.isFile()); + Assert.assertTrue(subFile.exists() && subFile.isFile()); } @Test - public void validateLoadingResourcesInJars() - { + public void validateLoadingResourcesInJars() { // Assemble - final File theJar = new File( extraClassLoaderDirFile, "jarSubDirectory/aJarWithResources.jar" ); + final File theJar = new File(extraClassLoaderDirFile, "jarSubDirectory/aJarWithResources.jar"); - holder = ThreadContextClassLoaderBuilder.createFor( originalClassLoader, log, encoding ).addPath( - FileSystemUtilities.getCanonicalPath( theJar ) ).buildAndSet(); + holder = ThreadContextClassLoaderBuilder.createFor(originalClassLoader, log, encoding) + .addPath(FileSystemUtilities.getCanonicalPath(theJar)) + .buildAndSet(); // Act final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader(); - final URL containedTopLevelResource = ctxClassLoader.getResource( "ContainedFileResource.txt" ); - final URL containedSubLevelResource = ctxClassLoader.getResource( "internalSubDir/SubContainedResource.txt" ); + final URL containedTopLevelResource = ctxClassLoader.getResource("ContainedFileResource.txt"); + final URL containedSubLevelResource = ctxClassLoader.getResource("internalSubDir/SubContainedResource.txt"); // Assert - Assert.assertNotNull( containedTopLevelResource ); - Assert.assertNotNull( containedSubLevelResource ); + Assert.assertNotNull(containedTopLevelResource); + Assert.assertNotNull(containedSubLevelResource); } // // Private helpers // - private String getNewLineSeparated( final List resources ) - { + private String getNewLineSeparated(final List resources) { final StringBuilder toReturn = new StringBuilder(); final AtomicInteger index = new AtomicInteger(); - for ( URL current : resources ) - { + for (URL current : resources) { final String urlIndex = "[" + index.getAndIncrement() + "]: "; - toReturn.append(urlIndex).append( current.toString() ).append( "\n" ); + toReturn.append(urlIndex).append(current.toString()).append("\n"); } // All Done. final String fullString = toReturn.toString(); - return fullString.substring( 0, fullString.length() - 2 ); + return fullString.substring(0, fullString.length() - 2); } - private void validateContains( final List resources, final String snippet ) - { + private void validateContains(final List resources, final String snippet) { - for ( URL current : resources ) - { - if ( current.toString().contains( snippet ) ) - { + for (URL current : resources) { + if (current.toString().contains(snippet)) { return; } } - Assert.fail( "Snippet [" + snippet + "] was not found within URL resources." ); + Assert.fail("Snippet [" + snippet + "] was not found within URL resources."); } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacetTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacetTest.java index f8138f9e..13ddf6e6 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacetTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/locale/LocaleFacetTest.java @@ -1,16 +1,16 @@ package org.codehaus.mojo.jaxb2.shared.environment.locale; +import java.util.Locale; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + import org.apache.maven.plugin.MojoExecutionException; import org.codehaus.mojo.jaxb2.BufferingLog; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.Locale; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -63,7 +63,8 @@ public void validateOptimalLocaleFindingIgnoringScripts() throws MojoExecutionEx // Ignore Locales with Scripts. if (script == null) { - Assert.assertSame(Locale.forLanguageTag(current.getValue().toLanguageTag()), + Assert.assertSame( + Locale.forLanguageTag(current.getValue().toLanguageTag()), LocaleFacet.findOptimumLocale(language, country, variant)); } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacetTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacetTest.java index 9642c44d..c89a80e2 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacetTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/environment/sysprops/SystemPropertySaveEnvironmentFacetTest.java @@ -1,17 +1,18 @@ package org.codehaus.mojo.jaxb2.shared.environment.sysprops; -import static org.junit.Assert.assertEquals; - import org.codehaus.mojo.jaxb2.BufferingLog; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class SystemPropertySaveEnvironmentFacetTest { private static final String PROPERTY_KEY_NOT_SAVED = "some.other.property"; private static final String PROPERTY_KEY_SAVED = "http.proxyHost"; private SystemPropertySaveEnvironmentFacet createAndSetupFacet() { final BufferingLog log = new BufferingLog(BufferingLog.LogLevel.DEBUG); - final SystemPropertySaveEnvironmentFacet facet = new SystemPropertySaveEnvironmentFacet(PROPERTY_KEY_SAVED, log); + final SystemPropertySaveEnvironmentFacet facet = + new SystemPropertySaveEnvironmentFacet(PROPERTY_KEY_SAVED, log); facet.setup(); return facet; } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/FiltersTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/FiltersTest.java index 3a7a793f..c46a995d 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/FiltersTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/FiltersTest.java @@ -1,16 +1,16 @@ package org.codehaus.mojo.jaxb2.shared.filters; +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - /** * @author Lennart Jörelid, jGuru Europe AB */ diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/PackageFilterInclusionTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/PackageFilterInclusionTest.java index 74ce1b4e..a17826c2 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/PackageFilterInclusionTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/PackageFilterInclusionTest.java @@ -1,13 +1,5 @@ package org.codehaus.mojo.jaxb2.shared.filters; -import org.codehaus.mojo.jaxb2.BufferingLog; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.codehaus.mojo.jaxb2.shared.filters.pattern.FileFilterAdapter; -import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import java.io.File; import java.io.FileFilter; import java.util.ArrayList; @@ -16,6 +8,14 @@ import java.util.SortedMap; import java.util.TreeMap; +import org.codehaus.mojo.jaxb2.BufferingLog; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.codehaus.mojo.jaxb2.shared.filters.pattern.FileFilterAdapter; +import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + import static java.io.File.separator; /** @@ -36,7 +36,10 @@ public void setupSharedState() { String basedir = System.getProperty("basedir"); if (basedir == null) { - baseDirectory = new File(getClass().getClassLoader().getResource("logback-test.xml").getPath()) + baseDirectory = new File(getClass() + .getClassLoader() + .getResource("logback-test.xml") + .getPath()) .getParentFile() .getParentFile() .getParentFile(); @@ -56,16 +59,15 @@ public void setupSharedState() { public void validateExcludingPackageInfoFiles() { // Assemble - final String rootPackagePath = contextRoot + separator + "org" + separator + "codehaus" + separator + "mojo" - + separator + "jaxb2"; + final String rootPackagePath = + contextRoot + separator + "org" + separator + "codehaus" + separator + "mojo" + separator + "jaxb2"; final String excludeFilenamePattern = "package-info\\.java"; - final List> excludedFilesIdentifierFilter = PatternFileFilter - .createIncludeFilterList(log, excludeFilenamePattern); + final List> excludedFilesIdentifierFilter = + PatternFileFilter.createIncludeFilterList(log, excludeFilenamePattern); // Act - final List sourceFiles = FileSystemUtilities.resolveRecursively(Collections.singletonList(srcMainJavaDir), - excludedFilesIdentifierFilter, - log); + final List sourceFiles = FileSystemUtilities.resolveRecursively( + Collections.singletonList(srcMainJavaDir), excludedFilesIdentifierFilter, log); final SortedMap path2FileMap = mapFiles(sourceFiles); // Assert @@ -75,10 +77,10 @@ public void validateExcludingPackageInfoFiles() { ? current.substring(baseDirectory.getPath().length() + 1) : current; - Assert.assertTrue("Path " + relativePath + " did not start with the root package path " + rootPackagePath, + Assert.assertTrue( + "Path " + relativePath + " did not start with the root package path " + rootPackagePath, relativePath.startsWith(rootPackagePath)); - Assert.assertTrue("Path " + current + " was a package-info.java file.", - !current.contains("package-info")); + Assert.assertTrue("Path " + current + " was a package-info.java file.", !current.contains("package-info")); } } @@ -96,9 +98,7 @@ public boolean accept(final File pathname) { includeFilter.initialize(log); final List allSourceFiles = FileSystemUtilities.resolveRecursively( - Collections.singletonList(srcMainJavaDir), - new ArrayList>(), - log); + Collections.singletonList(srcMainJavaDir), new ArrayList>(), log); // Act final List result = FileSystemUtilities.filterFiles(allSourceFiles, includeFilter, log); @@ -107,7 +107,8 @@ public boolean accept(final File pathname) { // Assert Assert.assertTrue(result.size() > 1); for (String current : path2FileMap.keySet()) { - Assert.assertTrue("Path " + current + " contained disallowed pattern " + locationPackageDirName, + Assert.assertTrue( + "Path " + current + " contained disallowed pattern " + locationPackageDirName, current.contains(locationPackageDirName)); } } diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/T_AbstractFilterTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/T_AbstractFilterTest.java index c463f773..b7427488 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/T_AbstractFilterTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/T_AbstractFilterTest.java @@ -1,12 +1,12 @@ package org.codehaus.mojo.jaxb2.shared.filters; +import java.util.SortedMap; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.SortedMap; - /** * @author Lennart Jörelid, jGuru Europe AB */ diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilterTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilterTest.java index 5fa57022..4549d49a 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilterTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/AbstractPatternFilterTest.java @@ -1,15 +1,15 @@ package org.codehaus.mojo.jaxb2.shared.filters.pattern; -import org.codehaus.mojo.jaxb2.BufferingLog; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.junit.Assert; -import org.junit.Before; - import java.io.File; import java.net.URL; import java.util.Map; import java.util.TreeMap; +import org.codehaus.mojo.jaxb2.BufferingLog; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.junit.Assert; +import org.junit.Before; + /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -52,9 +52,8 @@ protected void onSetup() { // Do nothing } - protected Map applyFilterAndRetrieveResults(final AbstractPatternFilter unitUnderTest, - final T[] candidates, - final StringConverter converter) { + protected Map applyFilterAndRetrieveResults( + final AbstractPatternFilter unitUnderTest, final T[] candidates, final StringConverter converter) { Map toReturn = new TreeMap(); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/DebugPatternFilter.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/DebugPatternFilter.java index d48717a3..cb7f5bed 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/DebugPatternFilter.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/DebugPatternFilter.java @@ -19,10 +19,11 @@ public DebugPatternFilter(final List patterns, final boolean acceptCandi setAcceptCandidateOnPatternMatch(acceptCandidateOnPatternMatch); } - public DebugPatternFilter(final boolean processNullValues, - final List patterns, - final StringConverter converter, - final boolean acceptCandidateOnPatternMatch) { + public DebugPatternFilter( + final boolean processNullValues, + final List patterns, + final StringConverter converter, + final boolean acceptCandidateOnPatternMatch) { super(); setProcessNullValues(processNullValues); setPatterns(patterns); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilterTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilterTest.java index 7e2ccedd..7912fdb7 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilterTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternFileFilterTest.java @@ -1,13 +1,13 @@ package org.codehaus.mojo.jaxb2.shared.filters.pattern; -import org.junit.Assert; -import org.junit.Test; - import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Map; +import org.junit.Assert; +import org.junit.Test; + /** * @author Lennart Jörelid, jGuru Europe AB */ diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilterTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilterTest.java index 59234d2c..62204425 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilterTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/PatternURLFilterTest.java @@ -1,15 +1,15 @@ package org.codehaus.mojo.jaxb2.shared.filters.pattern; -import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; -import org.junit.Assert; -import org.junit.Test; - import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; +import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; +import org.junit.Assert; +import org.junit.Test; + /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -54,9 +54,8 @@ public void validateAcceptNothingOnNullPatterns() { // Act unitUnderTest.initialize(log); - final Map result = applyFilterAndRetrieveResults(unitUnderTest, - urlList, - PatternURLFilter.NORMALIZED_URL_CONVERTER); + final Map result = + applyFilterAndRetrieveResults(unitUnderTest, urlList, PatternURLFilter.NORMALIZED_URL_CONVERTER); // Assert for (Map.Entry current : result.entrySet()) { @@ -69,17 +68,15 @@ public void validateExcludingMatchingURLs() { // Assemble final String urlProtocol = "file"; - final List txtFileSuffixExclusion = Arrays.asList(urlProtocol + ":/" - + PatternFileFilter.PATTERN_LETTER_DIGIT_PUNCT + "\\.txt"); + final List txtFileSuffixExclusion = + Arrays.asList(urlProtocol + ":/" + PatternFileFilter.PATTERN_LETTER_DIGIT_PUNCT + "\\.txt"); final PatternURLFilter unitUnderTest = new PatternURLFilter(txtFileSuffixExclusion); unitUnderTest.setAcceptCandidateOnPatternMatch(false); unitUnderTest.initialize(log); // Act - final Map result = applyFilterAndRetrieveResults( - unitUnderTest, - urlList, - PatternURLFilter.NORMALIZED_URL_CONVERTER); + final Map result = + applyFilterAndRetrieveResults(unitUnderTest, urlList, PatternURLFilter.NORMALIZED_URL_CONVERTER); // Assert for (Map.Entry current : result.entrySet()) { diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/T_AbstractPatternFilterTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/T_AbstractPatternFilterTest.java index b2f4f28d..980b03e9 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/T_AbstractPatternFilterTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/filters/pattern/T_AbstractPatternFilterTest.java @@ -1,14 +1,14 @@ package org.codehaus.mojo.jaxb2.shared.filters.pattern; +import java.util.Arrays; +import java.util.List; +import java.util.SortedMap; + import org.codehaus.mojo.jaxb2.BufferingLog; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.Arrays; -import java.util.List; -import java.util.SortedMap; - /** * @author Lennart Jörelid, jGuru Europe AB */ @@ -37,7 +37,6 @@ public void validateExceptionOnNullStringConverter() { final List patterns = null; final boolean acceptCandidateOnPatternMatch = true; - // Act & Assert new DebugPatternFilter(processNullValues, patterns, null, acceptCandidateOnPatternMatch); } @@ -51,10 +50,7 @@ public void validateNoAcceptedResultsWhenProcessingMessagesOnNullFilters() { final boolean acceptCandidateOnPatternMatch = true; final DebugPatternFilter unitUnderTest = new DebugPatternFilter( - processNullValues, - patterns, - UNITY_STRING_CONVERTER, - acceptCandidateOnPatternMatch); + processNullValues, patterns, UNITY_STRING_CONVERTER, acceptCandidateOnPatternMatch); // Act unitUnderTest.initialize(log); @@ -80,10 +76,7 @@ public void validateAcceptingFilterMessages() { final List patterns = Arrays.asList("f.*t"); // Should match 'first' but not 'third' final DebugPatternFilter unitUnderTest = new DebugPatternFilter( - processNullValues, - patterns, - UNITY_STRING_CONVERTER, - acceptCandidateOnPatternMatch); + processNullValues, patterns, UNITY_STRING_CONVERTER, acceptCandidateOnPatternMatch); // Act unitUnderTest.initialize(log); diff --git a/src/test/java/org/codehaus/mojo/jaxb2/shared/version/DependencyFileParserTest.java b/src/test/java/org/codehaus/mojo/jaxb2/shared/version/DependencyFileParserTest.java index 7c2a3007..80c7962d 100644 --- a/src/test/java/org/codehaus/mojo/jaxb2/shared/version/DependencyFileParserTest.java +++ b/src/test/java/org/codehaus/mojo/jaxb2/shared/version/DependencyFileParserTest.java @@ -1,16 +1,16 @@ package org.codehaus.mojo.jaxb2.shared.version; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; import java.util.List; import java.util.SortedMap; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + /** * @author Lennart Jörelid */ @@ -32,9 +32,8 @@ public void setupSharedState() throws Exception { final URL extraURL = getClass().getClassLoader().getResource(jarPath); Assert.assertNotNull("No resource found for path [" + jarPath + "]", extraURL); - final URLClassLoader decoratedClassLoader = new URLClassLoader( - new URL[]{extraURL}, - originalThreadContextClassLoader); + final URLClassLoader decoratedClassLoader = + new URLClassLoader(new URL[] {extraURL}, originalThreadContextClassLoader); Assert.assertNotNull("Could not create decorated ClassLoader", decoratedClassLoader); Thread.currentThread().setContextClassLoader(decoratedClassLoader); @@ -52,8 +51,7 @@ public void setupSharedState() throws Exception { } } Assert.assertNotNull( - "Expected resource not found for internal resource path [" + internalResourcePath + "] ", - urlToTestJar); + "Expected resource not found for internal resource path [" + internalResourcePath + "] ", urlToTestJar); } @After @@ -152,7 +150,8 @@ public void validateExceptionOnAttemptingToParseIncorrectlyFormedPropertiesFile( // Assemble final String resourcePath = "testdata/shared/not_a_dependency.properties"; - final URL incorrectResource = Thread.currentThread().getContextClassLoader().getResource(resourcePath); + final URL incorrectResource = + Thread.currentThread().getContextClassLoader().getResource(resourcePath); // Act & Assert DependsFileParser.getVersionMap(incorrectResource);