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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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 extends FieldLocation> locations) { + final Node aNode, final Node containingClassNode, final Set extends FieldLocation> 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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
true
oldPrefix
newPrefix
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. - * - * 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. - * 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. - * - * 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. + * + * 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. + * 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. + * + * 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 extends AbstractJaxbMojo> caller, - final String encoding) { + public static LoggingHandlerEnvironmentFacet create( + final Log mavenLog, final Class extends AbstractJaxbMojo> 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
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:
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:
Creates a new ChangeFilenameProcessor using the provided map relating namespace URIs - * to desired new file names.
<xs:import namespace="http://a/registered/namespace" schemaLocation="schema1.xsd"/>
NodeProcessor which alters the filename for generated XML schema files. + * The ChangeNamespacePrefixProcessor alters the following:
Creates a new ChangeFilenameProcessor using the provided map relating namespace URIs + * to desired new file names.
NodeProcessor which alters the namespace prefix for all relevant Nodes within an XML - * document Node. It alters namespace prefixes in the following logical places:
NodeProcessor
<xs:element ref="oldPrefix:aRequiredElementInTheOldPrefixNamespace"/>
<xs:element ref="newPrefix:aRequiredElementInTheOldPrefixNamespace"/>
<xs:element type="oldPrefix:something"/>
<xs:element type="newPrefix:something"/>
<xs:extension base="oldPrefix:something"/>
<xs:extension base="newPrefix:something"/>
<xs:element ref="oldPrefix:anElementInTheOldPrefixNamespace"/>
[oldPrefix]:
<xs:element type="oldPrefix:anElementInTheOldPrefixNamespace"/>
- * <xs:extension base="[oldPrefix]:importItem"> - *
<xs:extension base="[oldPrefix]:importItem">
NodeProcessor which alters the namespace prefix for all relevant Nodes within an XML + * document Node. It alters namespace prefixes in the following logical places:
+ * <xs:extension base="[oldPrefix]:importItem"> + *
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.
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.
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.
schemagen
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.
TransformSchema
<foo:bar/>
<xs:extension base="ns1:nazgulEntity">
toPrefix
toFile
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> - *
http://www.jguru.se/some/namespace
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:foo="http://www.acme.com/xml/schema/foo"
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.
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> + *
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
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