diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomMapping.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomMapping.java index abb8d648..b288cee5 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomMapping.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomMapping.java @@ -9,7 +9,6 @@ import javax.inject.Named; import javax.inject.Singleton; - import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -18,13 +17,13 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @Singleton -@Named( "atom" ) +@Named("atom") public class AtomMapping extends MappingSupport { - public AtomMapping() { - super("atom"); - setPomNames("pom.atom"); - setAcceptLocationExtensions(".atom"); - setAcceptOptionKeys("atom:4.0.0"); - setPriority(1); - } -} \ No newline at end of file + public AtomMapping() { + super("atom"); + setPomNames("pom.atom"); + setAcceptLocationExtensions(".atom"); + setAcceptOptionKeys("atom:4.0.0"); + setPriority(1); + } +} diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelReader.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelReader.java index 8ced4c6a..2f2d77ce 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelReader.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelReader.java @@ -7,13 +7,11 @@ */ package org.sonatype.maven.polyglot.atom; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Reader; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.building.ModelSource; @@ -25,18 +23,21 @@ /** * Reads a pom.atom and transforms into a Maven {@link Model}. - * + * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ @Singleton -@Named( "atom" ) +@Named("atom") public class AtomModelReader extends ModelReaderSupport { - public Model read(final Reader input, final Map options) throws IOException { - assert input != null; + public Model read(final Reader input, final Map options) throws IOException { + assert input != null; - // Parse the token stream from our pom.atom configuration file. - Project project = new AtomParser((ModelSource)options.get(ModelProcessor.SOURCE), new Tokenizer(IOUtil.toString(input)).tokenize()).parse(); - return project.toMavenModel(); - } + // Parse the token stream from our pom.atom configuration file. + Project project = new AtomParser( + (ModelSource) options.get(ModelProcessor.SOURCE), + new Tokenizer(IOUtil.toString(input)).tokenize()) + .parse(); + return project.toMavenModel(); + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelWriter.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelWriter.java index 38f137ef..a004d360 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelWriter.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/AtomModelWriter.java @@ -7,9 +7,6 @@ */ package org.sonatype.maven.polyglot.atom; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; @@ -17,7 +14,8 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -29,251 +27,256 @@ import org.sonatype.maven.polyglot.io.ModelWriterSupport; @Singleton -@Named( "atom" ) +@Named("atom") public class AtomModelWriter extends ModelWriterSupport { - private static final Pattern ATOM_REGEX = Pattern.compile("\\d+|true|false"); + private static final Pattern ATOM_REGEX = Pattern.compile("\\d+|true|false"); - protected Logger log = LoggerFactory.getLogger(AtomModelWriter.class); - String indent = " "; + protected Logger log = LoggerFactory.getLogger(AtomModelWriter.class); + String indent = " "; - @Override - public void write(final Writer output, final Map options, final Model model) throws IOException { - assert output != null; - assert model != null; + @Override + public void write(final Writer output, final Map options, final Model model) throws IOException { + assert output != null; + assert model != null; - PrintWriter pw = new PrintWriter(output); + PrintWriter pw = new PrintWriter(output); - repositories(pw, model); - project(pw, model); - id(pw, model); - parent(pw, model); - properties(pw, model); - dependencyManagement(pw, model); - dependencies(pw, model); - modules(pw, model); - pw.println(); - pluginManagement(pw, model); - plugins(pw, "plugin", model); + repositories(pw, model); + project(pw, model); + id(pw, model); + parent(pw, model); + properties(pw, model); + dependencyManagement(pw, model); + dependencies(pw, model); + modules(pw, model); + pw.println(); + pluginManagement(pw, model); + plugins(pw, "plugin", model); - pw.flush(); - pw.close(); - } + pw.flush(); + pw.close(); + } - private void repositories(PrintWriter pw, Model model) { - List repositories = model.getRepositories(); - if (!repositories.isEmpty()) { - pw.print("repositories << \""); - for (int i = 0; i < repositories.size(); i++) { - pw.print(repositories.get(i).getUrl()); - if (i + 1 != repositories.size()) { - pw.print(","); + private void repositories(PrintWriter pw, Model model) { + List repositories = model.getRepositories(); + if (!repositories.isEmpty()) { + pw.print("repositories << \""); + for (int i = 0; i < repositories.size(); i++) { + pw.print(repositories.get(i).getUrl()); + if (i + 1 != repositories.size()) { + pw.print(","); + } + } + pw.println("\""); + pw.println(); } - } - pw.println("\""); - pw.println(); } - } - private void project(PrintWriter pw, Model model) { - String name = model.getName(); - if (name == null) { - name = model.getArtifactId(); + private void project(PrintWriter pw, Model model) { + String name = model.getName(); + if (name == null) { + name = model.getArtifactId(); + } + String url = model.getUrl() == null ? "" : model.getUrl(); + pw.print("project \"" + name + "\" @ \"" + url + "\""); + packaging(pw, model); } - String url = model.getUrl() == null ? "" : model.getUrl(); - pw.print("project \"" + name + "\" @ \"" + url + "\""); - packaging(pw, model); - } - private void id(PrintWriter pw, Model model) { - String groupId = model.getGroupId(); - if (groupId == null & model.getParent() != null) { - groupId = model.getParent().getGroupId(); - } + private void id(PrintWriter pw, Model model) { + String groupId = model.getGroupId(); + if (groupId == null & model.getParent() != null) { + groupId = model.getParent().getGroupId(); + } - String version = model.getVersion(); - if (version == null && model.getParent() != null) { - version = model.getParent().getVersion(); + String version = model.getVersion(); + if (version == null && model.getParent() != null) { + version = model.getParent().getVersion(); + } + pw.println(indent + "id: " + groupId + ":" + model.getArtifactId() + ":" + version); } - pw.println(indent + "id: " + groupId + ":" + model.getArtifactId() + ":" + version); - } - private void parent(PrintWriter pw, Model model) { - if (model.getParent() != null) { - pw.print(indent + "inherits: " + model.getParent().getGroupId() + ":" + model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); - if (model.getParent().getRelativePath() != null) { - //pw.println(":" + model.getParent().getRelativePath()); -// pw.println(":" + "../pom.atom"); - } - pw.println(); + private void parent(PrintWriter pw, Model model) { + if (model.getParent() != null) { + pw.print(indent + "inherits: " + model.getParent().getGroupId() + ":" + + model.getParent().getArtifactId() + ":" + + model.getParent().getVersion()); + if (model.getParent().getRelativePath() != null) { + // pw.println(":" + model.getParent().getRelativePath()); + // pw.println(":" + "../pom.atom"); + } + pw.println(); + } } - } - private void packaging(PrintWriter pw, Model model) { - pw.println(" as " + model.getPackaging()); - } + private void packaging(PrintWriter pw, Model model) { + pw.println(" as " + model.getPackaging()); + } - private void properties(PrintWriter pw, Model model) { - if (!model.getProperties().isEmpty()) { - List keys = new ArrayList(model.getProperties().keySet()); - pw.print(indent + "properties: [ "); - for (int i = 0; i < keys.size(); i++) { - Object key = keys.get(i); - if (i != 0) { - pw.print(" "); - } - Object value = model.getProperties().get(key); - if (value != null) { - pw.print(key + ": " + toAtom(value.toString())); - if (i + 1 != keys.size()) { - pw.println(); - } + private void properties(PrintWriter pw, Model model) { + if (!model.getProperties().isEmpty()) { + List keys = new ArrayList(model.getProperties().keySet()); + pw.print(indent + "properties: [ "); + for (int i = 0; i < keys.size(); i++) { + Object key = keys.get(i); + if (i != 0) { + pw.print(" "); + } + Object value = model.getProperties().get(key); + if (value != null) { + pw.print(key + ": " + toAtom(value.toString())); + if (i + 1 != keys.size()) { + pw.println(); + } + } + } + pw.println(" ]"); } - } - pw.println(" ]"); } - } - private void modules(PrintWriter pw, Model model) { - List modules = model.getModules(); - if (!modules.isEmpty()) { - pw.print(indent + "modules: [ "); - for (int i = 0; i < modules.size(); i++) { - String module = modules.get(i); - if (i != 0) { - pw.print(indent + " "); - } - pw.print(module); - if (i + 1 != modules.size()) { - pw.println(); + private void modules(PrintWriter pw, Model model) { + List modules = model.getModules(); + if (!modules.isEmpty()) { + pw.print(indent + "modules: [ "); + for (int i = 0; i < modules.size(); i++) { + String module = modules.get(i); + if (i != 0) { + pw.print(indent + " "); + } + pw.print(module); + if (i + 1 != modules.size()) { + pw.println(); + } + } + pw.println(" ]"); } - } - pw.println(" ]"); } - } - private void dependencyManagement(PrintWriter pw, Model model) { - if (model.getDependencyManagement() != null) { - deps(pw, "overrides", model.getDependencyManagement().getDependencies()); + private void dependencyManagement(PrintWriter pw, Model model) { + if (model.getDependencyManagement() != null) { + deps(pw, "overrides", model.getDependencyManagement().getDependencies()); + } } - } - private void dependencies(PrintWriter pw, Model model) { - deps(pw, "deps", model.getDependencies()); - } + private void dependencies(PrintWriter pw, Model model) { + deps(pw, "deps", model.getDependencies()); + } - private void deps(PrintWriter pw, String elementName, List deps) { - if (!deps.isEmpty()) { - pw.print(indent + elementName + ": [ "); - for (int i = 0; i < deps.size(); i++) { - Dependency d = deps.get(i); - if (i != 0) { - pw.print(" "); + private void deps(PrintWriter pw, String elementName, List deps) { + if (!deps.isEmpty()) { + pw.print(indent + elementName + ": [ "); + for (int i = 0; i < deps.size(); i++) { + Dependency d = deps.get(i); + if (i != 0) { + pw.print(" "); + } + if (d.getVersion() != null) { + pw.print(d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion()); + } else { + // + // We are assuming the model is well-formed and that the parent is providing a version + // for this particular dependency. + // + pw.print(d.getGroupId() + ":" + d.getArtifactId()); + } + if (d.getClassifier() != null) { + pw.print("(" + d.getClassifier() + ")"); + } + if (i + 1 != deps.size()) { + pw.println(); + } + } + pw.println(" ]"); } - if (d.getVersion() != null) { - pw.print(d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion()); - } else { - // - // We are assuming the model is well-formed and that the parent is providing a version - // for this particular dependency. - // - pw.print(d.getGroupId() + ":" + d.getArtifactId()); - } - if (d.getClassifier() != null) { - pw.print("(" + d.getClassifier() + ")"); - } - if (i + 1 != deps.size()) { - pw.println(); - } - } - pw.println(" ]"); } - } - private void pluginManagement(PrintWriter pw, Model model) { - if (model.getBuild() != null && model.getBuild().getPluginManagement() != null) { - plugins(pw, Token.PLUGIN_OVERRIDE_KEYWORD, model.getBuild().getPluginManagement().getPlugins()); + private void pluginManagement(PrintWriter pw, Model model) { + if (model.getBuild() != null && model.getBuild().getPluginManagement() != null) { + plugins( + pw, + Token.PLUGIN_OVERRIDE_KEYWORD, + model.getBuild().getPluginManagement().getPlugins()); + } } - } - private void plugins(PrintWriter pw, String element, Model model) { - if (model.getBuild() != null && !model.getBuild().getPlugins().isEmpty()) { - plugins(pw, element, model.getBuild().getPlugins()); + private void plugins(PrintWriter pw, String element, Model model) { + if (model.getBuild() != null && !model.getBuild().getPlugins().isEmpty()) { + plugins(pw, element, model.getBuild().getPlugins()); + } } - } - // need to write nested objects - private void plugins(PrintWriter pw, String element, List plugins) { - if (!plugins.isEmpty()) { - for (int i = 0; i < plugins.size(); i++) { - Plugin plugin = plugins.get(i); - pw.println("\n" + element); + // need to write nested objects + private void plugins(PrintWriter pw, String element, List plugins) { + if (!plugins.isEmpty()) { + for (int i = 0; i < plugins.size(); i++) { + Plugin plugin = plugins.get(i); + pw.println("\n" + element); - pw.print(indent + "id: " + plugin.getGroupId() + ":" + plugin.getArtifactId()); - if (plugin.getVersion() != null) { - pw.print(":" + plugin.getVersion()); - } - if (plugin.getConfiguration() != null) { - pw.println(); - Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration(); - printChildren(pw, configuration); - } - if (i + 1 != plugins.size()) { - pw.println(); + pw.print(indent + "id: " + plugin.getGroupId() + ":" + plugin.getArtifactId()); + if (plugin.getVersion() != null) { + pw.print(":" + plugin.getVersion()); + } + if (plugin.getConfiguration() != null) { + pw.println(); + Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration(); + printChildren(pw, configuration); + } + if (i + 1 != plugins.size()) { + pw.println(); + } + } + pw.println(); } - } - pw.println(); } - } - private boolean flipBrackets = false; + private boolean flipBrackets = false; - private void printChildren(PrintWriter pw, Xpp3Dom configuration) { - if (configuration.getChildCount() > 0) { - int count = configuration.getChildCount(); - for (int j = 0; j < count; j++) { - Xpp3Dom c = configuration.getChild(j); - if (c.getValue() != null) { - pw.print(indent + c.getName() + ": " + toAtom(c.getValue())); - if (j + 1 != count) { - pw.println(); - } - } else { + private void printChildren(PrintWriter pw, Xpp3Dom configuration) { + if (configuration.getChildCount() > 0) { + int count = configuration.getChildCount(); + for (int j = 0; j < count; j++) { + Xpp3Dom c = configuration.getChild(j); + if (c.getValue() != null) { + pw.print(indent + c.getName() + ": " + toAtom(c.getValue())); + if (j + 1 != count) { + pw.println(); + } + } else { - String keyString = indent + c.getName() + ": " + lbraceket(); + String keyString = indent + c.getName() + ": " + lbraceket(); - if (c.getChildCount() == 0) { - pw.print(keyString); - } else { - pw.println(keyString); - } - String oldIndent = indent; - indent += " "; - flipBrackets = !flipBrackets; - printChildren(pw, c); - flipBrackets = !flipBrackets; - indent = oldIndent; - if (c.getChildCount() == 0) { - pw.print(rbraceket()); - } else { - pw.print("\n" + indent + rbraceket()); - } + if (c.getChildCount() == 0) { + pw.print(keyString); + } else { + pw.println(keyString); + } + String oldIndent = indent; + indent += " "; + flipBrackets = !flipBrackets; + printChildren(pw, c); + flipBrackets = !flipBrackets; + indent = oldIndent; + if (c.getChildCount() == 0) { + pw.print(rbraceket()); + } else { + pw.print("\n" + indent + rbraceket()); + } + } + } } - } } - } - /** - * Quotes the dom element as a string, but only if necessary. - */ - private String toAtom(String value) { - return '"' + value + '"'; - } + /** + * Quotes the dom element as a string, but only if necessary. + */ + private String toAtom(String value) { + return '"' + value + '"'; + } - private char lbraceket() { - return (flipBrackets ? '{' : '['); - } + private char lbraceket() { + return (flipBrackets ? '{' : '['); + } - private char rbraceket() { - return (flipBrackets ? '}' : ']'); - } + private char rbraceket() { + return (flipBrackets ? '}' : ']'); + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/execute/AtomExecuteTask.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/execute/AtomExecuteTask.java index e80113b3..08f12c59 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/execute/AtomExecuteTask.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/execute/AtomExecuteTask.java @@ -7,12 +7,11 @@ */ package org.sonatype.maven.polyglot.atom.execute; +import java.util.Map; import org.sonatype.maven.polyglot.execute.ExecuteContext; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.execute.ExecuteTaskSupport; -import java.util.Map; - /** * Encapsulates a Groovy {@link ExecuteTask}. * @@ -37,18 +36,16 @@ public Map getAttributes() { return attrs; } - public void execute(final ExecuteContext context) throws Exception { - System.out.println("Executing atom code..."); + System.out.println("Executing atom code..."); } @Override public String toString() { - return getClass().getSimpleName() + "{" + - "id='" + getId() + '\'' + - ", phase='" + getPhase() + '\'' + - ", value=" + value + - ", attrs=" + attrs + - '}'; + return getClass().getSimpleName() + "{" + "id='" + + getId() + '\'' + ", phase='" + + getPhase() + '\'' + ", value=" + + value + ", attrs=" + + attrs + '}'; } -} \ No newline at end of file +} diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/AtomParser.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/AtomParser.java index 5856147b..8bef2c64 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/AtomParser.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/AtomParser.java @@ -7,13 +7,6 @@ */ package org.sonatype.maven.polyglot.atom.parsing; -import org.apache.maven.model.Parent; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.building.ModelSource; -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.sonatype.maven.polyglot.atom.parsing.Token.Kind; - import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; @@ -23,6 +16,12 @@ import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; +import org.apache.maven.model.Parent; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.building.ModelSource; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.sonatype.maven.polyglot.atom.parsing.Token.Kind; /** * Parses the atom token stream into an internal model, which can be emitted as a Maven model. @@ -30,774 +29,762 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class AtomParser { - // TODO(dhanji): Replace with proper logging/console out - private final Logger log = Logger.getLogger(AtomParser.class.getName()); - private final List tokens; - // This is the ultimate source where the model came from. We can use this to help the user understand problems in the parsing of the - // model and help them make corrections. - private final ModelSource modelSource; - - // Parser state. (current index) - private int i = 0; - - public AtomParser(ModelSource modelSource, List tokens) { - this.tokens = tokens; - this.modelSource = modelSource; - } - - private void parseException(String message, Throwable t) { - String location = modelSource != null ? modelSource.getLocation() : ""; - throw new RuntimeException("Error parsing " + location + ": " + message, t); - } - - private void parseException(String message) { - String location = modelSource != null ? modelSource.getLocation() : ""; - throw new RuntimeException("Error parsing " + location + ": " + message); - } - - public Project parse() { - chewEols(); - Repositories repositories = repositories(); - if (null == repositories) { - // don't really need to log this. jvz. - // log.warning("No repositories specified in atom file, defaulting to Maven Central."); - } + // TODO(dhanji): Replace with proper logging/console out + private final Logger log = Logger.getLogger(AtomParser.class.getName()); + private final List tokens; + // This is the ultimate source where the model came from. We can use this to help the user understand problems in + // the parsing of the + // model and help them make corrections. + private final ModelSource modelSource; - chewEols(); + // Parser state. (current index) + private int i = 0; - return project(repositories); - } + public AtomParser(ModelSource modelSource, List tokens) { + this.tokens = tokens; + this.modelSource = modelSource; + } - /** - * Parsing rule for a single project build definition. - * - * project := 'project' STRING (AT URL)? ('as' PACKAGING)? EOL - * (idFragment COLON list EOL)+ - */ - private Project project(Repositories repositories) { - if (match(Token.Kind.PROJECT) == null) { - return null; + private void parseException(String message, Throwable t) { + String location = modelSource != null ? modelSource.getLocation() : ""; + throw new RuntimeException("Error parsing " + location + ": " + message, t); } - List signature = match(Token.Kind.STRING); - if (null == signature) { - log.severe("Expected string describing project after 'project'."); + private void parseException(String message) { + String location = modelSource != null ? modelSource.getLocation() : ""; + throw new RuntimeException("Error parsing " + location + ": " + message); } - String projectDescription = signature.get(0).value; - String projectUrl = null; + public Project parse() { + chewEols(); + Repositories repositories = repositories(); + if (null == repositories) { + // don't really need to log this. jvz. + // log.warning("No repositories specified in atom file, defaulting to Maven Central."); + } - signature = match(Token.Kind.AT, Token.Kind.STRING); - if (null != signature) { - projectUrl = signature.get(1).value; - } + chewEols(); - List packagingTokens = match(Kind.PACKAGING, Kind.IDENT); - String packaging = null; - if (null != packagingTokens) { - packaging = packagingTokens.get(1).value; + return project(repositories); } - if (match(Token.Kind.EOL) == null) { - log.severe("Expected end of line after project declaration"); - return null; - } + /** + * Parsing rule for a single project build definition. + * + * project := 'project' STRING (AT URL)? ('as' PACKAGING)? EOL + * (idFragment COLON list EOL)+ + */ + private Project project(Repositories repositories) { + if (match(Token.Kind.PROJECT) == null) { + return null; + } - // id definition - indent(); - if (match(Token.Kind.ID) == null) { - log.severe("Expected 'id' after project declaration"); - return null; - } + List signature = match(Token.Kind.STRING); + if (null == signature) { + log.severe("Expected string describing project after 'project'."); + } - // Now expect a colon. - if (match(Token.Kind.COLON) == null) { - log.severe("Expected ':' after 'id'"); - return null; - } + String projectDescription = signature.get(0).value; + String projectUrl = null; - Id projectId = id(); - - // parent - chewEols(); - chewIndents(); - - Parent parent = parent(); - - // packaging - chewEols(); - chewIndents(); - - // srcs - chewEols(); - Map dirs = srcs(); - - // properties - chewEols(); - chewIndents(); - List properties = properties(Token.Kind.PROPS); - - // dependencies - chewEols(); - chewIndents(); - List overrides = dependencies(Token.Kind.OVERRIDES, false); - - // dependencies - chewEols(); - chewIndents(); - List deps = dependencies(Token.Kind.DEPS, true); - - // modules - chewEols(); - chewIndents(); - List modules = modules(); - - ScmElement scm = scm(); - - // modules - chewEols(); - chewIndents(); - List pluginOverrides = plugins(Kind.PLUGIN_OVERRIDE); - List plugins = plugins(Kind.PLUGIN); - - return new Project(projectId, - parent, - packaging, - properties, - repositories, - projectDescription, - projectUrl, - overrides, - deps, - modules, - pluginOverrides, - plugins, - dirs, - scm); - } - - private ScmElement scm() { - chewIndents(); - if (match(Token.Kind.SCM, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { - return null; // no scm element - } + signature = match(Token.Kind.AT, Token.Kind.STRING); + if (null != signature) { + projectUrl = signature.get(1).value; + } - chewEols(); - chewIndents(); - - String connection = null, developerConnection = null, url = null; - List ident; - while ((ident = match(Token.Kind.IDENT)) != null) { - String label = ident.get(0).value; - - if (match(Token.Kind.COLON) == null) { - parseException("Expected : after label"); - } - - List valueToken = match(Token.Kind.STRING); - if (null == valueToken) { - parseException("Expected String after :"); - } - String value = valueToken.get(0).value; - - if ("connection".equals(label)) - connection = value; - else if ("developerConnection".equals(label)) - developerConnection = value; - else if ("url".equals(label)) - url = value; - - chewEols(); - chewIndents(); - } + List packagingTokens = match(Kind.PACKAGING, Kind.IDENT); + String packaging = null; + if (null != packagingTokens) { + packaging = packagingTokens.get(1).value; + } - if (match(Token.Kind.RBRACKET) == null) { - parseException("Expected ] after srcs list"); - } + if (match(Token.Kind.EOL) == null) { + log.severe("Expected end of line after project declaration"); + return null; + } - return new ScmElement(connection, developerConnection, url); - } + // id definition + indent(); + if (match(Token.Kind.ID) == null) { + log.severe("Expected 'id' after project declaration"); + return null; + } - /** - * Custom directory structure for maven builds. - */ - private Map srcs() { - indent(); - if (match(Token.Kind.SRCS, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { - return null; // No dirs! - } + // Now expect a colon. + if (match(Token.Kind.COLON) == null) { + log.severe("Expected ':' after 'id'"); + return null; + } - chewEols(); - chewIndents(); - List aMatch = match(Token.Kind.IDENT); - if (aMatch == null) { - parseException("Expected 'src' or 'test'"); - } + Id projectId = id(); + + // parent + chewEols(); + chewIndents(); + + Parent parent = parent(); + + // packaging + chewEols(); + chewIndents(); + + // srcs + chewEols(); + Map dirs = srcs(); + + // properties + chewEols(); + chewIndents(); + List properties = properties(Token.Kind.PROPS); + + // dependencies + chewEols(); + chewIndents(); + List overrides = dependencies(Token.Kind.OVERRIDES, false); + + // dependencies + chewEols(); + chewIndents(); + List deps = dependencies(Token.Kind.DEPS, true); + + // modules + chewEols(); + chewIndents(); + List modules = modules(); + + ScmElement scm = scm(); + + // modules + chewEols(); + chewIndents(); + List pluginOverrides = plugins(Kind.PLUGIN_OVERRIDE); + List plugins = plugins(Kind.PLUGIN); + + return new Project( + projectId, + parent, + packaging, + properties, + repositories, + projectDescription, + projectUrl, + overrides, + deps, + modules, + pluginOverrides, + plugins, + dirs, + scm); + } + + private ScmElement scm() { + chewIndents(); + if (match(Token.Kind.SCM, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { + return null; // no scm element + } - String srcDir = null; - if ("src".equals(aMatch.get(0).value)) { - if (null == match(Token.Kind.COLON)) { - parseException("Expected : after src"); - } + chewEols(); + chewIndents(); - List srcDirToken = match(Token.Kind.STRING); - if (null == srcDirToken) { - parseException("Expected string after src:"); - } + String connection = null, developerConnection = null, url = null; + List ident; + while ((ident = match(Token.Kind.IDENT)) != null) { + String label = ident.get(0).value; - srcDir = srcDirToken.get(0).value; - } + if (match(Token.Kind.COLON) == null) { + parseException("Expected : after label"); + } - aMatch = match(Token.Kind.IDENT); + List valueToken = match(Token.Kind.STRING); + if (null == valueToken) { + parseException("Expected String after :"); + } + String value = valueToken.get(0).value; - String testDir = null; - if (null != aMatch && "test".equals(aMatch.get(0).value)) { - if (null == match(Token.Kind.COLON)) { - parseException("Expected : after test"); - } + if ("connection".equals(label)) connection = value; + else if ("developerConnection".equals(label)) developerConnection = value; + else if ("url".equals(label)) url = value; - List testDirToken = match(Token.Kind.STRING); - if (null == testDirToken) { - parseException("Expected string after test:"); - } + chewEols(); + chewIndents(); + } + + if (match(Token.Kind.RBRACKET) == null) { + parseException("Expected ] after srcs list"); + } - testDir = testDirToken.get(0).value; + return new ScmElement(connection, developerConnection, url); } - Map dirs = new HashMap(); - // Strip quotes and store. - if (null != srcDir) - dirs.put("src", stripQuotes(srcDir)); - if (null != testDir) - dirs.put("test", stripQuotes(testDir)); + /** + * Custom directory structure for maven builds. + */ + private Map srcs() { + indent(); + if (match(Token.Kind.SRCS, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { + return null; // No dirs! + } - if (match(Token.Kind.RBRACKET) == null) { - parseException("Expected ] after srcs list"); - } + chewEols(); + chewIndents(); + List aMatch = match(Token.Kind.IDENT); + if (aMatch == null) { + parseException("Expected 'src' or 'test'"); + } - return dirs; - } + String srcDir = null; + if ("src".equals(aMatch.get(0).value)) { + if (null == match(Token.Kind.COLON)) { + parseException("Expected : after src"); + } - /** - * Dependencies of a project. The real meat of it. - */ - private List dependencies(Token.Kind kind, boolean allowNullVersion) { - indent(); - if (match(kind, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { - return null; // no deps. - } - List deps = new ArrayList(); - - chewEols(); - chewIndents(); - - // Slurp up the dep ids. - Id id; - while ((id = id(allowNullVersion)) != null) { - // Optional additional params at the end. - String classifier = classifier(); - if (null != classifier) { - id.setClassifier(classifier); - } - - chewEols(); - chewIndents(); - deps.add(id); - } + List srcDirToken = match(Token.Kind.STRING); + if (null == srcDirToken) { + parseException("Expected string after src:"); + } - if (match(Token.Kind.RBRACKET) == null) { - // ERROR! - parseException("Expected ]"); - } + srcDir = srcDirToken.get(0).value; + } - return deps; - } + aMatch = match(Token.Kind.IDENT); - /** - * Additional plugins and their configuration. - */ - private List plugins(Kind keyword) { - List plugins = new ArrayList(); + String testDir = null; + if (null != aMatch && "test".equals(aMatch.get(0).value)) { + if (null == match(Token.Kind.COLON)) { + parseException("Expected : after test"); + } - chewEols(); - Plugin plugin; - while ((plugin = plugin(keyword)) != null) { - plugins.add(plugin); + List testDirToken = match(Token.Kind.STRING); + if (null == testDirToken) { + parseException("Expected string after test:"); + } - chewEols(); - } + testDir = testDirToken.get(0).value; + } - return plugins; - } + Map dirs = new HashMap(); + // Strip quotes and store. + if (null != srcDir) dirs.put("src", stripQuotes(srcDir)); + if (null != testDir) dirs.put("test", stripQuotes(testDir)); - private Plugin plugin(Kind keyword) { - if (match(keyword) == null) - return null; + if (match(Token.Kind.RBRACKET) == null) { + parseException("Expected ] after srcs list"); + } - if (match(Kind.EOL) == null) { - parseException("Expected newline after 'plugin' keyword"); + return dirs; } - Plugin plugin = new Plugin(); + /** + * Dependencies of a project. The real meat of it. + */ + private List dependencies(Token.Kind kind, boolean allowNullVersion) { + indent(); + if (match(kind, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { + return null; // no deps. + } + List deps = new ArrayList(); + + chewEols(); + chewIndents(); + + // Slurp up the dep ids. + Id id; + while ((id = id(allowNullVersion)) != null) { + // Optional additional params at the end. + String classifier = classifier(); + if (null != classifier) { + id.setClassifier(classifier); + } + + chewEols(); + chewIndents(); + deps.add(id); + } - chewIndents(); - if (match(Kind.ID, Kind.COLON) == null) { - log.severe("Plugin declaration is missing an 'id' tag"); - return null; - } + if (match(Token.Kind.RBRACKET) == null) { + // ERROR! + parseException("Expected ]"); + } - Id pluginId = id(true); - if (pluginId == null) { - log.severe("Plugin id declaration malformed"); - return null; + return deps; } - if (match(Kind.EOL) == null) { - log.severe("Expected newline after plugin id declaration"); - return null; - } + /** + * Additional plugins and their configuration. + */ + private List plugins(Kind keyword) { + List plugins = new ArrayList(); - // Dont forget to set the id properties. - plugin.setGroupId(pluginId.getGroup()); - plugin.setArtifactId(pluginId.getArtifact()); - plugin.setVersion(pluginId.getVersion()); - - Map config; - if ((config = configurationMap()) == null || config.isEmpty()) - return plugin; - - // Transform the parsed config map into maven's XPP3 Dom thing. - plugin.setConfiguration(toXpp3DomTree("configuration", config)); - - return plugin; - } - - private Xpp3Dom toXpp3DomTree(String name, Map config) { - Xpp3Dom xConfig = new Xpp3Dom(name); - for (Entry entry : config.entrySet()) { - if (entry.getValue() instanceof String) { - Xpp3Dom node = new Xpp3Dom(entry.getKey()); - node.setValue(entry.getValue().toString()); - - xConfig.addChild(node); - } else { - @SuppressWarnings("unchecked") // Guaranteed by #configurationMap() - Map childMap = (Map) entry.getValue(); - - // Recurse. - Xpp3Dom child = toXpp3DomTree(entry.getKey(), childMap); - xConfig.addChild(child); - } - } - return xConfig; - } - - private Map configurationMap() { - Map config = new LinkedHashMap(); - List propKey; - - chewIndents(); - while ((propKey = match(Kind.IDENT, Kind.COLON)) != null) { - // Match the rest of the line as either an atom or as another set of properties. - String atom = idFragment(); - - if (atom == null) { - List tokens = match(Kind.STRING); - if (tokens != null) - atom = tokens.get(0).value; - } - - if (atom != null) { - atom = atom.trim(); - // Strip quotes. - atom = stripQuotes(atom); - - config.put(propKey.get(0).value, atom); - - // eol here is optional. - match(Kind.EOL); - } else { - // This is a multilevel thing, recurse! - if (anyOf(Kind.LBRACKET, Kind.LBRACE) != null) { - chewEols(); - chewIndents(); - Map childProps = configurationMap(); - chewEols(); - chewIndents(); - if (match(Kind.RBRACKET) == null && match(Kind.RBRACE) == null) - parseException("Expected ']' after configuration properties"); - - // stash into parent map. - config.put(propKey.get(0).value, childProps); + chewEols(); + Plugin plugin; + while ((plugin = plugin(keyword)) != null) { + plugins.add(plugin); - } else { - // ignore. Later we can force-parse this as a string. - log.warning("Unknown element type in plugin declaration"); - return null; + chewEols(); } - } - chewIndents(); + return plugins; } - return config; - } + private Plugin plugin(Kind keyword) { + if (match(keyword) == null) return null; - static String stripQuotes(String atom) { - if (atom.startsWith("\"") && atom.endsWith("\"")) - atom = atom.substring(1, atom.length() - 1); - return atom; - } + if (match(Kind.EOL) == null) { + parseException("Expected newline after 'plugin' keyword"); + } - private List properties(Token.Kind kind) { + Plugin plugin = new Plugin(); - indent(); - if (match(kind, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { - return null; // no properties. - } - List properties = new ArrayList(); + chewIndents(); + if (match(Kind.ID, Kind.COLON) == null) { + log.severe("Plugin declaration is missing an 'id' tag"); + return null; + } - chewEols(); - chewIndents(); + Id pluginId = id(true); + if (pluginId == null) { + log.severe("Plugin id declaration malformed"); + return null; + } - Property p; - while ((p = property()) != null) { - chewEols(); - chewIndents(); - properties.add(p); - } + if (match(Kind.EOL) == null) { + log.severe("Expected newline after plugin id declaration"); + return null; + } - if (match(Token.Kind.RBRACKET) == null) { - // ERROR! - parseException("Expected ]"); - } + // Dont forget to set the id properties. + plugin.setGroupId(pluginId.getGroup()); + plugin.setArtifactId(pluginId.getArtifact()); + plugin.setVersion(pluginId.getVersion()); - return properties; - } + Map config; + if ((config = configurationMap()) == null || config.isEmpty()) return plugin; - private List modules() { + // Transform the parsed config map into maven's XPP3 Dom thing. + plugin.setConfiguration(toXpp3DomTree("configuration", config)); - indent(); - if (match(Token.Kind.MODULES, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { - return null; // no properties. + return plugin; } - List modules = new ArrayList(); - chewEols(); - chewIndents(); + private Xpp3Dom toXpp3DomTree(String name, Map config) { + Xpp3Dom xConfig = new Xpp3Dom(name); + for (Entry entry : config.entrySet()) { + if (entry.getValue() instanceof String) { + Xpp3Dom node = new Xpp3Dom(entry.getKey()); + node.setValue(entry.getValue().toString()); + + xConfig.addChild(node); + } else { + @SuppressWarnings("unchecked") // Guaranteed by #configurationMap() + Map childMap = (Map) entry.getValue(); + + // Recurse. + Xpp3Dom child = toXpp3DomTree(entry.getKey(), childMap); + xConfig.addChild(child); + } + } + return xConfig; + } + + private Map configurationMap() { + Map config = new LinkedHashMap(); + List propKey; + + chewIndents(); + while ((propKey = match(Kind.IDENT, Kind.COLON)) != null) { + // Match the rest of the line as either an atom or as another set of properties. + String atom = idFragment(); + + if (atom == null) { + List tokens = match(Kind.STRING); + if (tokens != null) atom = tokens.get(0).value; + } + + if (atom != null) { + atom = atom.trim(); + // Strip quotes. + atom = stripQuotes(atom); + + config.put(propKey.get(0).value, atom); + + // eol here is optional. + match(Kind.EOL); + } else { + // This is a multilevel thing, recurse! + if (anyOf(Kind.LBRACKET, Kind.LBRACE) != null) { + chewEols(); + chewIndents(); + Map childProps = configurationMap(); + chewEols(); + chewIndents(); + if (match(Kind.RBRACKET) == null && match(Kind.RBRACE) == null) + parseException("Expected ']' after configuration properties"); + + // stash into parent map. + config.put(propKey.get(0).value, childProps); + + } else { + // ignore. Later we can force-parse this as a string. + log.warning("Unknown element type in plugin declaration"); + return null; + } + } + + chewIndents(); + } - String module; - while ((module = idFragment()) != null) { - chewEols(); - chewIndents(); - modules.add(module); + return config; } - if (match(Token.Kind.RBRACKET) == null) { - // ERROR! - parseException("Expected ]"); + static String stripQuotes(String atom) { + if (atom.startsWith("\"") && atom.endsWith("\"")) atom = atom.substring(1, atom.length() - 1); + return atom; } - return modules; - } + private List properties(Token.Kind kind) { - /** - * classifier := LPAREN IDENT RPAREN - */ - private String classifier() { - if (match(Token.Kind.LPAREN) == null) { - return null; - } + indent(); + if (match(kind, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { + return null; // no properties. + } + List properties = new ArrayList(); - List classifier = match(Token.Kind.IDENT); - if (classifier == null) { - log.severe("Expected identifier after '(' in classifier clause"); - return null; - } + chewEols(); + chewIndents(); - if (match(Token.Kind.RPAREN) == null) { - log.severe("Expected ')' in classifier clause before end of line"); - return null; + Property p; + while ((p = property()) != null) { + chewEols(); + chewIndents(); + properties.add(p); + } + + if (match(Token.Kind.RBRACKET) == null) { + // ERROR! + parseException("Expected ]"); + } + + return properties; } - return classifier.get(0).value; - } + private List modules() { - private Property property() { + indent(); + if (match(Token.Kind.MODULES, Token.Kind.COLON, Token.Kind.LBRACKET) == null) { + return null; // no properties. + } + List modules = new ArrayList(); - String key = idFragment(); - if (key == null) { - return null; - } + chewEols(); + chewIndents(); + + String module; + while ((module = idFragment()) != null) { + chewEols(); + chewIndents(); + modules.add(module); + } - // Now expect a colon. - if (match(Token.Kind.COLON) == null) { - return null; + if (match(Token.Kind.RBRACKET) == null) { + // ERROR! + parseException("Expected ]"); + } + + return modules; } - List value = match(Kind.STRING); - if (value == null) { - return null; + /** + * classifier := LPAREN IDENT RPAREN + */ + private String classifier() { + if (match(Token.Kind.LPAREN) == null) { + return null; + } + + List classifier = match(Token.Kind.IDENT); + if (classifier == null) { + log.severe("Expected identifier after '(' in classifier clause"); + return null; + } + + if (match(Token.Kind.RPAREN) == null) { + log.severe("Expected ')' in classifier clause before end of line"); + return null; + } + + return classifier.get(0).value; } - String actual = stripQuotes(value.get(0).value); + private Property property() { - return new Property(key, actual); - } + String key = idFragment(); + if (key == null) { + return null; + } - /** - * Id of a project definition. - *

- * id := IDENT (DOT IDENT)* COLON IDENT (COLON IDENT)? EOL - */ - private Id id() { - return id(false); - } + // Now expect a colon. + if (match(Token.Kind.COLON) == null) { + return null; + } - private Id id(boolean allowNullVersion) { + List value = match(Kind.STRING); + if (value == null) { + return null; + } - String groupId = idFragment(); - if (groupId == null) { - return null; - } + String actual = stripQuotes(value.get(0).value); - // Now expect a colon. - if (match(Token.Kind.COLON) == null) { - return null; + return new Property(key, actual); } - String artifactId = idFragment(); - if (artifactId == null) { - return null; + /** + * Id of a project definition. + *

+ * id := IDENT (DOT IDENT)* COLON IDENT (COLON IDENT)? EOL + */ + private Id id() { + return id(false); } - // Now expect a colon. - String version; - if (match(Token.Kind.COLON) == null && !allowNullVersion) { - return null; - } else { - version = idFragment(); - if (version == null && !allowNullVersion) { - return null; - } - } + private Id id(boolean allowNullVersion) { - return new Id(groupId, artifactId, StringUtils.isEmpty(version) ? null : version); - } + String groupId = idFragment(); + if (groupId == null) { + return null; + } - private Parent parent() { - if (match(Kind.PARENT) == null) - return null; + // Now expect a colon. + if (match(Token.Kind.COLON) == null) { + return null; + } - if (match(Kind.COLON) == null) { - log.severe("Expected ':' after 'inherits'"); - return null; - } + String artifactId = idFragment(); + if (artifactId == null) { + return null; + } - Id parentId = id(true); + // Now expect a colon. + String version; + if (match(Token.Kind.COLON) == null && !allowNullVersion) { + return null; + } else { + version = idFragment(); + if (version == null && !allowNullVersion) { + return null; + } + } - if (parentId == null) { - log.severe("Expected complete artifact identifier in 'parent' clause"); - return null; + return new Id(groupId, artifactId, StringUtils.isEmpty(version) ? null : version); } - String relativePath = "../pom.atom"; - if (match(Token.Kind.COLON) != null) { - relativePath = relativePath(); - if (relativePath == null) { - return null; - } - } + private Parent parent() { + if (match(Kind.PARENT) == null) return null; - Parent parent = new Parent(); - parent.setGroupId(parentId.getGroup()); - parent.setArtifactId(parentId.getArtifact()); - parent.setVersion(parentId.getVersion()); - parent.setRelativePath(relativePath); - - return parent; - } - - // - // ../atom.pom - // - private String relativePath() { - StringBuilder fragment = new StringBuilder(); - if (match(Token.Kind.DOT) != null) { - fragment.append("."); - } - if (match(Token.Kind.DOT) != null) { - fragment.append("."); - } + if (match(Kind.COLON) == null) { + log.severe("Expected ':' after 'inherits'"); + return null; + } - List idFragment; - while ((idFragment = match(Token.Kind.IDENT)) != null) { - fragment.append(idFragment.get(0).value); - if (match(Token.Kind.DOT) != null) { - fragment.append('.'); - } - } + Id parentId = id(true); - return fragment.toString(); - } - - private String idFragment() { - StringBuilder fragment = new StringBuilder(); - Token idFragment; - while ((idFragment = anyOf( - Token.Kind.IDENT, - Kind.PLUGIN, - Kind.PROJECT, - Kind.DEPS, - Kind.SCM, - Kind.SRCS, - Kind.MODULES, - Kind.ID, - Kind.PACKAGING, - Kind.PARENT, - Kind.OVERRIDES, - Kind.REPOSITORIES, - Kind.PROPS - )) != null) { - fragment.append(idFragment.value); - if (match(Token.Kind.DOT) != null) { - fragment.append('.'); - } - if (match(Token.Kind.DASH) != null) { - fragment.append('-'); - } + if (parentId == null) { + log.severe("Expected complete artifact identifier in 'parent' clause"); + return null; + } + + String relativePath = "../pom.atom"; + if (match(Token.Kind.COLON) != null) { + relativePath = relativePath(); + if (relativePath == null) { + return null; + } + } + + Parent parent = new Parent(); + parent.setGroupId(parentId.getGroup()); + parent.setArtifactId(parentId.getArtifact()); + parent.setVersion(parentId.getVersion()); + parent.setRelativePath(relativePath); + + return parent; } - // Try parsing as property expression. - if (fragment.length() == 1 && fragment.charAt(0) == '$') { - List startOfExpr = match(Kind.LBRACE); - if (startOfExpr == null) - return null; + // + // ../atom.pom + // + private String relativePath() { + StringBuilder fragment = new StringBuilder(); + if (match(Token.Kind.DOT) != null) { + fragment.append("."); + } + if (match(Token.Kind.DOT) != null) { + fragment.append("."); + } - fragment.append("{"); - String prop = idFragment(); - if (prop == null) - parseException("Expected a property expression after ${"); + List idFragment; + while ((idFragment = match(Token.Kind.IDENT)) != null) { + fragment.append(idFragment.get(0).value); + if (match(Token.Kind.DOT) != null) { + fragment.append('.'); + } + } - if (match(Kind.RBRACE) == null) - parseException("Expected '}' after property expression"); + return fragment.toString(); + } + + private String idFragment() { + StringBuilder fragment = new StringBuilder(); + Token idFragment; + while ((idFragment = anyOf( + Token.Kind.IDENT, + Kind.PLUGIN, + Kind.PROJECT, + Kind.DEPS, + Kind.SCM, + Kind.SRCS, + Kind.MODULES, + Kind.ID, + Kind.PACKAGING, + Kind.PARENT, + Kind.OVERRIDES, + Kind.REPOSITORIES, + Kind.PROPS)) + != null) { + fragment.append(idFragment.value); + if (match(Token.Kind.DOT) != null) { + fragment.append('.'); + } + if (match(Token.Kind.DASH) != null) { + fragment.append('-'); + } + } - fragment.append(prop).append("}"); - } + // Try parsing as property expression. + if (fragment.length() == 1 && fragment.charAt(0) == '$') { + List startOfExpr = match(Kind.LBRACE); + if (startOfExpr == null) return null; - // Nothing matched. - if (fragment.length() == 0) - return null; - - return fragment.toString(); - } - - /** - * Optional repositories declaration at the top of the file. - *

- * repositories := 'repositories' LEFT_WAVE STRING (COMMA STRING)* - */ - private Repositories repositories() { - if (match(Token.Kind.REPOSITORIES, Token.Kind.LEFT_WAVE) == null) { - return null; - } - List repoUrls = new ArrayList(); + fragment.append("{"); + String prop = idFragment(); + if (prop == null) parseException("Expected a property expression after ${"); - List repositories = match(Token.Kind.STRING); - if (repositories == null) { - // ERROR expected String. - parseException("Error: expected URL string after 'respositories"); - } + if (match(Kind.RBRACE) == null) parseException("Expected '}' after property expression"); - // Validate first URL... - //noinspection ConstantConditions - String url = repositories.get(0).value; - repoUrls.add(validateUrl(url)); - - while ((repositories = match(Token.Kind.COMMA)) != null) { - chewEols(); - chewIndents(); - repositories = match(Token.Kind.STRING); - chewEols(); - chewIndents(); - if (null != repositories) { - url = validateUrl(repositories.get(0).value); - - repoUrls.add(url); - } + fragment.append(prop).append("}"); + } + + // Nothing matched. + if (fragment.length() == 0) return null; + + return fragment.toString(); } - return new Repositories(repoUrls); - } + /** + * Optional repositories declaration at the top of the file. + *

+ * repositories := 'repositories' LEFT_WAVE STRING (COMMA STRING)* + */ + private Repositories repositories() { + if (match(Token.Kind.REPOSITORIES, Token.Kind.LEFT_WAVE) == null) { + return null; + } + List repoUrls = new ArrayList(); + + List repositories = match(Token.Kind.STRING); + if (repositories == null) { + // ERROR expected String. + parseException("Error: expected URL string after 'respositories"); + } - private String validateUrl(String url) { - url = stripQuotes(url); + // Validate first URL... + //noinspection ConstantConditions + String url = repositories.get(0).value; + repoUrls.add(validateUrl(url)); + + while ((repositories = match(Token.Kind.COMMA)) != null) { + chewEols(); + chewIndents(); + repositories = match(Token.Kind.STRING); + chewEols(); + chewIndents(); + if (null != repositories) { + url = validateUrl(repositories.get(0).value); + + repoUrls.add(url); + } + } - // Validate URL... - try { - new URL(url); - } catch (MalformedURLException e) { - parseException("Invalid URL: " + url, e); + return new Repositories(repoUrls); } - return url; - } - // Production tools. + private String validateUrl(String url) { + url = stripQuotes(url); - private void indent() { - if (match(Token.Kind.INDENT, Token.Kind.INDENT) != null) { - // ERROR! + // Validate URL... + try { + new URL(url); + } catch (MalformedURLException e) { + parseException("Invalid URL: " + url, e); + } + return url; } - } - private Token anyOf(Token.Kind... ident) { - if (i >= tokens.size()) { - return null; + // Production tools. + + private void indent() { + if (match(Token.Kind.INDENT, Token.Kind.INDENT) != null) { + // ERROR! + } } - for (Token.Kind kind : ident) { - Token token = tokens.get(i); - if (kind == token.kind) { - i++; - return token; - } + + private Token anyOf(Token.Kind... ident) { + if (i >= tokens.size()) { + return null; + } + for (Token.Kind kind : ident) { + Token token = tokens.get(i); + if (kind == token.kind) { + i++; + return token; + } + } + + // No match =( + return null; } - // No match =( - return null; - } + private List match(Token.Kind... ident) { + int cursor = i; + for (Token.Kind kind : ident) { - private List match(Token.Kind... ident) { - int cursor = i; - for (Token.Kind kind : ident) { + // What we want is more than the size of the token stream. + if (cursor >= tokens.size()) { + return null; + } - // What we want is more than the size of the token stream. - if (cursor >= tokens.size()) { - return null; - } + Token token = tokens.get(cursor); + if (token.kind != kind) { + return null; + } - Token token = tokens.get(cursor); - if (token.kind != kind) { - return null; - } + cursor++; + } + + // Forward cursor in token stream to match point. + int start = i; + i = cursor; + return tokens.subList(start, i); + } - cursor++; + private void chewEols() { + // Chew up end-of-lines. + while (match(Token.Kind.EOL) != null) + ; } - // Forward cursor in token stream to match point. - int start = i; - i = cursor; - return tokens.subList(start, i); - } - - private void chewEols() { - // Chew up end-of-lines. - while (match(Token.Kind.EOL) != null) - ; - } - - private void chewIndents() { - // Chew up end-of-lines. - while (match(Token.Kind.INDENT) != null) - ; - } + private void chewIndents() { + // Chew up end-of-lines. + while (match(Token.Kind.INDENT) != null) + ; + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Dependencies.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Dependencies.java index 4aad247e..0ebc8ef1 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Dependencies.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Dependencies.java @@ -10,5 +10,4 @@ /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ -public class Dependencies { -} +public class Dependencies {} diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Element.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Element.java index adc92099..f6784419 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Element.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Element.java @@ -12,5 +12,4 @@ * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ -abstract class Element { -} +abstract class Element {} diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Id.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Id.java index c0477ef4..91e60ce3 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Id.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Id.java @@ -11,39 +11,39 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Id { - private final String group; - private final String artifact; - private final String version; - private String classifier; - - public Id(String group, String artifact, String version) { - this.group = group; - this.artifact = artifact; - this.version = version; - } - - public String getGroup() { - return group; - } - - public String getArtifact() { - return artifact; - } - - public String getVersion() { - return version; - } - - public String getClassifier() { - return classifier; - } - - public void setClassifier(String classifier) { - this.classifier = classifier; - } - - @Override - public String toString() { - return group + ":" + artifact + ":" + version; - } + private final String group; + private final String artifact; + private final String version; + private String classifier; + + public Id(String group, String artifact, String version) { + this.group = group; + this.artifact = artifact; + this.version = version; + } + + public String getGroup() { + return group; + } + + public String getArtifact() { + return artifact; + } + + public String getVersion() { + return version; + } + + public String getClassifier() { + return classifier; + } + + public void setClassifier(String classifier) { + this.classifier = classifier; + } + + @Override + public String toString() { + return group + ":" + artifact + ":" + version; + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Project.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Project.java index c361c501..568d9882 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Project.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Project.java @@ -7,228 +7,226 @@ */ package org.sonatype.maven.polyglot.atom.parsing; -import org.apache.maven.model.*; - import java.util.List; import java.util.Map; import java.util.Properties; +import org.apache.maven.model.*; /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Project extends Element { - private final Id projectId; - private final Parent parent; - private String packaging = "jar"; - private List properties; - private final Repositories repositories; - private final String description; - private final String url; - private List deps; - private List overrides; - private List modules; - private List pluginOverrides; - private List plugins; - private Map dirs; - private static final String MAVEN_CENTRAL_URL = "http://repo1.maven.org/maven2"; - private final ScmElement scm; - - public Project(Id projectId, - Parent parent, - String packaging, - List properties, - Repositories repositories, - String description, - String url, - List overrides, - List deps, - List modules, - List pluginOverrides, - List plugins, - Map dirs, - ScmElement scm) { - this.projectId = projectId; - this.parent = parent; - this.packaging = packaging; - this.properties = properties; - this.repositories = repositories; - this.description = description; - this.url = url; - this.overrides = overrides; - this.deps = deps; - this.modules = modules; - this.pluginOverrides = pluginOverrides; - this.plugins = plugins; - this.dirs = dirs; - this.scm = scm; - } - - public Id getProjectId() { - return projectId; - } - - public Parent getParent() { - return parent; - } - - public String getPackaging() { - return packaging; - } - - public List getPlugins() { - return plugins; - } - - public List getPluginOverrides() { - return pluginOverrides; - } - - public List getModules() { - return modules; - } - - public List getOverrides() { - return overrides; - } - - public List getProperties() { - return properties; - } - - public Repositories getRepositories() { - return repositories; - } - - public String getDescription() { - return description; - } - - public String getUrl() { - return url; - } - - public List getDeps() { - return deps; - } - - public Map getDirs() { - return dirs; - } - - public Model toMavenModel() { - Model model = new Model(); - model.setBuild(new Build()); - model.setDescription(description); - model.setUrl(url); - model.setName(projectId.getArtifact()); - model.setGroupId(projectId.getGroup()); - model.setVersion(projectId.getVersion()); - model.setArtifactId(projectId.getArtifact()); - model.setModelVersion("4.0.0"); - - // parent - if (parent != null) { - model.setParent(parent); - } - - model.setPackaging(packaging); - - if (properties != null) { - Properties modelProperties = new Properties(); - for (Property p : properties) { - modelProperties.setProperty(p.getKey(), p.getValue()); - } - model.setProperties(modelProperties); - } - - // Add jar repository urls. - if (null != repositories) { - for (String repoUrl : repositories.getRepositories()) { - Repository repository = new Repository(); - repository.setId(Integer.toString(repoUrl.hashCode())); - repository.setUrl(repoUrl); - model.addRepository(repository); - } - } - - // Add dependency management - if (overrides != null) { - DependencyManagement depMan = new DependencyManagement(); - for (Id dep : overrides) { - Dependency dependency = new Dependency(); - dependency.setGroupId(dep.getGroup()); - dependency.setArtifactId(dep.getArtifact()); - dependency.setVersion(dep.getVersion()); - //JVZ: We need to parse these - dependency.setType("jar"); - - if (null != dep.getClassifier()) { - dependency.setClassifier(dep.getClassifier()); - } - depMan.addDependency(dependency); - } - model.setDependencyManagement(depMan); - } - - // Add project dependencies. - if (deps != null) { - for (Id dep : deps) { - Dependency dependency = new Dependency(); - dependency.setGroupId(dep.getGroup()); - dependency.setArtifactId(dep.getArtifact()); - dependency.setVersion(dep.getVersion()); - //JVZ: We need to parse these - dependency.setType("jar"); - - if (null != dep.getClassifier()) { - dependency.setClassifier(dep.getClassifier()); - } - model.addDependency(dependency); - } + private final Id projectId; + private final Parent parent; + private String packaging = "jar"; + private List properties; + private final Repositories repositories; + private final String description; + private final String url; + private List deps; + private List overrides; + private List modules; + private List pluginOverrides; + private List plugins; + private Map dirs; + private static final String MAVEN_CENTRAL_URL = "http://repo1.maven.org/maven2"; + private final ScmElement scm; + + public Project( + Id projectId, + Parent parent, + String packaging, + List properties, + Repositories repositories, + String description, + String url, + List overrides, + List deps, + List modules, + List pluginOverrides, + List plugins, + Map dirs, + ScmElement scm) { + this.projectId = projectId; + this.parent = parent; + this.packaging = packaging; + this.properties = properties; + this.repositories = repositories; + this.description = description; + this.url = url; + this.overrides = overrides; + this.deps = deps; + this.modules = modules; + this.pluginOverrides = pluginOverrides; + this.plugins = plugins; + this.dirs = dirs; + this.scm = scm; + } + + public Id getProjectId() { + return projectId; + } + + public Parent getParent() { + return parent; + } + + public String getPackaging() { + return packaging; } - if (modules != null) { - model.setModules(modules); + public List getPlugins() { + return plugins; } - if (pluginOverrides != null) { - PluginManagement management = new PluginManagement(); - management.setPlugins(pluginOverrides); - model.getBuild().setPluginManagement(management); + public List getPluginOverrides() { + return pluginOverrides; } - if (plugins != null) { - model.getBuild().setPlugins(plugins); + public List getModules() { + return modules; } - // Optional source dirs customization. - if (dirs != null) { - Build build = new Build(); - String srcDir = dirs.get("src"); - String testDir = dirs.get("test"); + public List getOverrides() { + return overrides; + } + + public List getProperties() { + return properties; + } - if (null != srcDir) - build.setSourceDirectory(srcDir); + public Repositories getRepositories() { + return repositories; + } - if (null != testDir) - build.setTestSourceDirectory(testDir); + public String getDescription() { + return description; + } - model.setBuild(build); + public String getUrl() { + return url; } - if (null != scm) { - Scm scm = new Scm(); - scm.setConnection(this.scm.getConnection()); - scm.setDeveloperConnection(this.scm.getDeveloperConnection()); - scm.setUrl(this.scm.getUrl()); + public List getDeps() { + return deps; + } - model.setScm(scm); + public Map getDirs() { + return dirs; } - return model; - } + public Model toMavenModel() { + Model model = new Model(); + model.setBuild(new Build()); + model.setDescription(description); + model.setUrl(url); + model.setName(projectId.getArtifact()); + model.setGroupId(projectId.getGroup()); + model.setVersion(projectId.getVersion()); + model.setArtifactId(projectId.getArtifact()); + model.setModelVersion("4.0.0"); + + // parent + if (parent != null) { + model.setParent(parent); + } + + model.setPackaging(packaging); + + if (properties != null) { + Properties modelProperties = new Properties(); + for (Property p : properties) { + modelProperties.setProperty(p.getKey(), p.getValue()); + } + model.setProperties(modelProperties); + } + + // Add jar repository urls. + if (null != repositories) { + for (String repoUrl : repositories.getRepositories()) { + Repository repository = new Repository(); + repository.setId(Integer.toString(repoUrl.hashCode())); + repository.setUrl(repoUrl); + model.addRepository(repository); + } + } + + // Add dependency management + if (overrides != null) { + DependencyManagement depMan = new DependencyManagement(); + for (Id dep : overrides) { + Dependency dependency = new Dependency(); + dependency.setGroupId(dep.getGroup()); + dependency.setArtifactId(dep.getArtifact()); + dependency.setVersion(dep.getVersion()); + // JVZ: We need to parse these + dependency.setType("jar"); + + if (null != dep.getClassifier()) { + dependency.setClassifier(dep.getClassifier()); + } + depMan.addDependency(dependency); + } + model.setDependencyManagement(depMan); + } + + // Add project dependencies. + if (deps != null) { + for (Id dep : deps) { + Dependency dependency = new Dependency(); + dependency.setGroupId(dep.getGroup()); + dependency.setArtifactId(dep.getArtifact()); + dependency.setVersion(dep.getVersion()); + // JVZ: We need to parse these + dependency.setType("jar"); + + if (null != dep.getClassifier()) { + dependency.setClassifier(dep.getClassifier()); + } + model.addDependency(dependency); + } + } + + if (modules != null) { + model.setModules(modules); + } + + if (pluginOverrides != null) { + PluginManagement management = new PluginManagement(); + management.setPlugins(pluginOverrides); + model.getBuild().setPluginManagement(management); + } + + if (plugins != null) { + model.getBuild().setPlugins(plugins); + } - public ScmElement getScm() { - return scm; - } + // Optional source dirs customization. + if (dirs != null) { + Build build = new Build(); + String srcDir = dirs.get("src"); + String testDir = dirs.get("test"); + + if (null != srcDir) build.setSourceDirectory(srcDir); + + if (null != testDir) build.setTestSourceDirectory(testDir); + + model.setBuild(build); + } + + if (null != scm) { + Scm scm = new Scm(); + scm.setConnection(this.scm.getConnection()); + scm.setDeveloperConnection(this.scm.getDeveloperConnection()); + scm.setUrl(this.scm.getUrl()); + + model.setScm(scm); + } + + return model; + } + + public ScmElement getScm() { + return scm; + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Property.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Property.java index 22de1cf3..356cb10a 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Property.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Property.java @@ -8,25 +8,27 @@ package org.sonatype.maven.polyglot.atom.parsing; public class Property { - private String key; - private String value; - - public Property(String key, String value) { - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - public void setKey(String key) { - this.key = key; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } - + private String key; + private String value; + + public Property(String key, String value) { + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Repositories.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Repositories.java index 0fed9725..6fe8378f 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Repositories.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Repositories.java @@ -13,17 +13,18 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Repositories extends Element { - private final List repositories; - public Repositories(List repositories) { - this.repositories = repositories; - } + private final List repositories; - public List getRepositories() { - return repositories; - } + public Repositories(List repositories) { + this.repositories = repositories; + } - @Override - public String toString() { - return repositories.toString(); - } + public List getRepositories() { + return repositories; + } + + @Override + public String toString() { + return repositories.toString(); + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/ScmElement.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/ScmElement.java index 5bec25b7..ac6a7589 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/ScmElement.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/ScmElement.java @@ -11,25 +11,25 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ class ScmElement { - private final String connection; - private final String developerConnection; - private final String url; + private final String connection; + private final String developerConnection; + private final String url; - ScmElement(String connection, String developerConnection, String url) { - this.connection = connection; - this.developerConnection = developerConnection; - this.url = url; - } + ScmElement(String connection, String developerConnection, String url) { + this.connection = connection; + this.developerConnection = developerConnection; + this.url = url; + } - public String getConnection() { - return connection; - } + public String getConnection() { + return connection; + } - public String getDeveloperConnection() { - return developerConnection; - } + public String getDeveloperConnection() { + return developerConnection; + } - public String getUrl() { - return url; - } + public String getUrl() { + return url; + } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Token.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Token.java index 8baefe84..95d57f00 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Token.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Token.java @@ -16,157 +16,149 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Token { - public static final String PLUGIN_OVERRIDE_KEYWORD = "plugin-override"; - public final String value; - public final Kind kind; - - public Token(String value, Kind kind) { - this.value = value; - this.kind = kind; - } - - public static enum Kind { - IDENT, - STRING, - DOT, - - COLON, - MINUS, - DIVIDE, - STAR, - MODULUS, - - COMMA, - - AT, - ARROW, - HASHROCKET, - - // Comparison operators - LEFT_WAVE, - GREATER, - LEQ, - GEQ, - - LPAREN, - RPAREN, - LBRACKET, - RBRACKET, - LBRACE, - RBRACE, - - // keywords - REQUIRE, - SRCS, - SCM, - - PROJECT, - REPOSITORIES, - OR, - AND, - NOT, - DEPS, - ID, - PARENT, - - // specials - EOL, - INDENT, - DASH, - PACKAGING, - OVERRIDES, - PROPS, - MODULES, - PLUGIN, - PLUGIN_OVERRIDE; - - private static final Map TOKEN_MAP = new HashMap(); - - static { - // can we optimize with chars? - TOKEN_MAP.put("@", AT); - TOKEN_MAP.put(".", DOT); - TOKEN_MAP.put("-", DASH); - TOKEN_MAP.put(":", COLON); - TOKEN_MAP.put("*", STAR); - TOKEN_MAP.put(",", COMMA); - TOKEN_MAP.put("->", ARROW); - - TOKEN_MAP.put("<=", LEQ); - TOKEN_MAP.put(">=", GEQ); - TOKEN_MAP.put("<<", LEFT_WAVE); - TOKEN_MAP.put(">", GREATER); - TOKEN_MAP.put("=>", HASHROCKET); - - TOKEN_MAP.put("(", LPAREN); - TOKEN_MAP.put(")", RPAREN); - TOKEN_MAP.put("[", LBRACKET); - TOKEN_MAP.put("]", RBRACKET); - TOKEN_MAP.put("{", LBRACE); // Alias braces as brackets. - TOKEN_MAP.put("}", RBRACE); - TOKEN_MAP.put("\n", EOL); - - TOKEN_MAP.put("id", ID); - TOKEN_MAP.put("inherits", PARENT); - TOKEN_MAP.put("as", PACKAGING); - TOKEN_MAP.put("properties", PROPS); - TOKEN_MAP.put("deps", DEPS); - TOKEN_MAP.put("overrides", OVERRIDES); - TOKEN_MAP.put("repositories", REPOSITORIES); - TOKEN_MAP.put("project", PROJECT); - TOKEN_MAP.put("srcs", SRCS); - TOKEN_MAP.put("scm", SCM); - TOKEN_MAP.put("modules", MODULES); - TOKEN_MAP.put("plugin", PLUGIN); - TOKEN_MAP.put(PLUGIN_OVERRIDE_KEYWORD, PLUGIN_OVERRIDE); - - - TOKEN_MAP.put("||", OR); - TOKEN_MAP.put("&&", AND); - TOKEN_MAP.put("!", NOT); + public static final String PLUGIN_OVERRIDE_KEYWORD = "plugin-override"; + public final String value; + public final Kind kind; + + public Token(String value, Kind kind) { + this.value = value; + this.kind = kind; + } + + public static enum Kind { + IDENT, + STRING, + DOT, + + COLON, + MINUS, + DIVIDE, + STAR, + MODULUS, + + COMMA, + + AT, + ARROW, + HASHROCKET, + + // Comparison operators + LEFT_WAVE, + GREATER, + LEQ, + GEQ, + + LPAREN, + RPAREN, + LBRACKET, + RBRACKET, + LBRACE, + RBRACE, + + // keywords + REQUIRE, + SRCS, + SCM, + + PROJECT, + REPOSITORIES, + OR, + AND, + NOT, + DEPS, + ID, + PARENT, + + // specials + EOL, + INDENT, + DASH, + PACKAGING, + OVERRIDES, + PROPS, + MODULES, + PLUGIN, + PLUGIN_OVERRIDE; + + private static final Map TOKEN_MAP = new HashMap(); + + static { + // can we optimize with chars? + TOKEN_MAP.put("@", AT); + TOKEN_MAP.put(".", DOT); + TOKEN_MAP.put("-", DASH); + TOKEN_MAP.put(":", COLON); + TOKEN_MAP.put("*", STAR); + TOKEN_MAP.put(",", COMMA); + TOKEN_MAP.put("->", ARROW); + + TOKEN_MAP.put("<=", LEQ); + TOKEN_MAP.put(">=", GEQ); + TOKEN_MAP.put("<<", LEFT_WAVE); + TOKEN_MAP.put(">", GREATER); + TOKEN_MAP.put("=>", HASHROCKET); + + TOKEN_MAP.put("(", LPAREN); + TOKEN_MAP.put(")", RPAREN); + TOKEN_MAP.put("[", LBRACKET); + TOKEN_MAP.put("]", RBRACKET); + TOKEN_MAP.put("{", LBRACE); // Alias braces as brackets. + TOKEN_MAP.put("}", RBRACE); + TOKEN_MAP.put("\n", EOL); + + TOKEN_MAP.put("id", ID); + TOKEN_MAP.put("inherits", PARENT); + TOKEN_MAP.put("as", PACKAGING); + TOKEN_MAP.put("properties", PROPS); + TOKEN_MAP.put("deps", DEPS); + TOKEN_MAP.put("overrides", OVERRIDES); + TOKEN_MAP.put("repositories", REPOSITORIES); + TOKEN_MAP.put("project", PROJECT); + TOKEN_MAP.put("srcs", SRCS); + TOKEN_MAP.put("scm", SCM); + TOKEN_MAP.put("modules", MODULES); + TOKEN_MAP.put("plugin", PLUGIN); + TOKEN_MAP.put(PLUGIN_OVERRIDE_KEYWORD, PLUGIN_OVERRIDE); + + TOKEN_MAP.put("||", OR); + TOKEN_MAP.put("&&", AND); + TOKEN_MAP.put("!", NOT); + } + + /** + * from token text, determines kind. + */ + public static Kind determine(String value) { + char first = value.charAt(0); + + if (first == '"' || first == '\'') return STRING; + + Kind knownKind = TOKEN_MAP.get(value); + if (null != knownKind) return knownKind; + + return IDENT; + } } - /** - * from token text, determines kind. - */ - public static Kind determine(String value) { - char first = value.charAt(0); + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - if (first == '"' || first == '\'') - return STRING; + Token token = (Token) o; - Kind knownKind = TOKEN_MAP.get(value); - if (null != knownKind) - return knownKind; + return (kind == token.kind) && !(value != null ? !value.equals(token.value) : token.value != null); + } + + @Override + public int hashCode() { + int result = value != null ? value.hashCode() : 0; + result = 31 * result + (kind != null ? kind.hashCode() : 0); + return result; + } - return IDENT; + @Override + public String toString() { + return "Token{" + "value='" + value + '\'' + ", kind=" + kind + '}'; } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Token token = (Token) o; - - return (kind == token.kind) - && !(value != null ? !value.equals(token.value) : token.value != null); - - } - - @Override - public int hashCode() { - int result = value != null ? value.hashCode() : 0; - result = 31 * result + (kind != null ? kind.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return "Token{" + - "value='" + value + '\'' + - ", kind=" + kind + - '}'; - } } diff --git a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Tokenizer.java b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Tokenizer.java index fdde34de..b391b838 100644 --- a/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Tokenizer.java +++ b/polyglot-atom/src/main/java/org/sonatype/maven/polyglot/atom/parsing/Tokenizer.java @@ -16,204 +16,198 @@ * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class Tokenizer { - private final String input; - - public Tokenizer(String input) { - this.input = input.replace("\r\n", "\n").replace('\r', '\n'); - } - - private static final int NON = 0; // MUST be zero - private static final int SINGLE_TOKEN = 1; - private static final int SEQUENCE_TOKEN = 2; - - private static final int[] DELIMITERS = new int[256]; - private static final boolean[] STRING_TERMINATORS = new boolean[256]; - - static { - - DELIMITERS['+'] = SEQUENCE_TOKEN; - DELIMITERS['/'] = SEQUENCE_TOKEN; - DELIMITERS['*'] = SEQUENCE_TOKEN; - DELIMITERS['>'] = SEQUENCE_TOKEN; - DELIMITERS['<'] = SEQUENCE_TOKEN; - DELIMITERS['!'] = SEQUENCE_TOKEN; - DELIMITERS['?'] = SEQUENCE_TOKEN; - - // SINGLE token delimiters are one char in length in any context - DELIMITERS['\n'] = SINGLE_TOKEN; - DELIMITERS['.'] = SINGLE_TOKEN; - DELIMITERS[','] = SINGLE_TOKEN; - DELIMITERS[':'] = SINGLE_TOKEN; - DELIMITERS['('] = SINGLE_TOKEN; - DELIMITERS[')'] = SINGLE_TOKEN; - DELIMITERS['['] = SINGLE_TOKEN; - DELIMITERS[']'] = SINGLE_TOKEN; - DELIMITERS['{'] = SINGLE_TOKEN; - DELIMITERS['}'] = SINGLE_TOKEN; - DELIMITERS['@'] = SINGLE_TOKEN; - - STRING_TERMINATORS['"'] = true; - STRING_TERMINATORS['\''] = true; - STRING_TERMINATORS['`'] = true; - } - - public List tokenize() { - List tokens = new ArrayList(); - char[] input = this.input.toCharArray(); - - int i = 0, start = 0; - boolean inWhitespace = false, inDelimiter = false, inComment = false, leading = true; - char inStringSequence = 0; - for (; i < input.length; i++) { - char c = input[i]; - - // strings and sequences - if (STRING_TERMINATORS[c]) { - - if (inStringSequence > 0) { - - // end of the current string sequence. bake. - if (inStringSequence == c) { - // +1 to include the terminating token. - bakeToken(tokens, input, i + 1, start); - start = i + 1; - - inStringSequence = 0; // reset to normal language - continue; - } - // it's a string terminator but it's ok, it's part of the string, ignore... - - } else { - // Also bake if there is any leading tokenage. - if (i > start) { - bakeToken(tokens, input, i, start); - start = i; - } - - inStringSequence = c; // start string - } - } - - // skip everything if we're in a string... - if (inStringSequence > 0) - continue; - - if (c == '\n') { - leading = true; - } - - // Comments beginning with # - if (c == '#') { - inComment = true; - } - - // We run the comment until the end of the line - if (inComment) { - if (c == '\n') - inComment = false; - start = i; - continue; - } - - // whitespace is ignored unless it is leading... - if (isWhitespace(c)) { - inDelimiter = false; - - if (!inWhitespace) { - //bake token - bakeToken(tokens, input, i, start); - inWhitespace = true; - } - - // leading whitespace is a special token... - if (leading) { - tokens.add(new Token(" ", Token.Kind.INDENT)); - } - - // skip whitespace - start = i + 1; - continue; - } - - // any non-whitespace character encountered - inWhitespace = false; - if (c != '\n') - leading = false; - - // For delimiters that are 1-char long in all contexts, - // break early. - if (isSingleTokenDelimiter(c)) { - - bakeToken(tokens, input, i, start); - start = i; + private final String input; - // Also add the delimiter. - bakeToken(tokens, input, i + 1, start); - start = i + 1; - continue; - } + public Tokenizer(String input) { + this.input = input.replace("\r\n", "\n").replace('\r', '\n'); + } - // is delimiter - if (isDelimiter(c)) { + private static final int NON = 0; // MUST be zero + private static final int SINGLE_TOKEN = 1; + private static final int SEQUENCE_TOKEN = 2; + + private static final int[] DELIMITERS = new int[256]; + private static final boolean[] STRING_TERMINATORS = new boolean[256]; + + static { + DELIMITERS['+'] = SEQUENCE_TOKEN; + DELIMITERS['/'] = SEQUENCE_TOKEN; + DELIMITERS['*'] = SEQUENCE_TOKEN; + DELIMITERS['>'] = SEQUENCE_TOKEN; + DELIMITERS['<'] = SEQUENCE_TOKEN; + DELIMITERS['!'] = SEQUENCE_TOKEN; + DELIMITERS['?'] = SEQUENCE_TOKEN; + + // SINGLE token delimiters are one char in length in any context + DELIMITERS['\n'] = SINGLE_TOKEN; + DELIMITERS['.'] = SINGLE_TOKEN; + DELIMITERS[','] = SINGLE_TOKEN; + DELIMITERS[':'] = SINGLE_TOKEN; + DELIMITERS['('] = SINGLE_TOKEN; + DELIMITERS[')'] = SINGLE_TOKEN; + DELIMITERS['['] = SINGLE_TOKEN; + DELIMITERS[']'] = SINGLE_TOKEN; + DELIMITERS['{'] = SINGLE_TOKEN; + DELIMITERS['}'] = SINGLE_TOKEN; + DELIMITERS['@'] = SINGLE_TOKEN; + + STRING_TERMINATORS['"'] = true; + STRING_TERMINATORS['\''] = true; + STRING_TERMINATORS['`'] = true; + } - if (!inDelimiter) { - bakeToken(tokens, input, i, start); - inDelimiter = true; - start = i; + public List tokenize() { + List tokens = new ArrayList(); + char[] input = this.input.toCharArray(); + + int i = 0, start = 0; + boolean inWhitespace = false, inDelimiter = false, inComment = false, leading = true; + char inStringSequence = 0; + for (; i < input.length; i++) { + char c = input[i]; + + // strings and sequences + if (STRING_TERMINATORS[c]) { + + if (inStringSequence > 0) { + + // end of the current string sequence. bake. + if (inStringSequence == c) { + // +1 to include the terminating token. + bakeToken(tokens, input, i + 1, start); + start = i + 1; + + inStringSequence = 0; // reset to normal language + continue; + } + // it's a string terminator but it's ok, it's part of the string, ignore... + + } else { + // Also bake if there is any leading tokenage. + if (i > start) { + bakeToken(tokens, input, i, start); + start = i; + } + + inStringSequence = c; // start string + } + } + + // skip everything if we're in a string... + if (inStringSequence > 0) continue; + + if (c == '\n') { + leading = true; + } + + // Comments beginning with # + if (c == '#') { + inComment = true; + } + + // We run the comment until the end of the line + if (inComment) { + if (c == '\n') inComment = false; + start = i; + continue; + } + + // whitespace is ignored unless it is leading... + if (isWhitespace(c)) { + inDelimiter = false; + + if (!inWhitespace) { + // bake token + bakeToken(tokens, input, i, start); + inWhitespace = true; + } + + // leading whitespace is a special token... + if (leading) { + tokens.add(new Token(" ", Token.Kind.INDENT)); + } + + // skip whitespace + start = i + 1; + continue; + } + + // any non-whitespace character encountered + inWhitespace = false; + if (c != '\n') leading = false; + + // For delimiters that are 1-char long in all contexts, + // break early. + if (isSingleTokenDelimiter(c)) { + + bakeToken(tokens, input, i, start); + start = i; + + // Also add the delimiter. + bakeToken(tokens, input, i + 1, start); + start = i + 1; + continue; + } + + // is delimiter + if (isDelimiter(c)) { + + if (!inDelimiter) { + bakeToken(tokens, input, i, start); + inDelimiter = true; + start = i; + } + + continue; + } + + // if coming out of a delimiter, we still need to bake + if (inDelimiter) { + bakeToken(tokens, input, i, start); + start = i; + inDelimiter = false; + } } - continue; - } + // collect residual token + if (i > start && !inComment) { + // we don't want trailing whitespace + bakeToken(tokens, input, i, start); + } - // if coming out of a delimiter, we still need to bake - if (inDelimiter) { - bakeToken(tokens, input, i, start); - start = i; - inDelimiter = false; - } + return tokens; } - // collect residual token - if (i > start && !inComment) { - // we don't want trailing whitespace - bakeToken(tokens, input, i, start); + private static boolean isWhitespace(char c) { + return '\n' != c && Character.isWhitespace(c); } - return tokens; - } - - private static boolean isWhitespace(char c) { - return '\n' != c && Character.isWhitespace(c); - } + static boolean isSingleTokenDelimiter(char c) { + return DELIMITERS[c] == SINGLE_TOKEN; + } - static boolean isSingleTokenDelimiter(char c) { - return DELIMITERS[c] == SINGLE_TOKEN; - } + public static String detokenize(List tokens) { + StringBuilder builder = new StringBuilder(); - public static String detokenize(List tokens) { - StringBuilder builder = new StringBuilder(); + for (Token token : tokens) { + if (Token.Kind.INDENT == token.kind) builder.append("~"); + else builder.append(token.value); + builder.append(' '); + } - for (Token token : tokens) { - if (Token.Kind.INDENT == token.kind) - builder.append("~"); - else - builder.append(token.value); - builder.append(' '); + return builder.toString().trim(); } - return builder.toString().trim(); - } - - private static boolean isDelimiter(char c) { - return DELIMITERS[c] != NON; - } + private static boolean isDelimiter(char c) { + return DELIMITERS[c] != NON; + } - private static void bakeToken(List tokens, char[] input, int i, int start) { - if (i > start) { - String value = new String(input, start, i - start); + private static void bakeToken(List tokens, char[] input, int i, int start) { + if (i > start) { + String value = new String(input, start, i - start); - // remove this disgusting hack when you can fix the lexer. - tokens.add(new Token(value, Token.Kind.determine(value))); + // remove this disgusting hack when you can fix the lexer. + tokens.add(new Token(value, Token.Kind.determine(value))); + } } - } -} \ No newline at end of file +} diff --git a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithGuiceTest.java b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithGuiceTest.java index 9de35f5b..d7f5ffb8 100644 --- a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithGuiceTest.java +++ b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithGuiceTest.java @@ -12,10 +12,8 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -28,96 +26,100 @@ public class AtomModelWithGuiceTest extends InjectedTestCase { - @Inject - @Named("${basedir}/src/test/poms") - private File poms; + @Inject + @Named("${basedir}/src/test/poms") + private File poms; - public void testAtomModelWriter() throws Exception { - File pom = new File(poms, "guice-pom.xml"); - MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); - // - testMavenModelForCompleteness(xmlModel); - // - // Write out the Atom POM - // - ModelWriter writer = new AtomModelWriter(); - StringWriter w = new StringWriter(); - writer.write(w, new HashMap(), xmlModel); + public void testAtomModelWriter() throws Exception { + File pom = new File(poms, "guice-pom.xml"); + MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + // + testMavenModelForCompleteness(xmlModel); + // + // Write out the Atom POM + // + ModelWriter writer = new AtomModelWriter(); + StringWriter w = new StringWriter(); + writer.write(w, new HashMap(), xmlModel); - // Let's take a look at see what's there - System.out.println(w.toString()); + // Let's take a look at see what's there + System.out.println(w.toString()); - // - // Read in the Atom POM - // - ModelReader atomModelReader = new AtomModelReader(); - StringReader r = new StringReader(w.toString()); - Model atomModel = atomModelReader.read(r, new HashMap()); - // - // Test for fidelity - // - assertNotNull(atomModel); - testMavenModelForCompleteness(atomModel); + // + // Read in the Atom POM + // + ModelReader atomModelReader = new AtomModelReader(); + StringReader r = new StringReader(w.toString()); + Model atomModel = atomModelReader.read(r, new HashMap()); + // + // Test for fidelity + // + assertNotNull(atomModel); + testMavenModelForCompleteness(atomModel); - w = new StringWriter(); - MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); - xmlWriter.write(w, xmlModel); - System.out.println(w.toString()); + w = new StringWriter(); + MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); + xmlWriter.write(w, xmlModel); + System.out.println(w.toString()); - assertEquals(xmlModel.getModules(), atomModel.getModules()); - assertEquals(xmlModel.getRepositories().size(), atomModel.getRepositories().size()); - } + assertEquals(xmlModel.getModules(), atomModel.getModules()); + assertEquals( + xmlModel.getRepositories().size(), atomModel.getRepositories().size()); + } - void testMavenModelForCompleteness(Model model) { - // - // parent - // - assertEquals("com.google.inject:guice-parent:3.0-SNAPSHOT", model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); - // - // id - // -// assertEquals("org.sonatype.oss:oss-parent:6", model.getParent().getGroupId() + ":" + model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); - // - // properties - // -// assertEquals("pom", model.getPackaging()); - assertNull(model.getProperties().getProperty("org.testng.version")); - assertEquals("1.3", model.getProperties().getProperty("guice.api.version")); - assertEquals("true", model.getProperties().getProperty("guice.with.jarjar")); - assertEquals("true", model.getProperties().getProperty("guice.with.no_aop")); - assertEquals("UTF-8", model.getProperties().getProperty("project.build.sourceEncoding")); - // - // depMan - // - Dependency testNg = model.getDependencies().get(0); - assertEquals("org.testng:testng:5.11", gav(testNg)); - assertEquals("jdk15", testNg.getClassifier()); - // - // modules - // - assertEquals("core", model.getModules().get(0)); - assertEquals("extensions", model.getModules().get(1)); - // - // plugins - // - Plugin p0 = model.getBuild().getPluginManagement().getPlugins().get(0); - assertEquals("org.apache.maven.plugins:maven-remote-resources-plugin:1.1", gav(p0)); + void testMavenModelForCompleteness(Model model) { + // + // parent + // + assertEquals( + "com.google.inject:guice-parent:3.0-SNAPSHOT", + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); + // + // id + // + // assertEquals("org.sonatype.oss:oss-parent:6", model.getParent().getGroupId() + ":" + + // model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); + // + // properties + // + // assertEquals("pom", model.getPackaging()); + assertNull(model.getProperties().getProperty("org.testng.version")); + assertEquals("1.3", model.getProperties().getProperty("guice.api.version")); + assertEquals("true", model.getProperties().getProperty("guice.with.jarjar")); + assertEquals("true", model.getProperties().getProperty("guice.with.no_aop")); + assertEquals("UTF-8", model.getProperties().getProperty("project.build.sourceEncoding")); + // + // depMan + // + Dependency testNg = model.getDependencies().get(0); + assertEquals("org.testng:testng:5.11", gav(testNg)); + assertEquals("jdk15", testNg.getClassifier()); + // + // modules + // + assertEquals("core", model.getModules().get(0)); + assertEquals("extensions", model.getModules().get(1)); + // + // plugins + // + Plugin p0 = model.getBuild().getPluginManagement().getPlugins().get(0); + assertEquals("org.apache.maven.plugins:maven-remote-resources-plugin:1.1", gav(p0)); - p0 = model.getBuild().getPluginManagement().getPlugins().get(1); - assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); - assertNull(p0.getConfiguration()); + p0 = model.getBuild().getPluginManagement().getPlugins().get(1); + assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); + assertNull(p0.getConfiguration()); - p0 = model.getBuild().getPluginManagement().getPlugins().get(2); - assertEquals("org.codehaus.mojo:animal-sniffer-maven-plugin:1.6", gav(p0)); - assertEquals(3, ((Xpp3Dom)p0.getConfiguration()).getChild("signature").getChildCount()); - } + p0 = model.getBuild().getPluginManagement().getPlugins().get(2); + assertEquals("org.codehaus.mojo:animal-sniffer-maven-plugin:1.6", gav(p0)); + assertEquals(3, ((Xpp3Dom) p0.getConfiguration()).getChild("signature").getChildCount()); + } - String gav(Dependency d) { - return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); - } + String gav(Dependency d) { + return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); + } - String gav(Plugin p) { - return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); - } + String gav(Plugin p) { + return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); + } } diff --git a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithMavenTest.java b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithMavenTest.java index 56ed9676..5865ce13 100644 --- a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithMavenTest.java +++ b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithMavenTest.java @@ -12,10 +12,8 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -27,98 +25,110 @@ public class AtomModelWithMavenTest extends InjectedTestCase { - @Inject - @Named("${basedir}/src/test/poms") - private File poms; - - public void testAtomModelWriter() throws Exception { - File pom = new File(poms, "maven-parent-pom.xml"); - MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); - // - //testMavenModelForCompleteness(xmlModel); - // - // Write out the Atom POM - // - ModelWriter writer = new AtomModelWriter(); - StringWriter w = new StringWriter(); - writer.write(w, new HashMap(), xmlModel); - - // Let's take a look at see what's there - System.out.println(w.toString()); - - // - // Read in the Atom POM - // - ModelReader atomModelReader = new AtomModelReader(); - StringReader r = new StringReader(w.toString()); - Model atomModel = atomModelReader.read(r, new HashMap()); - // - // Test for fidelity - // - assertNotNull(atomModel); - testMavenModelForCompleteness(atomModel); + @Inject + @Named("${basedir}/src/test/poms") + private File poms; - } + public void testAtomModelWriter() throws Exception { + File pom = new File(poms, "maven-parent-pom.xml"); + MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + // + // testMavenModelForCompleteness(xmlModel); + // + // Write out the Atom POM + // + ModelWriter writer = new AtomModelWriter(); + StringWriter w = new StringWriter(); + writer.write(w, new HashMap(), xmlModel); - void testMavenModelForCompleteness(Model model) { - // - // repos - // - assertEquals(0, model.getRepositories().size()); - // - // parent - // - assertEquals("org.apache.maven:maven:3.0.4-SNAPSHOT", model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); - // - // id - // - assertEquals("org.eclipse.tesla:tesla:3", model.getParent().getGroupId() + ":" + model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); - // - // properties - // - assertEquals("pom", model.getPackaging()); - assertNull(model.getProperties().getProperty("org.testng.version")); - assertNull(model.getProperties().getProperty("org.mortbay.jetty.version")); - assertEquals("1.7", model.getProperties().getProperty("gossipVersion")); - assertEquals("1.12", model.getProperties().getProperty("aetherVersion")); - assertEquals("4.8.2", model.getProperties().getProperty("junitVersion")); - assertEquals("Eclipse Tesla", model.getProperties().getProperty("distributionName")); - assertEquals("eclipse-tesla", model.getProperties().getProperty("distributionId")); - // - // depMan (overrides) - // - assertEquals("org.apache.maven:maven-model:${project.version}", gav(model.getDependencyManagement().getDependencies().get(0))); - assertEquals("org.apache.maven:maven-core:${project.version}", gav(model.getDependencyManagement().getDependencies().get(5))); - assertEquals("org.sonatype.sisu:sisu-inject-plexus:${sisuInjectVersion}", gav(model.getDependencyManagement().getDependencies().get(12))); - assertEquals("org.apache.maven.wagon:wagon-http-shared:${wagonVersion}", gav(model.getDependencyManagement().getDependencies().get(22))); - assertEquals("org.sonatype.gossip:gossip-core:${gossipVersion}", gav(model.getDependencyManagement().getDependencies().get(35))); - // - // modules - // - assertEquals("maven-core", model.getModules().get(0)); - assertEquals("maven-settings-builder", model.getModules().get(4)); - assertEquals("maven-aether-provider", model.getModules().get(6)); - // - // plugins - // - Plugin p0 = model.getBuild().getPluginManagement().getPlugins().get(0); - assertEquals("org.codehaus.plexus:plexus-component-metadata:${plexusVersion}", gav(p0)); - assertNull(p0.getConfiguration()); + // Let's take a look at see what's there + System.out.println(w.toString()); + // + // Read in the Atom POM + // + ModelReader atomModelReader = new AtomModelReader(); + StringReader r = new StringReader(w.toString()); + Model atomModel = atomModelReader.read(r, new HashMap()); + // + // Test for fidelity + // + assertNotNull(atomModel); + testMavenModelForCompleteness(atomModel); + } - p0 = model.getBuild().getPluginManagement().getPlugins().get(1); - assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); - assertEquals("1.5", ((Xpp3Dom)p0.getConfiguration()).getChild("source").getValue()); - assertEquals("1.5", ((Xpp3Dom)p0.getConfiguration()).getChild("target").getValue()); - } + void testMavenModelForCompleteness(Model model) { + // + // repos + // + assertEquals(0, model.getRepositories().size()); + // + // parent + // + assertEquals( + "org.apache.maven:maven:3.0.4-SNAPSHOT", + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); + // + // id + // + assertEquals( + "org.eclipse.tesla:tesla:3", + model.getParent().getGroupId() + ":" + model.getParent().getArtifactId() + ":" + + model.getParent().getVersion()); + // + // properties + // + assertEquals("pom", model.getPackaging()); + assertNull(model.getProperties().getProperty("org.testng.version")); + assertNull(model.getProperties().getProperty("org.mortbay.jetty.version")); + assertEquals("1.7", model.getProperties().getProperty("gossipVersion")); + assertEquals("1.12", model.getProperties().getProperty("aetherVersion")); + assertEquals("4.8.2", model.getProperties().getProperty("junitVersion")); + assertEquals("Eclipse Tesla", model.getProperties().getProperty("distributionName")); + assertEquals("eclipse-tesla", model.getProperties().getProperty("distributionId")); + // + // depMan (overrides) + // + assertEquals( + "org.apache.maven:maven-model:${project.version}", + gav(model.getDependencyManagement().getDependencies().get(0))); + assertEquals( + "org.apache.maven:maven-core:${project.version}", + gav(model.getDependencyManagement().getDependencies().get(5))); + assertEquals( + "org.sonatype.sisu:sisu-inject-plexus:${sisuInjectVersion}", + gav(model.getDependencyManagement().getDependencies().get(12))); + assertEquals( + "org.apache.maven.wagon:wagon-http-shared:${wagonVersion}", + gav(model.getDependencyManagement().getDependencies().get(22))); + assertEquals( + "org.sonatype.gossip:gossip-core:${gossipVersion}", + gav(model.getDependencyManagement().getDependencies().get(35))); + // + // modules + // + assertEquals("maven-core", model.getModules().get(0)); + assertEquals("maven-settings-builder", model.getModules().get(4)); + assertEquals("maven-aether-provider", model.getModules().get(6)); + // + // plugins + // + Plugin p0 = model.getBuild().getPluginManagement().getPlugins().get(0); + assertEquals("org.codehaus.plexus:plexus-component-metadata:${plexusVersion}", gav(p0)); + assertNull(p0.getConfiguration()); - String gav(Dependency d) { - return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); - } + p0 = model.getBuild().getPluginManagement().getPlugins().get(1); + assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); + assertEquals("1.5", ((Xpp3Dom) p0.getConfiguration()).getChild("source").getValue()); + assertEquals("1.5", ((Xpp3Dom) p0.getConfiguration()).getChild("target").getValue()); + } - String gav(Plugin p) { - return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); - } + String gav(Dependency d) { + return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); + } + String gav(Plugin p) { + return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); + } } diff --git a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithSBTest.java b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithSBTest.java index ccc8834c..62db3c09 100644 --- a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithSBTest.java +++ b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/AtomModelWithSBTest.java @@ -12,10 +12,8 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -28,123 +26,137 @@ public class AtomModelWithSBTest extends InjectedTestCase { - @Inject - @Named("${basedir}/src/test/poms") - private File poms; - - public void testAtomModelWriter() throws Exception { - File pom = new File(poms, "sitebricks-parent-pom.xml"); - MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); - // - testMavenModelForCompleteness(xmlModel); - // - // Write out the Atom POM - // - ModelWriter writer = new AtomModelWriter(); - StringWriter w = new StringWriter(); - writer.write(w, new HashMap(), xmlModel); - - // Let's take a look at see what's there - System.out.println(w.toString()); - - // - // Read in the Atom POM - // - ModelReader atomModelReader = new AtomModelReader(); - StringReader r = new StringReader(w.toString()); - Model atomModel = atomModelReader.read(r, new HashMap()); - // - // Test for fidelity - // - assertNotNull(atomModel); - testMavenModelForCompleteness(atomModel); - - w = new StringWriter(); - MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); - xmlWriter.write(w, xmlModel); - System.out.println(w.toString()); - - assertEquals(xmlModel.getModules(), atomModel.getModules()); - assertEquals(xmlModel.getRepositories().size(), atomModel.getRepositories().size()); - } - - public void testAtomModelWriterWhereModelHasDependenciesWithNoVersions() throws Exception { - File pom = new File(poms, "sitebricks-pom.xml"); - MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); - - // - // Write out the Atom POM - // - ModelWriter writer = new AtomModelWriter(); - StringWriter w = new StringWriter(); - writer.write(w, new HashMap(), xmlModel); - - // Let's take a look at see what's there - System.out.println(w.toString()); - - // - // Read in the Atom POM - // - ModelReader atomModelReader = new AtomModelReader(); - StringReader r = new StringReader(w.toString()); - Model atomModel = atomModelReader.read(r, new HashMap()); - // - // Test for fidelity - // - assertNotNull(atomModel); - } - - void testMavenModelForCompleteness(Model model) { - // - // repos - // - assertEquals("http://scala-tools.org/repo-releases/", model.getRepositories().get(0).getUrl()); - // - // parent - // - assertEquals("com.google.sitebricks:sitebricks-parent:0.8.6-SNAPSHOT", model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); - // - // id - // -// assertEquals("org.sonatype.oss:oss-parent:6", model.getParent().getGroupId() + ":" + model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); - // - // properties - // -// assertEquals("pom", model.getPackaging()); - assertEquals("5.8", model.getProperties().getProperty("org.testng.version")); - assertEquals("6.1.9", model.getProperties().getProperty("org.mortbay.jetty.version")); - // - // depMan - // - assertEquals("com.google.sitebricks:sitebricks-converter:${project.version}", gav(model.getDependencyManagement().getDependencies().get(0))); - assertEquals("com.google.guava:guava:r09", gav(model.getDependencyManagement().getDependencies().get(5))); - assertEquals("org.freemarker:freemarker:2.3.10", gav(model.getDependencyManagement().getDependencies().get(12))); - assertEquals("saxpath:saxpath:1.0-FCS", gav(model.getDependencyManagement().getDependencies().get(22))); - Dependency testNg = model.getDependencyManagement().getDependencies().get(35); - assertEquals("org.testng:testng:${org.testng.version}", gav(testNg)); - assertEquals("jdk15", testNg.getClassifier()); - // - // modules - // - assertEquals("sitebricks", model.getModules().get(0)); - assertEquals("sitebricks-acceptance-tests", model.getModules().get(4)); - assertEquals("slf4j", model.getModules().get(9)); - // - // plugins - // - Plugin p0 = model.getBuild().getPlugins().get(0); - assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); - assertEquals("1.6", ((Xpp3Dom)p0.getConfiguration()).getChild("source").getValue()); - assertEquals("1.6", ((Xpp3Dom)p0.getConfiguration()).getChild("target").getValue()); - } - - String gav(Dependency d) { - return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); - } - - String gav(Plugin p) { - return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); - } + @Inject + @Named("${basedir}/src/test/poms") + private File poms; + + public void testAtomModelWriter() throws Exception { + File pom = new File(poms, "sitebricks-parent-pom.xml"); + MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + // + testMavenModelForCompleteness(xmlModel); + // + // Write out the Atom POM + // + ModelWriter writer = new AtomModelWriter(); + StringWriter w = new StringWriter(); + writer.write(w, new HashMap(), xmlModel); + + // Let's take a look at see what's there + System.out.println(w.toString()); + + // + // Read in the Atom POM + // + ModelReader atomModelReader = new AtomModelReader(); + StringReader r = new StringReader(w.toString()); + Model atomModel = atomModelReader.read(r, new HashMap()); + // + // Test for fidelity + // + assertNotNull(atomModel); + testMavenModelForCompleteness(atomModel); + + w = new StringWriter(); + MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); + xmlWriter.write(w, xmlModel); + System.out.println(w.toString()); + + assertEquals(xmlModel.getModules(), atomModel.getModules()); + assertEquals( + xmlModel.getRepositories().size(), atomModel.getRepositories().size()); + } + + public void testAtomModelWriterWhereModelHasDependenciesWithNoVersions() throws Exception { + File pom = new File(poms, "sitebricks-pom.xml"); + MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + + // + // Write out the Atom POM + // + ModelWriter writer = new AtomModelWriter(); + StringWriter w = new StringWriter(); + writer.write(w, new HashMap(), xmlModel); + + // Let's take a look at see what's there + System.out.println(w.toString()); + + // + // Read in the Atom POM + // + ModelReader atomModelReader = new AtomModelReader(); + StringReader r = new StringReader(w.toString()); + Model atomModel = atomModelReader.read(r, new HashMap()); + // + // Test for fidelity + // + assertNotNull(atomModel); + } + + void testMavenModelForCompleteness(Model model) { + // + // repos + // + assertEquals( + "http://scala-tools.org/repo-releases/", + model.getRepositories().get(0).getUrl()); + // + // parent + // + assertEquals( + "com.google.sitebricks:sitebricks-parent:0.8.6-SNAPSHOT", + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); + // + // id + // + // assertEquals("org.sonatype.oss:oss-parent:6", model.getParent().getGroupId() + ":" + + // model.getParent().getArtifactId() + ":" + model.getParent().getVersion()); + // + // properties + // + // assertEquals("pom", model.getPackaging()); + assertEquals("5.8", model.getProperties().getProperty("org.testng.version")); + assertEquals("6.1.9", model.getProperties().getProperty("org.mortbay.jetty.version")); + // + // depMan + // + assertEquals( + "com.google.sitebricks:sitebricks-converter:${project.version}", + gav(model.getDependencyManagement().getDependencies().get(0))); + assertEquals( + "com.google.guava:guava:r09", + gav(model.getDependencyManagement().getDependencies().get(5))); + assertEquals( + "org.freemarker:freemarker:2.3.10", + gav(model.getDependencyManagement().getDependencies().get(12))); + assertEquals( + "saxpath:saxpath:1.0-FCS", + gav(model.getDependencyManagement().getDependencies().get(22))); + Dependency testNg = model.getDependencyManagement().getDependencies().get(35); + assertEquals("org.testng:testng:${org.testng.version}", gav(testNg)); + assertEquals("jdk15", testNg.getClassifier()); + // + // modules + // + assertEquals("sitebricks", model.getModules().get(0)); + assertEquals("sitebricks-acceptance-tests", model.getModules().get(4)); + assertEquals("slf4j", model.getModules().get(9)); + // + // plugins + // + Plugin p0 = model.getBuild().getPlugins().get(0); + assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p0)); + assertEquals("1.6", ((Xpp3Dom) p0.getConfiguration()).getChild("source").getValue()); + assertEquals("1.6", ((Xpp3Dom) p0.getConfiguration()).getChild("target").getValue()); + } + + String gav(Dependency d) { + return d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion(); + } + + String gav(Plugin p) { + return p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(); + } } diff --git a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/parsing/AtomParserTest.java b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/parsing/AtomParserTest.java index 839e412c..2a911c9d 100644 --- a/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/parsing/AtomParserTest.java +++ b/polyglot-atom/src/test/java/org/sonatype/maven/polyglot/atom/parsing/AtomParserTest.java @@ -7,6 +7,8 @@ */ package org.sonatype.maven.polyglot.atom.parsing; +import java.net.MalformedURLException; +import java.util.List; import junit.framework.TestCase; import org.apache.maven.model.Plugin; import org.apache.maven.model.building.ModelSource; @@ -14,110 +16,109 @@ import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.Xpp3Dom; -import java.net.MalformedURLException; -import java.util.List; - /** * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class AtomParserTest extends TestCase { - private static final String REPO_URLS = "http://repository.codehaus.org," + - " http://maven.org/central, http://repo1.maven.org/maven2"; - - private String pom; - private ModelSource modelSource; - - @Override - protected void setUp() throws Exception { - this.pom = IOUtil.toString(AtomParserTest.class.getResourceAsStream("example_pom.atom")); - this.modelSource = new StringModelSource(pom); - } - - public final void testRepositoryLineMalformedUrls() { - Exception thrown = null; - try { - new AtomParser(modelSource, new Tokenizer("repositories << \"...\"\n").tokenize()).parse(); - fail("Expected exception for Malformed URL"); - } catch (RuntimeException e) { - thrown = e; - } - assertTrue(thrown.getCause() instanceof MalformedURLException); - } + private static final String REPO_URLS = + "http://repository.codehaus.org," + " http://maven.org/central, http://repo1.maven.org/maven2"; - public final void testRepositoryLineParsing() { - Project element = new AtomParser(modelSource, new Tokenizer(pom).tokenize()).parse(); + private String pom; + private ModelSource modelSource; - assertEquals(String.format("[%s]", REPO_URLS), element.getRepositories().toString()); - } + @Override + protected void setUp() throws Exception { + this.pom = IOUtil.toString(AtomParserTest.class.getResourceAsStream("example_pom.atom")); + this.modelSource = new StringModelSource(pom); + } - public final void testProjectParsing() { - Project project = new AtomParser(modelSource, new Tokenizer(pom).tokenize()).parse(); + public final void testRepositoryLineMalformedUrls() { + Exception thrown = null; + try { + new AtomParser(modelSource, new Tokenizer("repositories << \"...\"\n").tokenize()).parse(); + fail("Expected exception for Malformed URL"); + } catch (RuntimeException e) { + thrown = e; + } + assertTrue(thrown.getCause() instanceof MalformedURLException); + } - assertEquals("\"Google Guice\"", project.getDescription()); - assertEquals("\"http://code.google.com/p/google-guice\"", project.getUrl()); - assertEquals("jar", project.getPackaging()); + public final void testRepositoryLineParsing() { + Project element = new AtomParser(modelSource, new Tokenizer(pom).tokenize()).parse(); - assertEquals("com.google.inject", project.getProjectId().getGroup()); - assertEquals("guice", project.getProjectId().getArtifact()); - assertEquals("2.0-SNAPSHOT", project.getProjectId().getVersion()); + assertEquals(String.format("[%s]", REPO_URLS), element.getRepositories().toString()); + } - assertEquals(3, project.getDeps().size()); + public final void testProjectParsing() { + Project project = new AtomParser(modelSource, new Tokenizer(pom).tokenize()).parse(); - Id id = project.getDeps().get(0); - assertEquals("junit:junit:3.8.1", id.toString()); - id = project.getDeps().get(1); - assertEquals("junit:junit:4.0", id.toString()); - id = project.getDeps().get(2); - assertEquals("kunit:org.kunit:SNAPSHOT-1.0b", id.toString()); - assertEquals("jdk15", id.getClassifier()); + assertEquals("\"Google Guice\"", project.getDescription()); + assertEquals("\"http://code.google.com/p/google-guice\"", project.getUrl()); + assertEquals("jar", project.getPackaging()); - assertEquals(2, project.getDirs().size()); - assertEquals("src", project.getDirs().get("src")); - assertEquals("test", project.getDirs().get("test")); + assertEquals("com.google.inject", project.getProjectId().getGroup()); + assertEquals("guice", project.getProjectId().getArtifact()); + assertEquals("2.0-SNAPSHOT", project.getProjectId().getVersion()); + assertEquals(3, project.getDeps().size()); - assertEquals("\"url:git:git@github.com:mikebrock/mvel.git\"", project.getScm().getUrl()); - assertEquals("\"con:git:git@github.com:mikebrock/mvel.git\"", project.getScm().getConnection()); - assertEquals("\"dev:git:git@github.com:mikebrock/mvel.git\"", - project.getScm().getDeveloperConnection()); + Id id = project.getDeps().get(0); + assertEquals("junit:junit:3.8.1", id.toString()); + id = project.getDeps().get(1); + assertEquals("junit:junit:4.0", id.toString()); + id = project.getDeps().get(2); + assertEquals("kunit:org.kunit:SNAPSHOT-1.0b", id.toString()); + assertEquals("jdk15", id.getClassifier()); + assertEquals(2, project.getDirs().size()); + assertEquals("src", project.getDirs().get("src")); + assertEquals("test", project.getDirs().get("test")); - List plugins = project.getPlugins(); - assertNotNull(plugins); - assertEquals(2, plugins.size()); + assertEquals( + "\"url:git:git@github.com:mikebrock/mvel.git\"", + project.getScm().getUrl()); + assertEquals( + "\"con:git:git@github.com:mikebrock/mvel.git\"", + project.getScm().getConnection()); + assertEquals( + "\"dev:git:git@github.com:mikebrock/mvel.git\"", + project.getScm().getDeveloperConnection()); - Plugin compiler = plugins.get(0); - Plugin surefire = plugins.get(1); + List plugins = project.getPlugins(); + assertNotNull(plugins); + assertEquals(2, plugins.size()); - assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.0.1", compiler.getId()); - assertEquals("org.apache.maven.plugins:maven-surefire-plugin:2.0.1", surefire.getId()); + Plugin compiler = plugins.get(0); + Plugin surefire = plugins.get(1); - Xpp3Dom config = (Xpp3Dom) compiler.getConfiguration(); - assertTrue(containsChild(config, "source", "1.5")); - assertTrue(containsChild(config, "target", "1.5")); + assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.0.1", compiler.getId()); + assertEquals("org.apache.maven.plugins:maven-surefire-plugin:2.0.1", surefire.getId()); - config = (Xpp3Dom) surefire.getConfiguration(); - assertTrue(containsChild(config, "childDelegation", "true")); + Xpp3Dom config = (Xpp3Dom) compiler.getConfiguration(); + assertTrue(containsChild(config, "source", "1.5")); + assertTrue(containsChild(config, "target", "1.5")); - Xpp3Dom extra = config.getChild("extra"); - assertNotNull(extra); - assertEquals(2, extra.getChildCount()); + config = (Xpp3Dom) surefire.getConfiguration(); + assertTrue(containsChild(config, "childDelegation", "true")); - assertTrue(containsChild(extra, "useThings", "true")); + Xpp3Dom extra = config.getChild("extra"); + assertNotNull(extra); + assertEquals(2, extra.getChildCount()); - Xpp3Dom useOtherThings = extra.getChild("useOtherThings"); - assertNotNull(useOtherThings); - assertEquals(1, useOtherThings.getChildCount()); - assertTrue(containsChild(useOtherThings, "maybe", "false")); - } + assertTrue(containsChild(extra, "useThings", "true")); - private static boolean containsChild(Xpp3Dom node, String key, String value) { - for (Xpp3Dom child : node.getChildren()) { - if (key.equals(child.getName()) && value.equals(child.getValue())) - return true; + Xpp3Dom useOtherThings = extra.getChild("useOtherThings"); + assertNotNull(useOtherThings); + assertEquals(1, useOtherThings.getChildCount()); + assertTrue(containsChild(useOtherThings, "maybe", "false")); } - System.out.println("No such node - " + key + ": " + value); - return false; - } + private static boolean containsChild(Xpp3Dom node, String key, String value) { + for (Xpp3Dom child : node.getChildren()) { + if (key.equals(child.getName()) && value.equals(child.getValue())) return true; + } + + System.out.println("No such node - " + key + ": " + value); + return false; + } } diff --git a/polyglot-clojure/pom.xml b/polyglot-clojure/pom.xml index 6295b0dc..59766da1 100644 --- a/polyglot-clojure/pom.xml +++ b/polyglot-clojure/pom.xml @@ -22,7 +22,7 @@ takari-maven-component Polyglot :: Clojure - + io.takari.polyglot polyglot-common @@ -31,7 +31,7 @@ org.clojure clojure 1.11.2 - + org.easytesting fest-assert @@ -41,22 +41,6 @@ - - - com.theoryinpractise - clojure-maven-plugin - 1.9.2 - - - - compile - testCompile - test - - - - - @@ -87,6 +71,22 @@ + + + com.theoryinpractise + clojure-maven-plugin + 1.9.2 + + + + compile + testCompile + test + + + + + diff --git a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureMapping.java b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureMapping.java index df8a1b1c..a9ff9899 100644 --- a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureMapping.java +++ b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureMapping.java @@ -9,7 +9,6 @@ import javax.inject.Named; import javax.inject.Singleton; - import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -21,10 +20,8 @@ * @since 0.7 */ @Singleton -@Named( "clojure" ) -public class ClojureMapping - extends MappingSupport -{ +@Named("clojure") +public class ClojureMapping extends MappingSupport { public ClojureMapping() { super("clojure"); setPomNames("pom.clj", "projwct.clj"); @@ -32,4 +29,4 @@ public ClojureMapping() { setAcceptOptionKeys("clojure:4.0.0"); setPriority(1); } -} \ No newline at end of file +} diff --git a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelReader.java b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelReader.java index 156350bc..addd9ace 100644 --- a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelReader.java +++ b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelReader.java @@ -7,32 +7,30 @@ */ package org.sonatype.maven.polyglot.clojure; -import javax.inject.Named; -import javax.inject.Singleton; - import clojure.lang.Atom; import clojure.lang.Namespace; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; -import org.apache.maven.model.Model; -import org.sonatype.maven.polyglot.PolyglotModelUtil; -import org.sonatype.maven.polyglot.io.ModelReaderSupport; - import java.io.IOException; import java.io.Reader; import java.util.Map; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.model.Model; +import org.sonatype.maven.polyglot.PolyglotModelUtil; +import org.sonatype.maven.polyglot.io.ModelReaderSupport; /** * Reads a pom.clj and transforms into a Maven {@link Model}. * * @author Mark Derricutt * @author Antony Blakey - + * * @since 0.7 */ @Singleton -@Named( "clojure" ) +@Named("clojure") public class ClojureModelReader extends ModelReaderSupport { public Model read(final Reader input, final Map options) throws IOException { @@ -52,12 +50,12 @@ public Model read(final Reader input, final Map options) throws IOExc USE.invoke(LEININGEN); clojure.lang.Compiler.load(input, location, location); final Var MODEL = Var.intern(Namespace.findOrCreate(READER), Symbol.create("*MODEL*")); - return (Model) ((Atom) MODEL.get()).deref(); + return (Model) ((Atom) MODEL.get()).deref(); } catch (Exception e) { // Don't use new IOException(e) because it doesn't exist in Java 5 throw (IOException) new IOException(e.toString()).initCause(e); } finally { - currentThread.setContextClassLoader(originalCL); + currentThread.setContextClassLoader(originalCL); } } } diff --git a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriter.java b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriter.java index 12d30a29..d0b9df2c 100644 --- a/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriter.java +++ b/polyglot-clojure/src/main/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriter.java @@ -7,19 +7,17 @@ */ package org.sonatype.maven.polyglot.clojure; -import javax.inject.Named; -import javax.inject.Singleton; - import clojure.lang.Namespace; import clojure.lang.RT; import clojure.lang.Symbol; import clojure.lang.Var; -import org.apache.maven.model.Model; -import org.sonatype.maven.polyglot.io.ModelWriterSupport; - import java.io.IOException; import java.io.Writer; import java.util.Map; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.model.Model; +import org.sonatype.maven.polyglot.io.ModelWriterSupport; /** * Writes a Maven {@link org.apache.maven.model.Model} to a pom.clj. @@ -30,7 +28,7 @@ * @since 0.7 */ @Singleton -@Named( "clojure" ) +@Named("clojure") public class ClojureModelWriter extends ModelWriterSupport { public void write(Writer writer, Map stringObjectMap, Model model) throws IOException { @@ -46,5 +44,4 @@ public void write(Writer writer, Map stringObjectMap, Model mode throw (IOException) new IOException(e.toString()).initCause(e); } } - } diff --git a/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelReaderTest.java b/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelReaderTest.java index b74b3b4d..385a1dac 100644 --- a/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelReaderTest.java +++ b/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelReaderTest.java @@ -10,9 +10,7 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; @@ -25,8 +23,7 @@ * * @author Mark Derricutt */ -public class ClojureModelReaderTest extends TestCase -{ +public class ClojureModelReaderTest extends TestCase { @Test public void testReading() throws Exception { Model model = readClojureModel("test1.clj"); @@ -36,7 +33,7 @@ public void testReading() throws Exception { assertEquals("UTF-8", model.getModelEncoding()); assertEquals("jar", model.getPackaging()); -// assertEquals("4.0.0", model.getModelVersion()); + // assertEquals("4.0.0", model.getModelVersion()); assertEquals("a", model.getGroupId()); assertEquals("b", model.getArtifactId()); assertEquals("c", model.getVersion()); @@ -96,7 +93,7 @@ private Model readClojureModel(final String sourceFile) throws Exception { URL input = getClass().getResource(sourceFile); assertNotNull(input); - Map options = new HashMap(); + Map options = new HashMap(); options.put(ModelProcessor.SOURCE, input); return reader.read(input.openStream(), options); } diff --git a/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriterTest.java b/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriterTest.java index 847302ea..1340eec9 100644 --- a/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriterTest.java +++ b/polyglot-clojure/src/test/java/org/sonatype/maven/polyglot/clojure/ClojureModelWriterTest.java @@ -11,9 +11,7 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; - import junit.framework.TestCase; - import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelReader; @@ -24,9 +22,7 @@ * * @author Mark Derricutt */ -public class ClojureModelWriterTest - extends TestCase -{ +public class ClojureModelWriterTest extends TestCase { @Test public void testModelPrinting() throws Exception { Model model = readClojureModel("test1.clj"); @@ -47,7 +43,7 @@ private Model readClojureModel(final String sourceFile) throws Exception { URL input = getClass().getResource(sourceFile); assertNotNull(input); - Map options = new HashMap(); + Map options = new HashMap(); options.put(ModelProcessor.SOURCE, input); return reader.read(input.openStream(), options); } diff --git a/polyglot-common/pom.xml b/polyglot-common/pom.xml index 8b1a4c61..fc13d279 100644 --- a/polyglot-common/pom.xml +++ b/polyglot-common/pom.xml @@ -29,8 +29,8 @@ - src/main/resources-filtered true + src/main/resources-filtered diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/Constants.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/Constants.java index 17438aae..018935ff 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/Constants.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/Constants.java @@ -10,46 +10,45 @@ import java.io.IOException; import java.io.InputStream; import java.util.Properties; - import org.codehaus.plexus.util.IOUtil; public class Constants { - private static Properties polyglotProperties; - - static { - polyglotProperties = getPolyglotMavenProperties(); - } - - public static String getGroupId() { - return polyglotProperties.getProperty("groupId"); - } - - public static String getArtifactId(String postfix) { - return polyglotProperties.getProperty("prefix") + postfix; - } - - public static String getVersion() { - return polyglotProperties.getProperty("version"); - } - - public static String getGAV(String postfix) { - return getGroupId() + ":" + getArtifactId(postfix) + ":" + getVersion(); - } - - public static Properties getPolyglotMavenProperties() { - Properties properties = new Properties(); - InputStream resourceAsStream = null; - try { - resourceAsStream = Constants.class.getClassLoader().getResourceAsStream("maven-polyglot.properties"); - if (resourceAsStream != null) { - properties.load(resourceAsStream); - } - } catch (IOException e) { - System.err.println("Unable determine version from JAR file: " + e.getMessage()); - } finally { - IOUtil.close(resourceAsStream); + private static Properties polyglotProperties; + + static { + polyglotProperties = getPolyglotMavenProperties(); + } + + public static String getGroupId() { + return polyglotProperties.getProperty("groupId"); + } + + public static String getArtifactId(String postfix) { + return polyglotProperties.getProperty("prefix") + postfix; + } + + public static String getVersion() { + return polyglotProperties.getProperty("version"); + } + + public static String getGAV(String postfix) { + return getGroupId() + ":" + getArtifactId(postfix) + ":" + getVersion(); + } + + public static Properties getPolyglotMavenProperties() { + Properties properties = new Properties(); + InputStream resourceAsStream = null; + try { + resourceAsStream = Constants.class.getClassLoader().getResourceAsStream("maven-polyglot.properties"); + if (resourceAsStream != null) { + properties.load(resourceAsStream); + } + } catch (IOException e) { + System.err.println("Unable determine version from JAR file: " + e.getMessage()); + } finally { + IOUtil.close(resourceAsStream); + } + return properties; } - return properties; - } } diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelManager.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelManager.java index b970cd35..3201adca 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelManager.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelManager.java @@ -7,17 +7,15 @@ */ package org.sonatype.maven.polyglot; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Properties; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.ModelWriter; import org.slf4j.Logger; @@ -35,83 +33,84 @@ @Named public class PolyglotModelManager { - protected Logger log = LoggerFactory.getLogger( PolyglotModelManager.class ); - - @Inject - protected List mappings; - - public void addMapping(final Mapping mapping) { - assert mapping != null; - mappings.add(mapping); - } - - private static final Comparator DESCENDING_PRIORITY = Comparator.comparingDouble(Mapping::getPriority).reversed(); - - public List getSortedMappings() { - List sortedMappings = new ArrayList<>(mappings); - sortedMappings.sort(DESCENDING_PRIORITY); - return sortedMappings; - } - - public ModelReader getReaderFor(final Map options) { - for (Mapping mapping : getSortedMappings()) { - if (mapping.accept(options)) { - return mapping.getReader(); - } + protected Logger log = LoggerFactory.getLogger(PolyglotModelManager.class); + + @Inject + protected List mappings; + + public void addMapping(final Mapping mapping) { + assert mapping != null; + mappings.add(mapping); } - throw new RuntimeException("Unable to determine model input format; options=" + options); - } - - public Properties getEnhancementPropertiesFor(final Map options) { - for (Mapping mapping : getSortedMappings()) { - if (mapping.accept(options)) { - return mapping.getEnhancementProperties(options); - } + private static final Comparator DESCENDING_PRIORITY = + Comparator.comparingDouble(Mapping::getPriority).reversed(); + + public List getSortedMappings() { + List sortedMappings = new ArrayList<>(mappings); + sortedMappings.sort(DESCENDING_PRIORITY); + return sortedMappings; } - return null; - } - - public ModelWriter getWriterFor(final Map options) { - for (Mapping mapping : getSortedMappings()) { - if (mapping.accept(options)) { - return mapping.getWriter(); - } + + public ModelReader getReaderFor(final Map options) { + for (Mapping mapping : getSortedMappings()) { + if (mapping.accept(options)) { + return mapping.getReader(); + } + } + + throw new RuntimeException("Unable to determine model input format; options=" + options); } - throw new RuntimeException("Unable to determine model output format; options=" + options); - } + public Properties getEnhancementPropertiesFor(final Map options) { + for (Mapping mapping : getSortedMappings()) { + if (mapping.accept(options)) { + return mapping.getEnhancementProperties(options); + } + } + return null; + } - public File findPom(final File dir) { - assert dir != null; + public ModelWriter getWriterFor(final Map options) { + for (Mapping mapping : getSortedMappings()) { + if (mapping.accept(options)) { + return mapping.getWriter(); + } + } - for (Mapping mapping : getSortedMappings()) { - File file = mapping.locatePom(dir); - if (file != null) { - return file; - } + throw new RuntimeException("Unable to determine model output format; options=" + options); } - return null; - } - - public String determineFlavourFromPom(final File dir) { - assert dir != null; - for (Mapping mapping : getSortedMappings()) { - File file = mapping.locatePom(dir); - if (file != null) { - return mapping.getFlavour(); - } + + public File findPom(final File dir) { + assert dir != null; + + for (Mapping mapping : getSortedMappings()) { + File file = mapping.locatePom(dir); + if (file != null) { + return file; + } + } + return null; } - return null; - } - - public String getFlavourFor(final Map options) { - for (Mapping mapping : getSortedMappings()) { - if (mapping.accept(options)) { - return mapping.getFlavour(); - } + + public String determineFlavourFromPom(final File dir) { + assert dir != null; + for (Mapping mapping : getSortedMappings()) { + File file = mapping.locatePom(dir); + if (file != null) { + return mapping.getFlavour(); + } + } + return null; } - throw new RuntimeException("Unable determine model input format; options=" + options); - } + public String getFlavourFor(final Map options) { + for (Mapping mapping : getSortedMappings()) { + if (mapping.accept(options)) { + return mapping.getFlavour(); + } + } + + throw new RuntimeException("Unable determine model input format; options=" + options); + } } diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelUtil.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelUtil.java index 6715983e..3010c147 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelUtil.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotModelUtil.java @@ -7,12 +7,11 @@ */ package org.sonatype.maven.polyglot; -import org.apache.maven.model.building.ModelProcessor; -import org.apache.maven.model.building.ModelSource; - import java.io.File; import java.net.URL; import java.util.Map; +import org.apache.maven.model.building.ModelProcessor; +import org.apache.maven.model.building.ModelSource; /** * Support for models. @@ -21,45 +20,45 @@ * @since 0.7 */ public class PolyglotModelUtil { - /** - * Gets the location, as configured via the {@link ModelProcessor#SOURCE} key. - * - * Supports values of: - *

    - *
  • String - *
  • File - *
  • URL - *
  • ModelSource - *
- * - * @return The model location; or null. - */ - public static String getLocation(final Map options) { - if (options != null) { - Object tmp = options.get(ModelProcessor.SOURCE); - if (tmp instanceof String) { - return (String) tmp; - } else if (tmp instanceof URL) { - return ((URL) tmp).toExternalForm(); - } else if (tmp instanceof File) { - return ((File) tmp).getAbsolutePath(); - } else if (tmp instanceof ModelSource) { - return ((ModelSource) tmp).getLocation(); - } + /** + * Gets the location, as configured via the {@link ModelProcessor#SOURCE} key. + * + * Supports values of: + *
    + *
  • String + *
  • File + *
  • URL + *
  • ModelSource + *
+ * + * @return The model location; or null. + */ + public static String getLocation(final Map options) { + if (options != null) { + Object tmp = options.get(ModelProcessor.SOURCE); + if (tmp instanceof String) { + return (String) tmp; + } else if (tmp instanceof URL) { + return ((URL) tmp).toExternalForm(); + } else if (tmp instanceof File) { + return ((File) tmp).getAbsolutePath(); + } else if (tmp instanceof ModelSource) { + return ((ModelSource) tmp).getLocation(); + } + } + return null; } - return null; - } - public static File getLocationFile(final Map options) { - if (options != null) { - Object src = options.get(ModelProcessor.SOURCE); - if (src instanceof URL) { - return new File(((URL) src).getFile()); - } else if (src != null) { - ModelSource sm = (ModelSource) src; - return new File(sm.getLocation()); - } + public static File getLocationFile(final Map options) { + if (options != null) { + Object src = options.get(ModelProcessor.SOURCE); + if (src instanceof URL) { + return new File(((URL) src).getFile()); + } else if (src != null) { + ModelSource sm = (ModelSource) src; + return new File(sm.getLocation()); + } + } + return null; } - return null; - } -} \ No newline at end of file +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotPropertiesEnhancer.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotPropertiesEnhancer.java index 24cd3c32..7a3cac8f 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotPropertiesEnhancer.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/PolyglotPropertiesEnhancer.java @@ -21,45 +21,44 @@ import java.util.Properties; import java.util.function.Consumer; - import org.apache.maven.model.Model; public class PolyglotPropertiesEnhancer { - /** - * Enhances the model by overriding properties - * - * @param properties - * the overriding properties - * @param model - * the model to enhance - */ - public static void enhanceModel(Properties properties, Model model) { - if (properties == null || model == null) { - // nothing to do then... - return; - } - setModelProperty(model::setArtifactId, ARTIFACT_ID_PROPERTY, properties); - setModelProperty(model::setGroupId, GROUP_ID_PROPERTY, properties); - setModelProperty(model::setVersion, VERSION_PROPERTY, properties); - setModelProperty(model::setPackaging, PACKAGING_PROPERTY, properties); - setModelProperty(model::setUrl, URL_PROPERTY, properties); - setModelProperty(model::setDescription, DESCRIPTION_PROPERTY, properties); - setModelProperty(model::setName, NAME_PROPERTY, properties); - Properties modelProperties = new Properties(model.getProperties()); - for (String property : properties.stringPropertyNames()) { - if (property.startsWith(PROPERTY_PREFIX)) { - modelProperties.setProperty(property.substring(PROPERTY_PREFIX.length()), - properties.getProperty(property)); - } - } - model.setProperties(modelProperties); - } + /** + * Enhances the model by overriding properties + * + * @param properties + * the overriding properties + * @param model + * the model to enhance + */ + public static void enhanceModel(Properties properties, Model model) { + if (properties == null || model == null) { + // nothing to do then... + return; + } + setModelProperty(model::setArtifactId, ARTIFACT_ID_PROPERTY, properties); + setModelProperty(model::setGroupId, GROUP_ID_PROPERTY, properties); + setModelProperty(model::setVersion, VERSION_PROPERTY, properties); + setModelProperty(model::setPackaging, PACKAGING_PROPERTY, properties); + setModelProperty(model::setUrl, URL_PROPERTY, properties); + setModelProperty(model::setDescription, DESCRIPTION_PROPERTY, properties); + setModelProperty(model::setName, NAME_PROPERTY, properties); + Properties modelProperties = new Properties(model.getProperties()); + for (String property : properties.stringPropertyNames()) { + if (property.startsWith(PROPERTY_PREFIX)) { + modelProperties.setProperty( + property.substring(PROPERTY_PREFIX.length()), properties.getProperty(property)); + } + } + model.setProperties(modelProperties); + } - private static void setModelProperty(Consumer setter, String key, Properties properties) { - String property = properties.getProperty(key, ""); - if (!property.isEmpty()) { - setter.accept(property); - } - } + private static void setModelProperty(Consumer setter, String key, Properties properties) { + String property = properties.getProperty(key, ""); + if (!property.isEmpty()) { + setter.accept(property); + } + } } diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelProcessor.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelProcessor.java index a7a96bda..044d60da 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelProcessor.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelProcessor.java @@ -7,22 +7,17 @@ */ package org.sonatype.maven.polyglot; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.apache.maven.model.building.FileModelSource; import org.apache.maven.model.building.ModelProcessor; @@ -31,11 +26,10 @@ import org.apache.maven.model.io.ModelReader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; +import org.codehaus.plexus.util.ReaderFactory; import org.eclipse.sisu.Priority; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.codehaus.plexus.util.ReaderFactory; /** * Polyglot model processor. @@ -44,140 +38,140 @@ * * @since 0.7 */ -//@Component(role = ModelProcessor.class, hint = "tesla-polyglot") +// @Component(role = ModelProcessor.class, hint = "tesla-polyglot") @Singleton @Named @Priority(10) public class TeslaModelProcessor implements ModelProcessor { - private static final String DEFAULT_POM_FILE = "pom.xml"; - private static final String NEW_LINE = System.getProperty("line.separator"); - private static final String WARNING = "?>" + NEW_LINE + ""; - private static final String POM_FILE_PREFIX = ".polyglot."; - - @Inject - private PolyglotModelManager manager; - - private Logger log = LoggerFactory.getLogger( TeslaModelProcessor.class ); - - @Override - public File locatePom(final File dir) { - assert manager != null; - - File pomFile = manager.findPom(dir); - if (pomFile == null) { - return new File(dir, DEFAULT_POM_FILE); - } - if (pomFile.getName().equals(DEFAULT_POM_FILE) && pomFile.getParentFile().equals(dir)) { - // behave like proper maven in case there is no pom from manager - return pomFile; - } - File polyglotPomFile = new File(pomFile.getParentFile(), POM_FILE_PREFIX + pomFile.getName()); - try { - if (!polyglotPomFile.exists() && polyglotPomFile.createNewFile()) { - polyglotPomFile.deleteOnExit(); - } - } catch (IOException e) { - throw new RuntimeException("error creating empty file", e); + private static final String DEFAULT_POM_FILE = "pom.xml"; + private static final String NEW_LINE = System.getProperty("line.separator"); + private static final String WARNING = "?>" + NEW_LINE + ""; + private static final String POM_FILE_PREFIX = ".polyglot."; + + @Inject + private PolyglotModelManager manager; + + private Logger log = LoggerFactory.getLogger(TeslaModelProcessor.class); + + @Override + public File locatePom(final File dir) { + assert manager != null; + + File pomFile = manager.findPom(dir); + if (pomFile == null) { + return new File(dir, DEFAULT_POM_FILE); + } + if (pomFile.getName().equals(DEFAULT_POM_FILE) + && pomFile.getParentFile().equals(dir)) { + // behave like proper maven in case there is no pom from manager + return pomFile; + } + File polyglotPomFile = new File(pomFile.getParentFile(), POM_FILE_PREFIX + pomFile.getName()); + try { + if (!polyglotPomFile.exists() && polyglotPomFile.createNewFile()) { + polyglotPomFile.deleteOnExit(); + } + } catch (IOException e) { + throw new RuntimeException("error creating empty file", e); + } + return polyglotPomFile; } - return polyglotPomFile; - } - @Override - public Model read(final File input, final Map options) throws IOException, ModelParseException { - Model model; + @Override + public Model read(final File input, final Map options) throws IOException, ModelParseException { + Model model; - try (Reader reader = ReaderFactory.newXmlReader(input)) { - model = read(reader, options); - model.setPomFile(input); + try (Reader reader = ReaderFactory.newXmlReader(input)) { + model = read(reader, options); + model.setPomFile(input); + } + return model; } - return model; - } - @Override - public Model read(final InputStream input, final Map options) throws IOException, ModelParseException { - try (Reader reader = ReaderFactory.newXmlReader(input)) { - return read(reader, options); - } - } - - @Override - @SuppressWarnings({ - "unchecked", "rawtypes" - }) - public Model read(final Reader input, final Map options) throws IOException, ModelParseException { - assert manager != null; - Optional optionalPomXml = getPomXmlFile(options); - if (optionalPomXml.isPresent()) { - File pom = optionalPomXml.get(); - log.debug(pom.toString()); - File realPom = new File(pom.getPath().replaceFirst(Pattern.quote(POM_FILE_PREFIX), "")); - - ((Map) options).put(ModelProcessor.SOURCE, new FileModelSource(realPom)); - - ModelReader reader = manager.getReaderFor(options); - Model model = reader.read(realPom, options); - PolyglotPropertiesEnhancer.enhanceModel(manager.getEnhancementPropertiesFor(options), model); - MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); - StringWriter xml = new StringWriter(); - xmlWriter.write(xml, model); - - FileUtils.fileWrite(pom, xml.toString()); - - // dump pom if filename is given via the pom properties - String dump = model.getProperties().getProperty("polyglot.dump.pom"); - if (dump == null) { - // just nice to dump the pom.xml via commandline switch - dump = System.getProperty("polyglot.dump.pom"); - } - if (dump != null) { - File dumpPom = new File(pom.getParentFile(), dump); - if (!dumpPom.exists() || !FileUtils.fileRead(dumpPom).equals(xml.toString().replace("?>", WARNING))) { - dumpPom.setWritable(true); - FileUtils.fileWrite(dumpPom, xml.toString().replace("?>", WARNING)); - if ("true".equals(model.getProperties().getProperty("polyglot.dump.readonly"))) { - dumpPom.setReadOnly(); - } + @Override + public Model read(final InputStream input, final Map options) throws IOException, ModelParseException { + try (Reader reader = ReaderFactory.newXmlReader(input)) { + return read(reader, options); } - } + } - model.setPomFile(pom); - return model; - } else { - ModelReader reader = manager.getReaderFor(options); - return reader.read(input, options); + @Override + @SuppressWarnings({"unchecked", "rawtypes"}) + public Model read(final Reader input, final Map options) throws IOException, ModelParseException { + assert manager != null; + Optional optionalPomXml = getPomXmlFile(options); + if (optionalPomXml.isPresent()) { + File pom = optionalPomXml.get(); + log.debug(pom.toString()); + File realPom = new File(pom.getPath().replaceFirst(Pattern.quote(POM_FILE_PREFIX), "")); + + ((Map) options).put(ModelProcessor.SOURCE, new FileModelSource(realPom)); + + ModelReader reader = manager.getReaderFor(options); + Model model = reader.read(realPom, options); + PolyglotPropertiesEnhancer.enhanceModel(manager.getEnhancementPropertiesFor(options), model); + MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); + StringWriter xml = new StringWriter(); + xmlWriter.write(xml, model); + + FileUtils.fileWrite(pom, xml.toString()); + + // dump pom if filename is given via the pom properties + String dump = model.getProperties().getProperty("polyglot.dump.pom"); + if (dump == null) { + // just nice to dump the pom.xml via commandline switch + dump = System.getProperty("polyglot.dump.pom"); + } + if (dump != null) { + File dumpPom = new File(pom.getParentFile(), dump); + if (!dumpPom.exists() + || !FileUtils.fileRead(dumpPom).equals(xml.toString().replace("?>", WARNING))) { + dumpPom.setWritable(true); + FileUtils.fileWrite(dumpPom, xml.toString().replace("?>", WARNING)); + if ("true".equals(model.getProperties().getProperty("polyglot.dump.readonly"))) { + dumpPom.setReadOnly(); + } + } + } + + model.setPomFile(pom); + return model; + } else { + ModelReader reader = manager.getReaderFor(options); + return reader.read(input, options); + } } - } - private Optional getPomXmlFile(Map options) { - ModelSource source = (ModelSource) options.get(ModelProcessor.SOURCE); - if (source != null) { - return getPomXmlFile(new File(source.getLocation())); + private Optional getPomXmlFile(Map options) { + ModelSource source = (ModelSource) options.get(ModelProcessor.SOURCE); + if (source != null) { + return getPomXmlFile(new File(source.getLocation())); + } + return Optional.empty(); } - return Optional.empty(); - } - - Optional getPomXmlFile(File sourceFile) { - String filename = sourceFile.getName(); - if (filename.startsWith(POM_FILE_PREFIX)) { - return Optional.of(sourceFile); - } else if (!filename.equals("pom.xml") && !filename.endsWith(".pom")) { - File parent = sourceFile.getParentFile(); - if (parent == null) { - // "virtual" model - return Optional.empty(); - } - File pom = locatePom(parent); - if (pom.getName().startsWith(POM_FILE_PREFIX)) { - return Optional.of(pom); - } + + Optional getPomXmlFile(File sourceFile) { + String filename = sourceFile.getName(); + if (filename.startsWith(POM_FILE_PREFIX)) { + return Optional.of(sourceFile); + } else if (!filename.equals("pom.xml") && !filename.endsWith(".pom")) { + File parent = sourceFile.getParentFile(); + if (parent == null) { + // "virtual" model + return Optional.empty(); + } + File pom = locatePom(parent); + if (pom.getName().startsWith(POM_FILE_PREFIX)) { + return Optional.of(pom); + } + } + return Optional.empty(); } - return Optional.empty(); - } } diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelTranslator.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelTranslator.java index 4df864c0..bc0035a6 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelTranslator.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaModelTranslator.java @@ -7,18 +7,6 @@ */ package org.sonatype.maven.polyglot; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.apache.maven.model.Model; -import org.apache.maven.model.building.ModelProcessor; -import org.apache.maven.model.io.ModelParseException; -import org.apache.maven.model.io.ModelReader; -import org.apache.maven.model.io.ModelWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -30,6 +18,16 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import org.apache.maven.model.Model; +import org.apache.maven.model.building.ModelProcessor; +import org.apache.maven.model.io.ModelParseException; +import org.apache.maven.model.io.ModelReader; +import org.apache.maven.model.io.ModelWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Translates between polyglot model formats. @@ -42,96 +40,103 @@ @Named public class TeslaModelTranslator { - protected Logger log = LoggerFactory.getLogger( TeslaModelTranslator.class ); - - @Inject - private PolyglotModelManager manager; + protected Logger log = LoggerFactory.getLogger(TeslaModelTranslator.class); - public void translate(final File input, final File output) throws IOException, ModelParseException { - assert input != null; - assert output != null; + @Inject + private PolyglotModelManager manager; - Map inputOptions = new HashMap(); - inputOptions.put(ModelProcessor.SOURCE, input); + public void translate(final File input, final File output) throws IOException, ModelParseException { + assert input != null; + assert output != null; - Map outputOptions = new HashMap(); - outputOptions.put(ModelProcessor.SOURCE, output); + Map inputOptions = new HashMap(); + inputOptions.put(ModelProcessor.SOURCE, input); - translate(input, inputOptions, output, outputOptions); - } + Map outputOptions = new HashMap(); + outputOptions.put(ModelProcessor.SOURCE, output); - @SuppressWarnings({ - "unchecked" - }) - public void translate(final File input, final Map inputOptions, final File output, final Map outputOptions) throws IOException, ModelParseException { - assert input != null; - assert output != null; - - ModelReader reader = manager.getReaderFor(inputOptions); - Model model = reader.read(input, inputOptions); + translate(input, inputOptions, output, outputOptions); + } - ModelWriter writer = manager.getWriterFor(outputOptions); - writer.write(output, (Map) outputOptions, model); - } + @SuppressWarnings({"unchecked"}) + public void translate( + final File input, final Map inputOptions, final File output, final Map outputOptions) + throws IOException, ModelParseException { + assert input != null; + assert output != null; - public void translate(final URL input, final URL output) throws IOException, ModelParseException { - assert input != null; - assert output != null; + ModelReader reader = manager.getReaderFor(inputOptions); + Model model = reader.read(input, inputOptions); - Map inputOptions = new HashMap(); - inputOptions.put(ModelProcessor.SOURCE, input); + ModelWriter writer = manager.getWriterFor(outputOptions); + writer.write(output, (Map) outputOptions, model); + } - Map outputOptions = new HashMap(); - outputOptions.put(ModelProcessor.SOURCE, output); + public void translate(final URL input, final URL output) throws IOException, ModelParseException { + assert input != null; + assert output != null; - translate(input, inputOptions, output, outputOptions); - } + Map inputOptions = new HashMap(); + inputOptions.put(ModelProcessor.SOURCE, input); - public void translate(final URL input, final Map inputOptions, final URL output, final Map outputOptions) throws IOException, ModelParseException { - assert input != null; - assert output != null; + Map outputOptions = new HashMap(); + outputOptions.put(ModelProcessor.SOURCE, output); - OutputStream out; - if (output.getProtocol().equals("file")) { - File file = new File(output.getPath()); - out = new BufferedOutputStream(new FileOutputStream(file)); - } else { - out = output.openConnection().getOutputStream(); + translate(input, inputOptions, output, outputOptions); } - try { - translate(input.openStream(), inputOptions, out, outputOptions); - } finally { - out.flush(); + public void translate( + final URL input, final Map inputOptions, final URL output, final Map outputOptions) + throws IOException, ModelParseException { + assert input != null; + assert output != null; + + OutputStream out; + if (output.getProtocol().equals("file")) { + File file = new File(output.getPath()); + out = new BufferedOutputStream(new FileOutputStream(file)); + } else { + out = output.openConnection().getOutputStream(); + } + + try { + translate(input.openStream(), inputOptions, out, outputOptions); + } finally { + out.flush(); + } } - } - - @SuppressWarnings({ - "unchecked" - }) - public void translate(final InputStream input, final Map inputOptions, final OutputStream output, final Map outputOptions) throws IOException, ModelParseException { - assert input != null; - assert output != null; - - ModelReader reader = manager.getReaderFor(inputOptions); - Model model = reader.read(input, inputOptions); - - ModelWriter writer = manager.getWriterFor(outputOptions); - writer.write(output, (Map) outputOptions, model); - } - @SuppressWarnings({ - "unchecked" - }) - public void translate(final Reader input, final Map inputOptions, final Writer output, final Map outputOptions) throws IOException, ModelParseException { - assert input != null; - assert output != null; - - ModelReader reader = manager.getReaderFor(inputOptions); - Model model = reader.read(input, inputOptions); - - ModelWriter writer = manager.getWriterFor(outputOptions); - writer.write(output, (Map) outputOptions, model); - } + @SuppressWarnings({"unchecked"}) + public void translate( + final InputStream input, + final Map inputOptions, + final OutputStream output, + final Map outputOptions) + throws IOException, ModelParseException { + assert input != null; + assert output != null; + + ModelReader reader = manager.getReaderFor(inputOptions); + Model model = reader.read(input, inputOptions); + + ModelWriter writer = manager.getWriterFor(outputOptions); + writer.write(output, (Map) outputOptions, model); + } -} \ No newline at end of file + @SuppressWarnings({"unchecked"}) + public void translate( + final Reader input, + final Map inputOptions, + final Writer output, + final Map outputOptions) + throws IOException, ModelParseException { + assert input != null; + assert output != null; + + ModelReader reader = manager.getReaderFor(inputOptions); + Model model = reader.read(input, inputOptions); + + ModelWriter writer = manager.getWriterFor(outputOptions); + writer.write(output, (Map) outputOptions, model); + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaProjectBuilder.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaProjectBuilder.java index d2202075..73ebe4b8 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaProjectBuilder.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/TeslaProjectBuilder.java @@ -1,21 +1,19 @@ package org.sonatype.maven.polyglot; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +import static java.util.Objects.requireNonNull; import java.io.File; import java.util.List; import java.util.stream.Collectors; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.building.ModelProblem; import org.apache.maven.model.building.ModelSource; import org.apache.maven.project.*; import org.eclipse.sisu.Priority; -import static java.util.Objects.requireNonNull; - @Singleton @Named @Priority(10) @@ -37,22 +35,26 @@ public ProjectBuildingResult build(File pomFile, ProjectBuildingRequest request) } @Override - public ProjectBuildingResult build(ModelSource modelSource, ProjectBuildingRequest request) throws ProjectBuildingException { + public ProjectBuildingResult build(ModelSource modelSource, ProjectBuildingRequest request) + throws ProjectBuildingException { return convert(defaultProjectBuilder.build(modelSource, request)); } @Override - public ProjectBuildingResult build(Artifact artifact, ProjectBuildingRequest request) throws ProjectBuildingException { + public ProjectBuildingResult build(Artifact artifact, ProjectBuildingRequest request) + throws ProjectBuildingException { return convert(defaultProjectBuilder.build(artifact, request)); } @Override - public ProjectBuildingResult build(Artifact artifact, boolean allowStubModel, ProjectBuildingRequest request) throws ProjectBuildingException { + public ProjectBuildingResult build(Artifact artifact, boolean allowStubModel, ProjectBuildingRequest request) + throws ProjectBuildingException { return convert(defaultProjectBuilder.build(artifact, allowStubModel, request)); } @Override - public List build(List pomFiles, boolean recursive, ProjectBuildingRequest request) throws ProjectBuildingException { + public List build(List pomFiles, boolean recursive, ProjectBuildingRequest request) + throws ProjectBuildingException { List results = defaultProjectBuilder.build(pomFiles, recursive, request); return results.stream().map(this::convert).collect(Collectors.toList()); } @@ -81,11 +83,12 @@ private static class TeslaProjectBuildingResult implements ProjectBuildingResult private final List problems; private final DependencyResolutionResult dependencyResolutionResult; - public TeslaProjectBuildingResult(String projectId, - File pomFile, - MavenProject project, - List problems, - DependencyResolutionResult dependencyResolutionResult) { + public TeslaProjectBuildingResult( + String projectId, + File pomFile, + MavenProject project, + List problems, + DependencyResolutionResult dependencyResolutionResult) { this.projectId = projectId; this.pomFile = pomFile; this.project = project; diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/cli/TeslaTranslatorCli.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/cli/TeslaTranslatorCli.java index bfa6aa32..9c70cfef 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/cli/TeslaTranslatorCli.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/cli/TeslaTranslatorCli.java @@ -10,7 +10,6 @@ import java.io.File; import java.io.IOException; import java.net.URL; - import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; @@ -18,62 +17,63 @@ import org.sonatype.maven.polyglot.TeslaModelTranslator; public class TeslaTranslatorCli { - private final DefaultPlexusContainer container; - - private final TeslaModelTranslator translator; + private final DefaultPlexusContainer container; - public TeslaTranslatorCli(ClassWorld classWorld) throws Exception { - if (classWorld == null) { - classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader()); - } + private final TeslaModelTranslator translator; - ContainerConfiguration cc = new DefaultContainerConfiguration().setClassWorld(classWorld).setName("translator"); + public TeslaTranslatorCli(ClassWorld classWorld) throws Exception { + if (classWorld == null) { + classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader()); + } - container = new DefaultPlexusContainer(cc); - translator = container.lookup(TeslaModelTranslator.class); - } + ContainerConfiguration cc = + new DefaultContainerConfiguration().setClassWorld(classWorld).setName("translator"); - public TeslaTranslatorCli() throws Exception { - this(null); - } + container = new DefaultPlexusContainer(cc); + translator = container.lookup(TeslaModelTranslator.class); + } - public int run(final String[] args) throws Exception { - if (args == null || args.length != 2) { - System.out.println("usage: translate "); - return -1; + public TeslaTranslatorCli() throws Exception { + this(null); } - File input = new File(args[0]).getCanonicalFile(); - File output = new File(args[1]).getCanonicalFile(); + public int run(final String[] args) throws Exception { + if (args == null || args.length != 2) { + System.out.println("usage: translate "); + return -1; + } + + File input = new File(args[0]).getCanonicalFile(); + File output = new File(args[1]).getCanonicalFile(); - System.out.println("Translating " + input + " -> " + output); + System.out.println("Translating " + input + " -> " + output); - translate(input, output); + translate(input, output); - return 0; - } + return 0; + } - public void translate(final File input, final File output) throws IOException { - assert input != null; - assert output != null; + public void translate(final File input, final File output) throws IOException { + assert input != null; + assert output != null; - translate(input.toURI().toURL(), output.toURI().toURL()); - } + translate(input.toURI().toURL(), output.toURI().toURL()); + } - public void translate(final URL input, final URL output) throws IOException { - assert input != null; - assert output != null; + public void translate(final URL input, final URL output) throws IOException { + assert input != null; + assert output != null; - translator.translate(input, output); - } + translator.translate(input, output); + } - public static void main(final String[] args) throws Exception { - int result = main(args, null); - System.exit(result); - } + public static void main(final String[] args) throws Exception { + int result = main(args, null); + System.exit(result); + } - public static int main(final String[] args, final ClassWorld classWorld) throws Exception { - assert classWorld != null; - return new TeslaTranslatorCli(classWorld).run(args); - } -} \ No newline at end of file + public static int main(final String[] args, final ClassWorld classWorld) throws Exception { + assert classWorld != null; + return new TeslaTranslatorCli(classWorld).run(args); + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteContext.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteContext.java index 1bafa912..dab5c945 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteContext.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteContext.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.execute; import java.io.File; - import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; @@ -22,45 +21,45 @@ */ public interface ExecuteContext { - /** - * Returns the maven project. - */ - MavenProject getProject(); + /** + * Returns the maven project. + */ + MavenProject getProject(); - /** - * Returns the maven session. - */ - MavenSession getSession(); + /** + * Returns the maven session. + */ + MavenSession getSession(); - /** - * Returns the project base directory. - * - * @deprecated Use {@link #getBasedir()} instead - */ - @Deprecated - default File basedir() { - return getBasedir(); - } + /** + * Returns the project base directory. + * + * @deprecated Use {@link #getBasedir()} instead + */ + @Deprecated + default File basedir() { + return getBasedir(); + } - /** - * Returns the project base directory. - */ - default File getBasedir() { - return getProject().getBasedir(); - } + /** + * Returns the project base directory. + */ + default File getBasedir() { + return getProject().getBasedir(); + } - /** - * Returns the logger. - * - * @deprecated Use {@link #getLog()} instead - */ - @Deprecated - default Log log() { - return getLog(); - } + /** + * Returns the logger. + * + * @deprecated Use {@link #getLog()} instead + */ + @Deprecated + default Log log() { + return getLog(); + } - /** - * Returns the log. - */ - Log getLog(); -} \ No newline at end of file + /** + * Returns the log. + */ + Log getLog(); +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManager.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManager.java index eda724f7..e9f9beff 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManager.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManager.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.Map; - import org.apache.maven.model.Model; /** @@ -21,9 +20,9 @@ * @since 0.7 */ public interface ExecuteManager { - void register(Model model, List tasks); + void register(Model model, List tasks); - List getTasks(Model model); + List getTasks(Model model); - void install(Model model, Map options); -} \ No newline at end of file + void install(Model model, Map options); +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManagerImpl.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManagerImpl.java index a0984f49..9cebdfc7 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManagerImpl.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteManagerImpl.java @@ -7,16 +7,14 @@ */ package org.sonatype.maven.polyglot.execute; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Build; import org.apache.maven.model.BuildBase; import org.apache.maven.model.Dependency; @@ -41,177 +39,178 @@ @Named public class ExecuteManagerImpl implements ExecuteManager { - protected Logger log = LoggerFactory.getLogger( ExecuteManagerImpl.class ); + protected Logger log = LoggerFactory.getLogger(ExecuteManagerImpl.class); - @Inject - protected PolyglotModelManager manager; + @Inject + protected PolyglotModelManager manager; - private final Map> modelTasks = new HashMap<>(); + private final Map> modelTasks = new HashMap<>(); - @Override - public void register(final Model model, final List tasks) { - assert model != null; - assert tasks != null; + @Override + public void register(final Model model, final List tasks) { + assert model != null; + assert tasks != null; - // Need to copy the contents to avoid the elements - List copy = new ArrayList<>(tasks.size()); - copy.addAll(tasks); - modelTasks.put(model.getId(), Collections.unmodifiableList(copy)); - } + // Need to copy the contents to avoid the elements + List copy = new ArrayList<>(tasks.size()); + copy.addAll(tasks); + modelTasks.put(model.getId(), Collections.unmodifiableList(copy)); + } - @Override - public List getTasks(final Model model) { - assert model != null; + @Override + public List getTasks(final Model model) { + assert model != null; - List tasks = modelTasks.get(model.getId()); + List tasks = modelTasks.get(model.getId()); - // If we cannot find the model then look for the model where it has been registered with less - // specificity. - if (tasks == null) { - Model inheritingModel = new Model(); - inheritingModel.setArtifactId(model.getArtifactId()); - inheritingModel.setPackaging(model.getPackaging()); - inheritingModel.setVersion(model.getVersion()); - tasks = modelTasks.get(inheritingModel.getId()); - } - if (tasks == null) { - Model inheritingModel = new Model(); - inheritingModel.setArtifactId(model.getArtifactId()); - inheritingModel.setGroupId(model.getGroupId()); - inheritingModel.setPackaging(model.getPackaging()); - tasks = modelTasks.get(inheritingModel.getId()); - } - if (tasks == null) { - Model inheritingModel = new Model(); - inheritingModel.setArtifactId(model.getArtifactId()); - inheritingModel.setPackaging(model.getPackaging()); - tasks = modelTasks.get(inheritingModel.getId()); - } + // If we cannot find the model then look for the model where it has been registered with less + // specificity. + if (tasks == null) { + Model inheritingModel = new Model(); + inheritingModel.setArtifactId(model.getArtifactId()); + inheritingModel.setPackaging(model.getPackaging()); + inheritingModel.setVersion(model.getVersion()); + tasks = modelTasks.get(inheritingModel.getId()); + } + if (tasks == null) { + Model inheritingModel = new Model(); + inheritingModel.setArtifactId(model.getArtifactId()); + inheritingModel.setGroupId(model.getGroupId()); + inheritingModel.setPackaging(model.getPackaging()); + tasks = modelTasks.get(inheritingModel.getId()); + } + if (tasks == null) { + Model inheritingModel = new Model(); + inheritingModel.setArtifactId(model.getArtifactId()); + inheritingModel.setPackaging(model.getPackaging()); + tasks = modelTasks.get(inheritingModel.getId()); + } + + // Well, we've tried our hardest... + if (tasks == null) { + return Collections.emptyList(); + } - // Well, we've tried our hardest... - if (tasks == null) { - return Collections.emptyList(); + return tasks; } - return tasks; - } + @Override + public void install(final Model model, final Map options) { + assert model != null; - @Override - public void install(final Model model, final Map options) { - assert model != null; + List tasks = getTasks(model); + if (tasks.isEmpty()) { + return; + } - List tasks = getTasks(model); - if (tasks.isEmpty()) { - return; - } + if (log.isDebugEnabled()) { + log.debug("Registering tasks for: " + model.getId()); + } - if (log.isDebugEnabled()) { - log.debug("Registering tasks for: " + model.getId()); - } + List goals = Collections.singletonList("execute"); - List goals = Collections.singletonList("execute"); + Map plugins = new HashMap<>(); - Map plugins = new HashMap<>(); + for (ExecuteTask task : tasks) { + if (log.isDebugEnabled()) { + log.debug("Registering task: " + task.getId()); + } - for (ExecuteTask task : tasks) { - if (log.isDebugEnabled()) { - log.debug("Registering task: " + task.getId()); - } + Plugin plugin = getPlugin(model, task.getProfileId(), plugins); - Plugin plugin = getPlugin(model, task.getProfileId(), plugins); + String id = task.getId(); - String id = task.getId(); + PluginExecution execution = new PluginExecution(); + if (id != null && id.length() > 0) { + execution.setId(id); + } + execution.setPhase(task.getPhase()); + execution.setGoals(goals); - PluginExecution execution = new PluginExecution(); - if (id != null && id.length() > 0) { - execution.setId(id); - } - execution.setPhase(task.getPhase()); - execution.setGoals(goals); + Xpp3Dom config = new Xpp3Dom("configuration"); + execution.setConfiguration(config); - Xpp3Dom config = new Xpp3Dom("configuration"); - execution.setConfiguration(config); + if (id != null && id.length() > 0) { + Xpp3Dom child = new Xpp3Dom("taskId"); + child.setValue(id); + config.addChild(child); + } - if (id != null && id.length() > 0) { - Xpp3Dom child = new Xpp3Dom("taskId"); - child.setValue(id); - config.addChild(child); - } + if (model.getPomFile() != null) { + Xpp3Dom nativePom = new Xpp3Dom("nativePom"); + nativePom.setValue(model.getPomFile().getName()); + config.addChild(nativePom); + } - if (model.getPomFile() != null) { - Xpp3Dom nativePom = new Xpp3Dom("nativePom"); - nativePom.setValue(model.getPomFile().getName()); - config.addChild(nativePom); - } + plugin.addExecution(execution); + } - plugin.addExecution(execution); + String flavour = manager.getFlavourFor(options); + for (Plugin plugin : plugins.values()) { + Dependency dep = new Dependency(); + dep.setGroupId(Constants.getGroupId()); + dep.setArtifactId(Constants.getArtifactId(flavour)); + dep.setVersion(Constants.getVersion()); + plugin.addDependency(dep); + } } - String flavour = manager.getFlavourFor(options); - for (Plugin plugin : plugins.values()) { - Dependency dep = new Dependency(); - dep.setGroupId(Constants.getGroupId()); - dep.setArtifactId(Constants.getArtifactId(flavour)); - dep.setVersion(Constants.getVersion()); - plugin.addDependency(dep); - } - } - - private BuildBase getBuild(final Model model, String profileId) { - if (profileId == null) { - if (model.getBuild() == null) { - model.setBuild(new Build()); - } - return model.getBuild(); - } else { - for (Profile p : model.getProfiles()) { - if (profileId.equals(p.getId())) { - if (p.getBuild() == null) { - p.setBuild(new Build()); - } - return p.getBuild(); + private BuildBase getBuild(final Model model, String profileId) { + if (profileId == null) { + if (model.getBuild() == null) { + model.setBuild(new Build()); + } + return model.getBuild(); + } else { + for (Profile p : model.getProfiles()) { + if (profileId.equals(p.getId())) { + if (p.getBuild() == null) { + p.setBuild(new Build()); + } + return p.getBuild(); + } + } + Profile profile = new Profile(); + profile.setId(profileId); + profile.setBuild(new Build()); + model.addProfile(profile); + return profile.getBuild(); } - } - Profile profile = new Profile(); - profile.setId(profileId); - profile.setBuild(new Build()); - model.addProfile(profile); - return profile.getBuild(); } - } - - private Plugin getPlugin(final Model model, String profileId, Map plugins) { - Plugin plugin = plugins.get(profileId); - if (plugin == null) { - BuildBase build = getBuild(model, profileId); - List existingPlugins = build.getPlugins(); - - // Look up existing plugin entry if it exists - Plugin existing = existingPlugins.stream() - .filter(pl -> pl.getGroupId().equals(Constants.getGroupId())) - .filter(pl -> pl.getArtifactId().equals(Constants.getArtifactId("maven-plugin"))) - .findFirst() - .orElse(null); - - if (existing == null) { - plugin = new Plugin(); - plugin.setGroupId(Constants.getGroupId()); - plugin.setArtifactId(Constants.getArtifactId("maven-plugin")); - } else { - plugin = existing; - } - plugin.setVersion(Constants.getVersion()); // Force to use current version - plugin.setInherited(false); // Force inherited to false (inheritence of execute tasks is currently unsupported) - - if (existing == null) { - // Do not assume that the existing list is mutable. - List mutablePlugins = new ArrayList<>(existingPlugins); - build.setPlugins(mutablePlugins); - build.addPlugin(plugin); - } - - plugins.put(profileId, plugin); + + private Plugin getPlugin(final Model model, String profileId, Map plugins) { + Plugin plugin = plugins.get(profileId); + if (plugin == null) { + BuildBase build = getBuild(model, profileId); + List existingPlugins = build.getPlugins(); + + // Look up existing plugin entry if it exists + Plugin existing = existingPlugins.stream() + .filter(pl -> pl.getGroupId().equals(Constants.getGroupId())) + .filter(pl -> pl.getArtifactId().equals(Constants.getArtifactId("maven-plugin"))) + .findFirst() + .orElse(null); + + if (existing == null) { + plugin = new Plugin(); + plugin.setGroupId(Constants.getGroupId()); + plugin.setArtifactId(Constants.getArtifactId("maven-plugin")); + } else { + plugin = existing; + } + plugin.setVersion(Constants.getVersion()); // Force to use current version + plugin.setInherited( + false); // Force inherited to false (inheritence of execute tasks is currently unsupported) + + if (existing == null) { + // Do not assume that the existing list is mutable. + List mutablePlugins = new ArrayList<>(existingPlugins); + build.setPlugins(mutablePlugins); + build.addPlugin(plugin); + } + + plugins.put(profileId, plugin); + } + return plugin; } - return plugin; - } -} \ No newline at end of file +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTask.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTask.java index 0cab02d6..901f1926 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTask.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTask.java @@ -15,15 +15,15 @@ * @since 0.7 */ public interface ExecuteTask { - String getId(); + String getId(); - String getPhase(); + String getPhase(); - /** - * profile id of the execute task. can be null then the execute task belongs to - * project.build - */ - String getProfileId(); + /** + * profile id of the execute task. can be null then the execute task belongs to + * project.build + */ + String getProfileId(); - void execute(ExecuteContext context) throws Exception; -} \ No newline at end of file + void execute(ExecuteContext context) throws Exception; +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTaskSupport.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTaskSupport.java index e53c95ad..0a8a15df 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTaskSupport.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/execute/ExecuteTaskSupport.java @@ -15,33 +15,33 @@ * @since 0.7 */ public abstract class ExecuteTaskSupport implements ExecuteTask { - private String id; + private String id; - private String phase; + private String phase; - private String profileId = null; + private String profileId = null; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(final String id) { - this.id = id; - } + public void setId(final String id) { + this.id = id; + } - public String getPhase() { - return phase; - } + public String getPhase() { + return phase; + } - public void setPhase(final String phase) { - this.phase = phase; - } + public void setPhase(final String phase) { + this.phase = phase; + } - public String getProfileId() { - return profileId; - } + public String getProfileId() { + return profileId; + } - public void setProfileId(String profileId) { - this.profileId = profileId; - } -} \ No newline at end of file + public void setProfileId(String profileId) { + this.profileId = profileId; + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelReaderSupport.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelReaderSupport.java index ac87fe10..ba155915 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelReaderSupport.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelReaderSupport.java @@ -14,7 +14,6 @@ import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Map; - import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelReader; @@ -26,19 +25,19 @@ * @since 0.7 */ public abstract class ModelReaderSupport implements ModelReader { - public Model read(final File input, final Map options) throws IOException { - try (FileInputStream inputStream = new FileInputStream(input)) { - Model model = read(inputStream, options); - model.setPomFile(input); - return model; - } - } + public Model read(final File input, final Map options) throws IOException { + try (FileInputStream inputStream = new FileInputStream(input)) { + Model model = read(inputStream, options); + model.setPomFile(input); + return model; + } + } + + public Model read(final InputStream input, final Map options) throws IOException { + return read(new InputStreamReader(input, getCharset(options)), options); + } - public Model read(final InputStream input, final Map options) throws IOException { - return read(new InputStreamReader(input, getCharset(options)), options); - } - - protected Charset getCharset(Map options) { - return Charset.defaultCharset(); - } -} \ No newline at end of file + protected Charset getCharset(Map options) { + return Charset.defaultCharset(); + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelWriterSupport.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelWriterSupport.java index 77c3e075..f48605e9 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelWriterSupport.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/io/ModelWriterSupport.java @@ -7,10 +7,6 @@ */ package org.sonatype.maven.polyglot.io; -import org.apache.maven.model.Model; -import org.apache.maven.model.io.ModelWriter; -import org.codehaus.plexus.util.IOUtil; - import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -18,6 +14,9 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Map; +import org.apache.maven.model.Model; +import org.apache.maven.model.io.ModelWriter; +import org.codehaus.plexus.util.IOUtil; /** * Support for {@link ModelWriter} implementations. @@ -27,23 +26,24 @@ * @since 0.7 */ public abstract class ModelWriterSupport implements ModelWriter { - public void write(final File file, final Map options, final Model model) throws IOException { - assert file != null; - assert model != null; + public void write(final File file, final Map options, final Model model) throws IOException { + assert file != null; + assert model != null; - OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - try { - write(out, options, model); - out.flush(); - } finally { - IOUtil.close(out); + OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); + try { + write(out, options, model); + out.flush(); + } finally { + IOUtil.close(out); + } } - } - public void write(final OutputStream output, final Map options, final Model model) throws IOException { - assert output != null; - assert model != null; + public void write(final OutputStream output, final Map options, final Model model) + throws IOException { + assert output != null; + assert model != null; - write(new OutputStreamWriter(output), options, model); - } -} \ No newline at end of file + write(new OutputStreamWriter(output), options, model); + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/Mapping.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/Mapping.java index f313e50f..97957f1f 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/Mapping.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/Mapping.java @@ -7,12 +7,11 @@ */ package org.sonatype.maven.polyglot.mapping; -import org.apache.maven.model.io.ModelReader; -import org.apache.maven.model.io.ModelWriter; - import java.io.File; import java.util.Map; import java.util.Properties; +import org.apache.maven.model.io.ModelReader; +import org.apache.maven.model.io.ModelWriter; /** * Provides a mapping to polyglot specific models. @@ -22,69 +21,69 @@ * @since 0.7 */ public interface Mapping { - - public static final String NAME_PROPERTY = "pom.model.name"; - public static final String DESCRIPTION_PROPERTY = "pom.model.description"; - public static final String URL_PROPERTY = "pom.model.url"; - public static final String PACKAGING_PROPERTY = "pom.model.packaging"; - public static final String VERSION_PROPERTY = "pom.model.version"; - public static final String GROUP_ID_PROPERTY = "pom.model.groupId"; - public static final String ARTIFACT_ID_PROPERTY = "pom.model.artifactId"; - public static final String PROPERTY_PREFIX = "pom.model.property."; - - /** - * Locates the pom in the given directory - * @param dir the directory to locate the pom for - * @return the located pom or null if none was found by this mapping - */ - File locatePom(File dir); - /** - * Tests weather this mapping accepts the given option - * @param options the options to use - * @return true if options are accepted, false otherwise - */ - boolean accept(Map options); + public static final String NAME_PROPERTY = "pom.model.name"; + public static final String DESCRIPTION_PROPERTY = "pom.model.description"; + public static final String URL_PROPERTY = "pom.model.url"; + public static final String PACKAGING_PROPERTY = "pom.model.packaging"; + public static final String VERSION_PROPERTY = "pom.model.version"; + public static final String GROUP_ID_PROPERTY = "pom.model.groupId"; + public static final String ARTIFACT_ID_PROPERTY = "pom.model.artifactId"; + public static final String PROPERTY_PREFIX = "pom.model.property."; + + /** + * Locates the pom in the given directory + * @param dir the directory to locate the pom for + * @return the located pom or null if none was found by this mapping + */ + File locatePom(File dir); + + /** + * Tests weather this mapping accepts the given option + * @param options the options to use + * @return true if options are accepted, false otherwise + */ + boolean accept(Map options); - /** - * - * @return the {@link ModelReader} responsible for reading poms returned by the {@link #locatePom(File)} method - */ - ModelReader getReader(); + /** + * + * @return the {@link ModelReader} responsible for reading poms returned by the {@link #locatePom(File)} method + */ + ModelReader getReader(); - /** - * - * @return the {@link ModelWriter} responsible for writing poms returned by the {@link #locatePom(File)} method - */ - ModelWriter getWriter(); + /** + * + * @return the {@link ModelWriter} responsible for writing poms returned by the {@link #locatePom(File)} method + */ + ModelWriter getWriter(); - /** - * get the priority of this mapping, higher priorities are given precedence over those with lower priority, the default priority is 0 - * @return the priority - */ - float getPriority(); + /** + * get the priority of this mapping, higher priorities are given precedence over those with lower priority, the default priority is 0 + * @return the priority + */ + float getPriority(); - /** - * @return the flavor used to identify this mapping (e.g. xml, json, yaml, ...) - */ - String getFlavour(); + /** + * @return the flavor used to identify this mapping (e.g. xml, json, yaml, ...) + */ + String getFlavour(); - /** - * A properties object can enhance the returned polyglot model by e.g. a user defined file read by the mapping, supported keys are - *
    - *
  • {@link #ARTIFACT_ID_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #GROUP_ID_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #VERSION_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #PACKAGING_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #NAME_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #DESCRIPTION_PROPERTY}, empty property will be interpreted as not given
  • - *
  • {@link #URL_PROPERTY}, empty property will be interpreted as not given
  • - *
- * other keys are possible but will be silently ignored. - * If a property starts with {@link #PROPERTY_PREFIX} it will be interpreted as an enhancement to the properties of the model by removing the prefix and using its value as-is. - * @return a properties object that enhances the the generated model (e.g. by a user provided file) or null if no properties exits - */ - default Properties getEnhancementProperties(Map options) { - return null; - } -} \ No newline at end of file + /** + * A properties object can enhance the returned polyglot model by e.g. a user defined file read by the mapping, supported keys are + *
    + *
  • {@link #ARTIFACT_ID_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #GROUP_ID_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #VERSION_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #PACKAGING_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #NAME_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #DESCRIPTION_PROPERTY}, empty property will be interpreted as not given
  • + *
  • {@link #URL_PROPERTY}, empty property will be interpreted as not given
  • + *
+ * other keys are possible but will be silently ignored. + * If a property starts with {@link #PROPERTY_PREFIX} it will be interpreted as an enhancement to the properties of the model by removing the prefix and using its value as-is. + * @return a properties object that enhances the the generated model (e.g. by a user provided file) or null if no properties exits + */ + default Properties getEnhancementProperties(Map options) { + return null; + } +} diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/MappingSupport.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/MappingSupport.java index 56700f81..3bf84f0f 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/MappingSupport.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/MappingSupport.java @@ -7,8 +7,10 @@ */ package org.sonatype.maven.polyglot.mapping; +import java.io.File; +import java.net.URL; +import java.util.Map; import javax.inject.Inject; - import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.building.ModelSource; import org.apache.maven.model.io.ModelReader; @@ -16,10 +18,6 @@ import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import java.io.File; -import java.net.URL; -import java.util.Map; - /** * Support for {@link Mapping} implementations. * @@ -28,136 +26,136 @@ * @since 0.7 */ public abstract class MappingSupport implements Mapping { - private static final String[] EMPTY = {}; + private static final String[] EMPTY = {}; - private String roleHint; + private String roleHint; - private String[] pomNames = EMPTY; + private String[] pomNames = EMPTY; - private String[] acceptOptionKeys = EMPTY; + private String[] acceptOptionKeys = EMPTY; - private String[] acceptLocationExtensions = EMPTY; + private String[] acceptLocationExtensions = EMPTY; - private float priority; + private float priority; - @Inject - private PlexusContainer container; + @Inject + private PlexusContainer container; - private ModelReader reader; + private ModelReader reader; - private ModelWriter writer; + private ModelWriter writer; - protected MappingSupport(final String roleHint) { - this.roleHint = roleHint == null ? "default" : roleHint; - } - - public String getFlavour() { - return roleHint; - } - - public ModelReader getReader() { - if (reader == null) { - try { - assert container != null; - reader = container.lookup(ModelReader.class, roleHint); - } catch (ComponentLookupException e) { - throw new RuntimeException(e); - } + protected MappingSupport(final String roleHint) { + this.roleHint = roleHint == null ? "default" : roleHint; } - return reader; - } - - public ModelWriter getWriter() { - if (writer == null) { - try { - assert container != null; - writer = container.lookup(ModelWriter.class, roleHint); - } catch (ComponentLookupException e) { - throw new RuntimeException(e); - } + + public String getFlavour() { + return roleHint; } - return writer; - } - public String[] getAcceptLocationExtensions() { - return acceptLocationExtensions; - } + public ModelReader getReader() { + if (reader == null) { + try { + assert container != null; + reader = container.lookup(ModelReader.class, roleHint); + } catch (ComponentLookupException e) { + throw new RuntimeException(e); + } + } + return reader; + } - public void setAcceptLocationExtensions(final String... accept) { - this.acceptLocationExtensions = accept; - } + public ModelWriter getWriter() { + if (writer == null) { + try { + assert container != null; + writer = container.lookup(ModelWriter.class, roleHint); + } catch (ComponentLookupException e) { + throw new RuntimeException(e); + } + } + return writer; + } - public String[] getAcceptOptionKeys() { - return acceptOptionKeys; - } + public String[] getAcceptLocationExtensions() { + return acceptLocationExtensions; + } - public void setAcceptOptionKeys(final String... accept) { - this.acceptOptionKeys = accept; - } + public void setAcceptLocationExtensions(final String... accept) { + this.acceptLocationExtensions = accept; + } - public String[] getPomNames() { - return pomNames; - } + public String[] getAcceptOptionKeys() { + return acceptOptionKeys; + } - public void setPomNames(final String... names) { - this.pomNames = names; - } + public void setAcceptOptionKeys(final String... accept) { + this.acceptOptionKeys = accept; + } - public File locatePom(final File dir) { - assert dir != null; + public String[] getPomNames() { + return pomNames; + } - for (String name : getPomNames()) { - File file = new File(dir, name); - if (file.exists()) { - return file; - } + public void setPomNames(final String... names) { + this.pomNames = names; } - return null; - } + public File locatePom(final File dir) { + assert dir != null; - public boolean accept(final Map options) { - if (options != null) { - for (String key : getAcceptOptionKeys()) { - if (options.containsKey(key)) { - return true; + for (String name : getPomNames()) { + File file = new File(dir, name); + if (file.exists()) { + return file; + } } - } - - String location = getLocation(options); - if (location != null) { - for (String ext : getAcceptLocationExtensions()) { - if (location.endsWith(ext)) { - return true; - } + + return null; + } + + public boolean accept(final Map options) { + if (options != null) { + for (String key : getAcceptOptionKeys()) { + if (options.containsKey(key)) { + return true; + } + } + + String location = getLocation(options); + if (location != null) { + for (String ext : getAcceptLocationExtensions()) { + if (location.endsWith(ext)) { + return true; + } + } + } } - } + + return false; + } + + public float getPriority() { + return priority; } - return false; - } - - public float getPriority() { - return priority; - } - - protected void setPriority(float priority) { - this.priority = priority; - } - - public String getLocation(final Map options) { - if (options != null) { - Object tmp = options.get(ModelProcessor.SOURCE); - if (tmp instanceof String) { - return (String) tmp; - } else if (tmp instanceof URL) { - return ((URL) tmp).toExternalForm(); - } else if (tmp instanceof File) { - return ((File) tmp).getAbsolutePath(); - } else if (tmp instanceof ModelSource) { - return ((ModelSource) tmp).getLocation(); - } + protected void setPriority(float priority) { + this.priority = priority; + } + + public String getLocation(final Map options) { + if (options != null) { + Object tmp = options.get(ModelProcessor.SOURCE); + if (tmp instanceof String) { + return (String) tmp; + } else if (tmp instanceof URL) { + return ((URL) tmp).toExternalForm(); + } else if (tmp instanceof File) { + return ((File) tmp).getAbsolutePath(); + } else if (tmp instanceof ModelSource) { + return ((ModelSource) tmp).getLocation(); + } + } + return null; } - return null; - } } diff --git a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/XmlMapping.java b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/XmlMapping.java index 1760e425..358c86e4 100644 --- a/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/XmlMapping.java +++ b/polyglot-common/src/main/java/org/sonatype/maven/polyglot/mapping/XmlMapping.java @@ -7,11 +7,9 @@ */ package org.sonatype.maven.polyglot.mapping; +import java.util.Map; import javax.inject.Named; import javax.inject.Singleton; - -import java.util.Map; - import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.building.StringModelSource; @@ -23,21 +21,21 @@ * @since 0.7 */ @Singleton -@Named( "xml" ) +@Named("xml") public class XmlMapping extends MappingSupport { - public XmlMapping() { - super(null); - setPomNames("pom.xml"); - setAcceptLocationExtensions(".xml", ".pom"); - setAcceptOptionKeys("xml:4.0.0"); - } + public XmlMapping() { + super(null); + setPomNames("pom.xml"); + setAcceptLocationExtensions(".xml", ".pom"); + setAcceptOptionKeys("xml:4.0.0"); + } - @Override - public boolean accept(Map options) { - // assume StringModelSource is default maven, i.e. xml - if (options != null && options.get(ModelProcessor.SOURCE) instanceof StringModelSource) { - return true; + @Override + public boolean accept(Map options) { + // assume StringModelSource is default maven, i.e. xml + if (options != null && options.get(ModelProcessor.SOURCE) instanceof StringModelSource) { + return true; + } + return super.accept(options); } - return super.accept(options); - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/Dom2Groovy.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/Dom2Groovy.java index 25cafcb8..5ff53ba3 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/Dom2Groovy.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/Dom2Groovy.java @@ -8,6 +8,14 @@ package org.sonatype.maven.polyglot.groovy; import groovy.util.IndentPrinter; +import java.io.PrintWriter; +import java.io.Reader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; @@ -19,15 +27,6 @@ import org.w3c.dom.Text; import org.xml.sax.InputSource; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.PrintWriter; -import java.io.Reader; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - // // NOTE: Augmented from Groovy's DomToGroovy. // @@ -42,325 +41,376 @@ * @since 0.7 */ public class Dom2Groovy { - // FIXME: Re-extend from DomToGroovy once version us is released - - // FIXME: Need the full list, look at Types for hints on how to generate a full list - protected final List keywords = Arrays.asList("class", "extends", "implements", "package", "return", "def", "try", "finally", "this", "new", "catch", "switch", "case", "default", "while", - "if", "else", "elseif", "private", "protected", "final", "for", "in", "byte", "short", "break", "instanceof", "synchronized", "const", "float", "null", "throws", "do", "super", "with", - "threadsafe", "transient", "native", "interface", "any", "double", "volatile", "as", "assert", "goto", "enum", "int", "boolean", "char", "false", "true", "static", "abstract", "continue", - "import", "void", "long"); - - protected final IndentPrinter out; - - protected boolean inMixed = false; - - // FIXME: Do not quote things like 'true', 'false' or numbers - protected String qt = "'"; - - public Dom2Groovy(final PrintWriter out) { - this(new IndentPrinter(out)); - } - - public Dom2Groovy(final IndentPrinter out) { - assert out != null; - this.out = out; - } - - public void print(final Document document) { - printChildren(document, new HashMap()); - } - - public void print(final Reader input) throws Exception { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.parse(new InputSource(input)); - print(doc); - } - - protected void print(final Node node, final Map namespaces, final boolean endWithComma) { - switch (node.getNodeType()) { - case Node.ELEMENT_NODE: - printElement((Element) node, namespaces, endWithComma); - break; - case Node.PROCESSING_INSTRUCTION_NODE: - printPI((ProcessingInstruction) node, endWithComma); - break; - case Node.TEXT_NODE: - printText((Text) node, endWithComma); - break; - case Node.COMMENT_NODE: - printComment((Comment) node, endWithComma); - break; + // FIXME: Re-extend from DomToGroovy once version us is released + + // FIXME: Need the full list, look at Types for hints on how to generate a full list + protected final List keywords = Arrays.asList( + "class", + "extends", + "implements", + "package", + "return", + "def", + "try", + "finally", + "this", + "new", + "catch", + "switch", + "case", + "default", + "while", + "if", + "else", + "elseif", + "private", + "protected", + "final", + "for", + "in", + "byte", + "short", + "break", + "instanceof", + "synchronized", + "const", + "float", + "null", + "throws", + "do", + "super", + "with", + "threadsafe", + "transient", + "native", + "interface", + "any", + "double", + "volatile", + "as", + "assert", + "goto", + "enum", + "int", + "boolean", + "char", + "false", + "true", + "static", + "abstract", + "continue", + "import", + "void", + "long"); + + protected final IndentPrinter out; + + protected boolean inMixed = false; + + // FIXME: Do not quote things like 'true', 'false' or numbers + protected String qt = "'"; + + public Dom2Groovy(final PrintWriter out) { + this(new IndentPrinter(out)); } - } - - protected void printElement(final Element element, Map namespaces, final boolean endWithComma) { - namespaces = defineNamespaces(element, namespaces); - - element.normalize(); - printIndent(); - - String prefix = element.getPrefix(); - boolean hasPrefix = prefix != null && prefix.length() > 0; - String localName = getLocalName(element); - boolean isKeyword = checkEscaping(localName); - if (isKeyword || hasPrefix) - print(qt); - if (hasPrefix) { - print(prefix); - print("."); + + public Dom2Groovy(final IndentPrinter out) { + assert out != null; + this.out = out; + } + + public void print(final Document document) { + printChildren(document, new HashMap()); + } + + public void print(final Reader input) throws Exception { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.parse(new InputSource(input)); + print(doc); } - print(localName); - if (isKeyword || hasPrefix) - print(qt); - - boolean hasAttributes = printAttributes(element); - - // - // FIXME: Allow omitting () from empty attributes... needs some more work, - // move back to DomToGroovy once sorted - // - - NodeList list = element.getChildNodes(); - int length = list.getLength(); - if (length == 0) { - // empty xml translates to groovy 'element {}' - printEnd(" {}", endWithComma); - } else { - print(" "); - Node node = list.item(0); - if (length == 1 && node instanceof Text) { - Text textNode = (Text) node; - String text = getTextNodeData(textNode); - if (hasAttributes) - print(", "); - printQuoted(text); - printEnd("", endWithComma); - } else if (mixedContent(list)) { - println("{"); - out.incrementIndent(); - boolean oldInMixed = inMixed; - inMixed = true; - for (node = element.getFirstChild(); node != null; node = node.getNextSibling()) { - print(node, namespaces, false); + + protected void print(final Node node, final Map namespaces, final boolean endWithComma) { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE: + printElement((Element) node, namespaces, endWithComma); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + printPI((ProcessingInstruction) node, endWithComma); + break; + case Node.TEXT_NODE: + printText((Text) node, endWithComma); + break; + case Node.COMMENT_NODE: + printComment((Comment) node, endWithComma); + break; } - inMixed = oldInMixed; - out.decrementIndent(); + } + + protected void printElement(final Element element, Map namespaces, final boolean endWithComma) { + namespaces = defineNamespaces(element, namespaces); + + element.normalize(); printIndent(); - printEnd("}", endWithComma); - } else { - println("{"); - out.incrementIndent(); - printChildren(element, namespaces); - out.decrementIndent(); + + String prefix = element.getPrefix(); + boolean hasPrefix = prefix != null && prefix.length() > 0; + String localName = getLocalName(element); + boolean isKeyword = checkEscaping(localName); + if (isKeyword || hasPrefix) print(qt); + if (hasPrefix) { + print(prefix); + print("."); + } + print(localName); + if (isKeyword || hasPrefix) print(qt); + + boolean hasAttributes = printAttributes(element); + + // + // FIXME: Allow omitting () from empty attributes... needs some more work, + // move back to DomToGroovy once sorted + // + + NodeList list = element.getChildNodes(); + int length = list.getLength(); + if (length == 0) { + // empty xml translates to groovy 'element {}' + printEnd(" {}", endWithComma); + } else { + print(" "); + Node node = list.item(0); + if (length == 1 && node instanceof Text) { + Text textNode = (Text) node; + String text = getTextNodeData(textNode); + if (hasAttributes) print(", "); + printQuoted(text); + printEnd("", endWithComma); + } else if (mixedContent(list)) { + println("{"); + out.incrementIndent(); + boolean oldInMixed = inMixed; + inMixed = true; + for (node = element.getFirstChild(); node != null; node = node.getNextSibling()) { + print(node, namespaces, false); + } + inMixed = oldInMixed; + out.decrementIndent(); + printIndent(); + printEnd("}", endWithComma); + } else { + println("{"); + out.incrementIndent(); + printChildren(element, namespaces); + out.decrementIndent(); + printIndent(); + printEnd("}", endWithComma); + } + } + } + + protected void printQuoted(final String text) { + if (text.contains("\n")) { + print("'''"); + print(text); + print("'''"); + } else { + print(qt); + print(escapeQuote(text)); + print(qt); + } + } + + protected void printPI(final ProcessingInstruction instruction, final boolean endWithComma) { printIndent(); - printEnd("}", endWithComma); - } + print("mkp.pi(" + qt); + print(instruction.getTarget()); + print(qt + ", " + qt); + print(instruction.getData()); + printEnd(qt + ");", endWithComma); } - } - - protected void printQuoted(final String text) { - if (text.contains("\n")) { - print("'''"); - print(text); - print("'''"); - } else { - print(qt); - print(escapeQuote(text)); - print(qt); + + protected void printComment(final Comment comment, final boolean endWithComma) { + String text = comment.getData().trim(); + if (text.length() > 0) { + printIndent(); + print("/* "); + print(text); + printEnd(" */", endWithComma); + } } - } - - protected void printPI(final ProcessingInstruction instruction, final boolean endWithComma) { - printIndent(); - print("mkp.pi(" + qt); - print(instruction.getTarget()); - print(qt + ", " + qt); - print(instruction.getData()); - printEnd(qt + ");", endWithComma); - } - - protected void printComment(final Comment comment, final boolean endWithComma) { - String text = comment.getData().trim(); - if (text.length() > 0) { - printIndent(); - print("/* "); - print(text); - printEnd(" */", endWithComma); + + protected void printText(final Text node, final boolean endWithComma) { + String text = getTextNodeData(node); + if (text.length() > 0) { + printIndent(); + if (inMixed) print("mkp.yield "); + printQuoted(text); + printEnd("", endWithComma); + } } - } - - protected void printText(final Text node, final boolean endWithComma) { - String text = getTextNodeData(node); - if (text.length() > 0) { - printIndent(); - if (inMixed) - print("mkp.yield "); - printQuoted(text); - printEnd("", endWithComma); + + protected String escapeQuote(final String text) { + return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt); } - } - - protected String escapeQuote(final String text) { - return text.replaceAll("\\\\", "\\\\\\\\").replaceAll(qt, "\\\\" + qt); - } - - protected Map defineNamespaces(final Element element, final Map namespaces) { - Map answer = null; - String prefix = element.getPrefix(); - if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { - answer = new HashMap(namespaces); - defineNamespace(answer, prefix, element.getNamespaceURI()); + + protected Map defineNamespaces(final Element element, final Map namespaces) { + Map answer = null; + String prefix = element.getPrefix(); + if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { + answer = new HashMap(namespaces); + defineNamespace(answer, prefix, element.getNamespaceURI()); + } + NamedNodeMap attributes = element.getAttributes(); + int length = attributes.getLength(); + for (int i = 0; i < length; i++) { + Attr attribute = (Attr) attributes.item(i); + prefix = attribute.getPrefix(); + if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { + if (answer == null) { + answer = new HashMap(namespaces); + } + defineNamespace(answer, prefix, attribute.getNamespaceURI()); + } + } + return (answer != null) ? answer : namespaces; } - NamedNodeMap attributes = element.getAttributes(); - int length = attributes.getLength(); - for (int i = 0; i < length; i++) { - Attr attribute = (Attr) attributes.item(i); - prefix = attribute.getPrefix(); - if (prefix != null && prefix.length() > 0 && !namespaces.containsKey(prefix)) { - if (answer == null) { - answer = new HashMap(namespaces); + + protected void defineNamespace(final Map namespaces, final String prefix, final String uri) { + namespaces.put(prefix, uri); + if (!prefix.equals("xmlns") && !prefix.equals("xml")) { + printIndent(); + print("mkp.declareNamespace("); + print(prefix); + print(":" + qt); + print(uri); + println(qt + ")"); } - defineNamespace(answer, prefix, attribute.getNamespaceURI()); - } } - return (answer != null) ? answer : namespaces; - } - - protected void defineNamespace(final Map namespaces, final String prefix, final String uri) { - namespaces.put(prefix, uri); - if (!prefix.equals("xmlns") && !prefix.equals("xml")) { - printIndent(); - print("mkp.declareNamespace("); - print(prefix); - print(":" + qt); - print(uri); - println(qt + ")"); + + protected boolean printAttributes(final Element element) { + boolean hasAttribute = false; + NamedNodeMap attributes = element.getAttributes(); + int length = attributes.getLength(); + if (length > 0) { + print("("); + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < length; i++) { + printAttributeWithPrefix((Attr) attributes.item(i), buffer); + } + for (int i = 0; i < length; i++) { + hasAttribute = printAttributeWithoutPrefix((Attr) attributes.item(i), hasAttribute); + } + if (buffer.length() > 0) { + if (hasAttribute) { + print(", "); + } + print(buffer.toString()); + hasAttribute = true; + } + print(")"); + } + return hasAttribute; } - } - - protected boolean printAttributes(final Element element) { - boolean hasAttribute = false; - NamedNodeMap attributes = element.getAttributes(); - int length = attributes.getLength(); - if (length > 0) { - print("("); - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < length; i++) { - printAttributeWithPrefix((Attr) attributes.item(i), buffer); - } - for (int i = 0; i < length; i++) { - hasAttribute = printAttributeWithoutPrefix((Attr) attributes.item(i), hasAttribute); - } - if (buffer.length() > 0) { - if (hasAttribute) { - print(", "); + + protected void printAttributeWithPrefix(final Attr attribute, final StringBuffer buffer) { + String prefix = attribute.getPrefix(); + if (prefix != null && prefix.length() > 0 && !prefix.equals("xmlns")) { + if (buffer.length() > 0) { + buffer.append(", "); + } + buffer.append(qt); + buffer.append(prefix); + buffer.append(":"); + buffer.append(getLocalName(attribute)); + buffer.append(qt + ":" + qt); + buffer.append(escapeQuote(getAttributeValue(attribute))); + buffer.append(qt); } - print(buffer.toString()); - hasAttribute = true; - } - print(")"); } - return hasAttribute; - } - - protected void printAttributeWithPrefix(final Attr attribute, final StringBuffer buffer) { - String prefix = attribute.getPrefix(); - if (prefix != null && prefix.length() > 0 && !prefix.equals("xmlns")) { - if (buffer.length() > 0) { - buffer.append(", "); - } - buffer.append(qt); - buffer.append(prefix); - buffer.append(":"); - buffer.append(getLocalName(attribute)); - buffer.append(qt + ":" + qt); - buffer.append(escapeQuote(getAttributeValue(attribute))); - buffer.append(qt); + + protected String getAttributeValue(final Attr attribute) { + return attribute.getValue(); } - } - - protected String getAttributeValue(final Attr attribute) { - return attribute.getValue(); - } - - protected boolean printAttributeWithoutPrefix(final Attr attribute, boolean hasAttribute) { - String prefix = attribute.getPrefix(); - if (prefix == null || prefix.length() == 0) { - if (!hasAttribute) { - hasAttribute = true; - } else { - print(", "); - } - String localName = getLocalName(attribute); - boolean needsEscaping = checkEscaping(localName); - if (needsEscaping) - print(qt); - print(localName); - if (needsEscaping) - print(qt); - print(":"); - printQuoted(getAttributeValue(attribute)); + + protected boolean printAttributeWithoutPrefix(final Attr attribute, boolean hasAttribute) { + String prefix = attribute.getPrefix(); + if (prefix == null || prefix.length() == 0) { + if (!hasAttribute) { + hasAttribute = true; + } else { + print(", "); + } + String localName = getLocalName(attribute); + boolean needsEscaping = checkEscaping(localName); + if (needsEscaping) print(qt); + print(localName); + if (needsEscaping) print(qt); + print(":"); + printQuoted(getAttributeValue(attribute)); + } + return hasAttribute; } - return hasAttribute; - } - - protected boolean checkEscaping(final String localName) { - return keywords.contains(localName) || localName.contains("-") || localName.contains(".") || localName.contains(":"); - } - - protected String getTextNodeData(final Text node) { - return node.getData().trim(); - } - - protected boolean mixedContent(final NodeList list) { - boolean hasText = false; - boolean hasElement = false; - for (int i = 0, size = list.getLength(); i < size; i++) { - Node node = list.item(i); - if (node instanceof Element) { - hasElement = true; - } else if (node instanceof Text) { - String text = getTextNodeData((Text) node); - if (text.length() > 0) { - hasText = true; + + protected boolean checkEscaping(final String localName) { + return keywords.contains(localName) + || localName.contains("-") + || localName.contains(".") + || localName.contains(":"); + } + + protected String getTextNodeData(final Text node) { + return node.getData().trim(); + } + + protected boolean mixedContent(final NodeList list) { + boolean hasText = false; + boolean hasElement = false; + for (int i = 0, size = list.getLength(); i < size; i++) { + Node node = list.item(i); + if (node instanceof Element) { + hasElement = true; + } else if (node instanceof Text) { + String text = getTextNodeData((Text) node); + if (text.length() > 0) { + hasText = true; + } + } } - } + return hasText && hasElement; } - return hasText && hasElement; - } - protected void printChildren(final Node parent, final Map namespaces) { - for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) { - print(node, namespaces, false); + protected void printChildren(final Node parent, final Map namespaces) { + for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) { + print(node, namespaces, false); + } } - } - protected String getLocalName(final Node node) { - String answer = node.getLocalName(); - if (answer == null) { - answer = node.getNodeName(); + protected String getLocalName(final Node node) { + String answer = node.getLocalName(); + if (answer == null) { + answer = node.getNodeName(); + } + return answer.trim(); } - return answer.trim(); - } - - protected void printEnd(final String text, final boolean endWithComma) { - if (endWithComma) { - print(text); - println(","); - } else { - println(text); + + protected void printEnd(final String text, final boolean endWithComma) { + if (endWithComma) { + print(text); + println(","); + } else { + println(text); + } } - } - protected void println(final String text) { - out.println(text); - } + protected void println(final String text) { + out.println(text); + } - protected void print(final String text) { - out.print(text); - } + protected void print(final String text) { + out.print(text); + } - protected void printIndent() { - out.printIndent(); - } + protected void printIndent() { + out.printIndent(); + } } diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyMapping.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyMapping.java index 331599ba..cef1ac9f 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyMapping.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyMapping.java @@ -9,7 +9,6 @@ import javax.inject.Named; import javax.inject.Singleton; - import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -20,13 +19,13 @@ * @since 0.7 */ @Singleton -@Named( "groovy" ) +@Named("groovy") public class GroovyMapping extends MappingSupport { - public GroovyMapping() { - super("groovy"); - setPomNames("pom.groovy", "pom.gy"); - setAcceptLocationExtensions(".groovy", ".gy"); - setAcceptOptionKeys("groovy:4.0.0"); - setPriority(1); - } -} \ No newline at end of file + public GroovyMapping() { + super("groovy"); + setPomNames("pom.groovy", "pom.gy"); + setAcceptLocationExtensions(".groovy", ".gy"); + setAcceptOptionKeys("groovy:4.0.0"); + setPriority(1); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelReader.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelReader.java index f3b4faea..5be9e69e 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelReader.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelReader.java @@ -7,19 +7,16 @@ */ package org.sonatype.maven.polyglot.groovy; -import javax.inject.Inject; -import javax.inject.Named; - import groovy.lang.GroovyCodeSource; import groovy.lang.GroovyShell; import groovy.lang.Script; - +import groovy.lang.Singleton; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.util.Map; - -import groovy.lang.Singleton; +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.codehaus.groovy.runtime.StackTraceUtils; @@ -39,84 +36,84 @@ * @since 0.7 */ @Singleton -@Named( "groovy" ) +@Named("groovy") public class GroovyModelReader extends ModelReaderSupport { - protected Logger log = LoggerFactory.getLogger(GroovyModelReader.class); + protected Logger log = LoggerFactory.getLogger(GroovyModelReader.class); - @Inject - private ModelBuilder builder; + @Inject + private ModelBuilder builder; - @Inject - private ExecuteManager executeManager; + @Inject + private ExecuteManager executeManager; - @Override - public Model read(final Reader input, final Map options) throws IOException { - assert input != null; + @Override + public Model read(final Reader input, final Map options) throws IOException { + assert input != null; - Model model; + Model model; - try { - model = doRead(input, options); - } catch (Throwable t) { - t = StackTraceUtils.sanitize(t); + try { + model = doRead(input, options); + } catch (Throwable t) { + t = StackTraceUtils.sanitize(t); - if (t instanceof IOException) { - throw (IOException) t; - } - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - if (t instanceof Error) { - throw (Error) t; - } + if (t instanceof IOException) { + throw (IOException) t; + } + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + if (t instanceof Error) { + throw (Error) t; + } - throw new RuntimeException(t); - } + throw new RuntimeException(t); + } + + // FIXME: Looks like there are cases where the model is loaded more than once + executeManager.install(model, options); - // FIXME: Looks like there are cases where the model is loaded more than once - executeManager.install(model, options); + if (log.isDebugEnabled()) { + DefaultModelWriter writer = new DefaultModelWriter(); + StringWriter buff = new StringWriter(); + writer.write(buff, null, model); + log.debug("Read groovy model: \n" + buff); + } - if (log.isDebugEnabled()) { - DefaultModelWriter writer = new DefaultModelWriter(); - StringWriter buff = new StringWriter(); - writer.write(buff, null, model); - log.debug("Read groovy model: \n" + buff); + return model; } - return model; - } - - private Model doRead(final Reader input, final Map options) throws IOException { - assert input != null; - - GroovyShell shell = new GroovyShell(); - String text = IOUtil.toString(input); - String location = PolyglotModelUtil.getLocation(options); - Script script = shell.parse(new GroovyCodeSource(text, location, location)); - - /* - * FIXME: Bring this back as pure java - * - * def include = {source -> assert source != null - * - * def include - * - * // TODO: Support String, support loading from resource - * - * if (source instanceof Class) { include = source.newInstance() } else if (source instanceof File) { include = shell.parse((File)source) } else if (source instanceof URL) { include = - * shell.parse(((URL)source).openStream()) } else { throw new IllegalArgumentException("Invalid include source: $source") } - * - * include.run() - * - * // Include each closure variable which starts with '$' and curry in the builder include.binding.properties.variables.each { if (it.value instanceof Closure && it.key.startsWith('$')) { - * binding.setVariable(it.key, it.value.curry(builder)) } } } - * - * include(Macros) - * - * binding.setProperty('$include', include) - */ - - assert builder != null; - return (Model) builder.build(script); - } + private Model doRead(final Reader input, final Map options) throws IOException { + assert input != null; + + GroovyShell shell = new GroovyShell(); + String text = IOUtil.toString(input); + String location = PolyglotModelUtil.getLocation(options); + Script script = shell.parse(new GroovyCodeSource(text, location, location)); + + /* + * FIXME: Bring this back as pure java + * + * def include = {source -> assert source != null + * + * def include + * + * // TODO: Support String, support loading from resource + * + * if (source instanceof Class) { include = source.newInstance() } else if (source instanceof File) { include = shell.parse((File)source) } else if (source instanceof URL) { include = + * shell.parse(((URL)source).openStream()) } else { throw new IllegalArgumentException("Invalid include source: $source") } + * + * include.run() + * + * // Include each closure variable which starts with '$' and curry in the builder include.binding.properties.variables.each { if (it.value instanceof Closure && it.key.startsWith('$')) { + * binding.setVariable(it.key, it.value.curry(builder)) } } } + * + * include(Macros) + * + * binding.setProperty('$include', include) + */ + + assert builder != null; + return (Model) builder.build(script); + } } diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelWriter.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelWriter.java index d5b5e98c..3aa14f47 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelWriter.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/GroovyModelWriter.java @@ -9,19 +9,16 @@ import groovy.lang.Singleton; import groovy.util.IndentPrinter; - import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Map; - import javax.inject.Named; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import org.apache.maven.model.Model; import org.apache.maven.model.io.DefaultModelWriter; import org.slf4j.Logger; @@ -42,40 +39,40 @@ * @since 0.7 */ @Singleton -@Named( "groovy" ) +@Named("groovy") public class GroovyModelWriter extends ModelWriterSupport { - protected Logger log = LoggerFactory.getLogger(GroovyModelWriter.class); + protected Logger log = LoggerFactory.getLogger(GroovyModelWriter.class); - @Override - public void write(final Writer output, final Map options, final Model model) throws IOException { - assert output != null; - assert model != null; + @Override + public void write(final Writer output, final Map options, final Model model) throws IOException { + assert output != null; + assert model != null; - StringWriter buff = new StringWriter(); - DefaultModelWriter writer = new DefaultModelWriter(); - writer.write(buff, options, model); + StringWriter buff = new StringWriter(); + DefaultModelWriter writer = new DefaultModelWriter(); + writer.write(buff, options, model); - Dom2Groovy converter = new Dom2Groovy(new IndentPrinter(new PrintWriter(output), " ")); + Dom2Groovy converter = new Dom2Groovy(new IndentPrinter(new PrintWriter(output), " ")); - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.parse(new InputSource(new StringReader(buff.toString()))); + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.parse(new InputSource(new StringReader(buff.toString()))); - Element root = doc.getDocumentElement(); - NamedNodeMap attrs = root.getAttributes(); - for (int i = 0; i < attrs.getLength(); i++) { - Attr attr = (Attr) attrs.item(i); - root.removeAttribute(attr.getName()); - } - // Not sure where this comes from but the above will not nuke it - root.removeAttribute("xmlns:xsi"); + Element root = doc.getDocumentElement(); + NamedNodeMap attrs = root.getAttributes(); + for (int i = 0; i < attrs.getLength(); i++) { + Attr attr = (Attr) attrs.item(i); + root.removeAttribute(attr.getName()); + } + // Not sure where this comes from but the above will not nuke it + root.removeAttribute("xmlns:xsi"); - converter.print(doc); - output.flush(); - } catch (ParserConfigurationException e) { - throw (IOException) new IOException().initCause(e); - } catch (SAXException e) { - throw (IOException) new IOException().initCause(e); + converter.print(doc); + output.flush(); + } catch (ParserConfigurationException e) { + throw (IOException) new IOException().initCause(e); + } catch (SAXException e) { + throw (IOException) new IOException().initCause(e); + } } - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/ModelBuilder.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/ModelBuilder.java index 60809476..af1e7228 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/ModelBuilder.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/ModelBuilder.java @@ -7,16 +7,12 @@ */ package org.sonatype.maven.polyglot.groovy.builder; -import javax.inject.Inject; -import javax.inject.Named; - import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.GroovyObjectSupport; import groovy.lang.Singleton; import groovy.util.Factory; import groovy.util.FactoryBuilderSupport; - import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -25,7 +21,8 @@ import java.util.Map; import java.util.Properties; import java.util.Set; - +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.model.Activation; import org.apache.maven.model.Contributor; import org.apache.maven.model.Dependency; @@ -82,260 +79,261 @@ @Singleton @Named public class ModelBuilder extends FactoryBuilderSupport { - protected Logger log = LoggerFactory.getLogger(ModelBuilder.class); + protected Logger log = LoggerFactory.getLogger(ModelBuilder.class); - private final Set factoryNames = new HashSet(); + private final Set factoryNames = new HashSet(); - private final Set factoryTypes = new HashSet(); + private final Set factoryTypes = new HashSet(); - private final List tasks = new ArrayList(); + private final List tasks = new ArrayList(); - @Inject - private ExecuteManager executeManager; + @Inject + private ExecuteManager executeManager; - public ModelBuilder() { - registerFactories(); - } + public ModelBuilder() { + registerFactories(); + } + + /** + * Delegate to force use of invokeMethod when building the model. + */ + private final GroovyObject invokeDelegate = new GroovyObjectSupport() { + @Override + public Object invokeMethod(final String name, final Object args) { + return ModelBuilder.this.invokeMethod(name, args); + } + }; - /** - * Delegate to force use of invokeMethod when building the model. - */ - private final GroovyObject invokeDelegate = new GroovyObjectSupport() - { @Override - public Object invokeMethod(final String name, final Object args) { - return ModelBuilder.this.invokeMethod(name, args); + protected void setClosureDelegate(final Closure c, final Object o) { + c.setDelegate(invokeDelegate); + c.setResolveStrategy(Closure.DELEGATE_FIRST); } - }; - - @Override - protected void setClosureDelegate(final Closure c, final Object o) { - c.setDelegate(invokeDelegate); - c.setResolveStrategy(Closure.DELEGATE_FIRST); - } - - public ExecuteManager getExecuteManager() { - return executeManager; - } - - public List getTasks() { - return tasks; - } - - public void registerFactories() { - registerStringFactory("module"); - registerStringFactory("filter"); - registerStringFactory("include"); - registerStringFactory("exclude"); - registerStringFactory("goal"); - registerStringFactory("role"); - registerStringFactory("otherArchive"); - registerStringFactory("activeByDefault"); - registerStringFactory("report"); - - registerFactory(new PluginFactory()); - registerFactoriesFor(Plugin.class); - - registerFactory(new ModulesFactory()); - registerFactory(new ExclusionsFactory()); - registerFactory(new ExtensionsFactory()); - registerFactory(new IncludesFactory()); - registerFactory(new ExcludesFactory()); - registerFactory(new GoalsFactory()); - registerFactory(new ExecuteFactory()); - registerFactory(new ReportSetsFactory()); - registerFactory(new ReportsFactory()); - - registerFactory(new ReportingFactory()); - registerFactoriesFor(Reporting.class); - - registerFactory(new ExecutionFactory()); - registerFactoriesFor(PluginExecution.class); - - registerFactory(new ModelFactory()); - registerFactoriesFor(Model.class); - - registerChildFactory("dependency", Dependency.class); - registerChildFactory("exclusion", Exclusion.class); - registerChildFactory("extension", Extension.class); - registerChildFactory("resource", Resource.class); - registerChildFactory("testResource", Resource.class); - registerChildFactory("notifier", Notifier.class); - registerChildFactory("contributor", Contributor.class); - registerChildFactory("developer", Developer.class); - registerChildFactory("license", License.class); - registerChildFactory("mailingList", MailingList.class); - registerChildFactory("profile", Profile.class); - registerChildFactory("repository", DeploymentRepository.class); - registerChildFactory("pluginRepository", Repository.class); - registerChildFactory("reportSet", ReportSet.class); - registerChildFactory("activation", Activation.class); - } - - @Override - public void registerBeanFactory(final String name, final Class type) { - super.registerBeanFactory(name, type); - registerFactoriesFor(type); - } - - @Override - public void registerFactory(final String name, final String groupName, final Factory factory) { - if (log.isDebugEnabled()) { - log.debug("Registering factory: " + name + ", factory: " + factory); - if (factoryNames.contains(name)) { - log.warn("Duplicate factory: " + name); - } + + public ExecuteManager getExecuteManager() { + return executeManager; } - factoryNames.add(name); - super.registerFactory(name, groupName, factory); - } - - private void registerFactory(final NamedFactory factory) { - assert factory != null; - registerFactory(factory.getName(), null, factory); - } - - private void registerChildFactory(final String name, final Class type) { - registerFactory(createChildFactory(name, type)); - registerFactoriesFor(type); - } - - private NamedFactory createChildFactory(final String name, final Class type) { - assert name != null; - assert type != null; - - if (type == Parent.class) { - return new ParentFactory(); + + public List getTasks() { + return tasks; } - if (type == Dependency.class) { - return new DependencyFactory(); + + public void registerFactories() { + registerStringFactory("module"); + registerStringFactory("filter"); + registerStringFactory("include"); + registerStringFactory("exclude"); + registerStringFactory("goal"); + registerStringFactory("role"); + registerStringFactory("otherArchive"); + registerStringFactory("activeByDefault"); + registerStringFactory("report"); + + registerFactory(new PluginFactory()); + registerFactoriesFor(Plugin.class); + + registerFactory(new ModulesFactory()); + registerFactory(new ExclusionsFactory()); + registerFactory(new ExtensionsFactory()); + registerFactory(new IncludesFactory()); + registerFactory(new ExcludesFactory()); + registerFactory(new GoalsFactory()); + registerFactory(new ExecuteFactory()); + registerFactory(new ReportSetsFactory()); + registerFactory(new ReportsFactory()); + + registerFactory(new ReportingFactory()); + registerFactoriesFor(Reporting.class); + + registerFactory(new ExecutionFactory()); + registerFactoriesFor(PluginExecution.class); + + registerFactory(new ModelFactory()); + registerFactoriesFor(Model.class); + + registerChildFactory("dependency", Dependency.class); + registerChildFactory("exclusion", Exclusion.class); + registerChildFactory("extension", Extension.class); + registerChildFactory("resource", Resource.class); + registerChildFactory("testResource", Resource.class); + registerChildFactory("notifier", Notifier.class); + registerChildFactory("contributor", Contributor.class); + registerChildFactory("developer", Developer.class); + registerChildFactory("license", License.class); + registerChildFactory("mailingList", MailingList.class); + registerChildFactory("profile", Profile.class); + registerChildFactory("repository", DeploymentRepository.class); + registerChildFactory("pluginRepository", Repository.class); + registerChildFactory("reportSet", ReportSet.class); + registerChildFactory("activation", Activation.class); } - if (type == Exclusion.class) { - return new ExclusionFactory(); + + @Override + public void registerBeanFactory(final String name, final Class type) { + super.registerBeanFactory(name, type); + registerFactoriesFor(type); } - return new ChildFactory(name, type); - } + @Override + public void registerFactory(final String name, final String groupName, final Factory factory) { + if (log.isDebugEnabled()) { + log.debug("Registering factory: " + name + ", factory: " + factory); + if (factoryNames.contains(name)) { + log.warn("Duplicate factory: " + name); + } + } + factoryNames.add(name); + super.registerFactory(name, groupName, factory); + } - private void registerStringFactory(final String name) { - registerFactory(new StringFactory(name)); - } + private void registerFactory(final NamedFactory factory) { + assert factory != null; + registerFactory(factory.getName(), null, factory); + } - private void registerListFactory(final String name) { - registerFactory(new ListFactory(name)); - } + private void registerChildFactory(final String name, final Class type) { + registerFactory(createChildFactory(name, type)); + registerFactoriesFor(type); + } - private void registerPropertiesFactory(final String name) { - registerFactory(new PropertiesFactory(name)); - } + private NamedFactory createChildFactory(final String name, final Class type) { + assert name != null; + assert type != null; - private void registerObjectFactory(final String name) { - registerFactory(new ObjectFactory(name)); - } + if (type == Parent.class) { + return new ParentFactory(); + } + if (type == Dependency.class) { + return new DependencyFactory(); + } + if (type == Exclusion.class) { + return new ExclusionFactory(); + } + + return new ChildFactory(name, type); + } - private void registerFactoriesFor(final Class type) { - assert type != null; + private void registerStringFactory(final String name) { + registerFactory(new StringFactory(name)); + } + + private void registerListFactory(final String name) { + registerFactory(new ListFactory(name)); + } - if (factoryTypes.contains(type)) { - return; + private void registerPropertiesFactory(final String name) { + registerFactory(new PropertiesFactory(name)); } - factoryTypes.add(type); - if (log.isDebugEnabled()) { - log.debug("Registering factories for type: " + type); + private void registerObjectFactory(final String name) { + registerFactory(new ObjectFactory(name)); } - Method[] methods = type.getMethods(); - for (Method method : methods) { - if (isSetter(method)) { - String name = propertyNameOf(method); + private void registerFactoriesFor(final Class type) { + assert type != null; - if (factoryNames.contains(name)) { - continue; + if (factoryTypes.contains(type)) { + return; } + factoryTypes.add(type); - Class param = method.getParameterTypes()[0]; - if (param == String.class) { - registerStringFactory(name); - } else if (param == List.class) { - registerListFactory(name); - } else if (param == Properties.class) { - registerPropertiesFactory(name); - } else if (param == Object.class) { - registerObjectFactory(name); - } else if (param.getName().startsWith("org.apache.maven.model.")) { - registerChildFactory(name, param); - } else { - // Skip setters with unsupported types (model will use string versions) - if (log.isDebugEnabled()) { - log.debug("Skipping setter with unsupported type: " + method); - } + if (log.isDebugEnabled()) { + log.debug("Registering factories for type: " + type); } - } - } - } - private boolean isSetter(final Method method) { - assert method != null; - if (!method.getName().startsWith("set")) { - return false; + Method[] methods = type.getMethods(); + for (Method method : methods) { + if (isSetter(method)) { + String name = propertyNameOf(method); + + if (factoryNames.contains(name)) { + continue; + } + + Class param = method.getParameterTypes()[0]; + if (param == String.class) { + registerStringFactory(name); + } else if (param == List.class) { + registerListFactory(name); + } else if (param == Properties.class) { + registerPropertiesFactory(name); + } else if (param == Object.class) { + registerObjectFactory(name); + } else if (param.getName().startsWith("org.apache.maven.model.")) { + registerChildFactory(name, param); + } else { + // Skip setters with unsupported types (model will use string versions) + if (log.isDebugEnabled()) { + log.debug("Skipping setter with unsupported type: " + method); + } + } + } + } } - if (method.getParameterTypes().length > 1) { - return false; + private boolean isSetter(final Method method) { + assert method != null; + if (!method.getName().startsWith("set")) { + return false; + } - } - if (method.getReturnType() != Void.TYPE) { - return false; - } + if (method.getParameterTypes().length > 1) { + return false; + } + if (method.getReturnType() != Void.TYPE) { + return false; + } - int m = method.getModifiers(); - if (!Modifier.isPublic(m) || Modifier.isStatic(m)) { - return false; + int m = method.getModifiers(); + if (!Modifier.isPublic(m) || Modifier.isStatic(m)) { + return false; + } + + return true; } - return true; - } + private String propertyNameOf(final Method method) { + assert method != null; + + String name = method.getName(); + name = name.substring(3, name.length()); - private String propertyNameOf(final Method method) { - assert method != null; + return new StringBuffer(name.length()) + .append(Character.toLowerCase(name.charAt(0))) + .append(name.substring(1)) + .toString(); + } - String name = method.getName(); - name = name.substring(3, name.length()); + public Object findInContext(final String key) { + for (Map ctx : getContexts()) { + if (ctx.containsKey(key)) { + return ctx.get(key); + } + } - return new StringBuffer(name.length()).append(Character.toLowerCase(name.charAt(0))).append(name.substring(1)).toString(); - } + return null; + } + + // BEGIN: Kludgy Workaround + // Explanation: When I translated the slf4j pom.xml to pom.groovy, I ended up with this: + // plugin { + // artifactId 'maven-project-info-reports-plugin' + // reportSets { + // reportSet + // } + // } + // The ModelBuilder saw this, and assumed that it was trying to populate the reportSet method. Note + // that this shows up because the slf4j pom.xml includes + // a + private ReportSet reportSet; + + public ReportSet getReportSet() { + return reportSet; + } - public Object findInContext(final String key) { - for (Map ctx : getContexts()) { - if (ctx.containsKey(key)) { - return ctx.get(key); - } + public void setReportSet(ReportSet reportSet) { + this.reportSet = reportSet; } + // END: Kludgy Workaround - return null; - } - - // BEGIN: Kludgy Workaround - // Explanation: When I translated the slf4j pom.xml to pom.groovy, I ended up with this: - // plugin { - // artifactId 'maven-project-info-reports-plugin' - // reportSets { - // reportSet - // } - // } - // The ModelBuilder saw this, and assumed that it was trying to populate the reportSet method. Note - // that this shows up because the slf4j pom.xml includes - // a - private ReportSet reportSet; - - public ReportSet getReportSet() { - return reportSet; - } - - public void setReportSet(ReportSet reportSet) { - this.reportSet = reportSet; - } - // END: Kludgy Workaround - -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ChildFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ChildFactory.java index d56db3aa..17d9a4df 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ChildFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ChildFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.Map; /** @@ -19,14 +18,15 @@ * @since 0.7 */ public class ChildFactory extends NamedFactory { - private final Class type; + private final Class type; - public ChildFactory(final String name, final Class type) { - super(name); - this.type = type; - } + public ChildFactory(final String name, final Class type) { + super(name); + this.type = type; + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return type.newInstance(); - } -} \ No newline at end of file + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return type.newInstance(); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/DependencyFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/DependencyFactory.java index c0e212cd..ac597204 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/DependencyFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/DependencyFactory.java @@ -8,9 +8,8 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Dependency; - import java.util.Map; +import org.apache.maven.model.Dependency; /** * Builds {@link org.apache.maven.model.Dependency} nodes. @@ -20,53 +19,54 @@ * @since 0.7 */ public class DependencyFactory extends NamedFactory { - public DependencyFactory() { - super("dependency"); - } + public DependencyFactory() { + super("dependency"); + } + + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + Dependency node; - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - Dependency node; + if (value != null) { + node = parse(value); - if (value != null) { - node = parse(value); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new Dependency(); + } - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new Dependency(); + return node; } - return node; - } + public static Dependency parse(final Object value) { + assert value != null; - public static Dependency parse(final Object value) { - assert value != null; + if (value instanceof String) { + Dependency node = new Dependency(); + String[] items = ((String) value).split(":"); + switch (items.length) { + case 4: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + node.setVersion(items[2]); + node.setScope(items[3]); + return node; - if (value instanceof String) { - Dependency node = new Dependency(); - String[] items = ((String) value).split(":"); - switch (items.length) { - case 4: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - node.setVersion(items[2]); - node.setScope(items[3]); - return node; + case 3: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + node.setVersion(items[2]); + return node; - case 3: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - node.setVersion(items[2]); - return node; + case 2: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + return node; + } + } - case 2: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - return node; - } + return null; } - - return null; - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExcludesFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExcludesFactory.java index 87ac5a71..33540cc3 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExcludesFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExcludesFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -21,42 +20,43 @@ * @since 0.7 */ public class ExcludesFactory extends ListFactory { - public ExcludesFactory() { - super("excludes"); - } - - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; - - if (value != null) { - node = parse(value); - - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); + public ExcludesFactory() { + super("excludes"); } - return node; - } + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - public static List parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); - List node = new ArrayList(); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - if (value instanceof String) { - node.add(value); - return node; - } else if (value instanceof List) { - for (Object item : (List) value) { - node.add(String.valueOf(item)); - } - return node; + return node; } - return null; - } -} \ No newline at end of file + public static List parse(final Object value) { + assert value != null; + + List node = new ArrayList(); + + if (value instanceof String) { + node.add(value); + return node; + } else if (value instanceof List) { + for (Object item : (List) value) { + node.add(String.valueOf(item)); + } + return node; + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionFactory.java index ff73fbb4..9cf23682 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionFactory.java @@ -8,9 +8,8 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; - import java.util.Map; +import org.apache.maven.model.Exclusion; /** * Builds {@link org.apache.maven.model.Exclusion} nodes. @@ -20,39 +19,40 @@ * @since 0.7 */ public class ExclusionFactory extends NamedFactory { - public ExclusionFactory() { - super("exclusion"); - } - - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - Exclusion node; - - if (value != null) { - node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new Exclusion(); + public ExclusionFactory() { + super("exclusion"); } - return node; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + Exclusion node; - public static Exclusion parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new Exclusion(); + } - if (value instanceof String) { - Exclusion node = new Exclusion(); - String[] items = ((String) value).split(":"); - switch (items.length) { - case 2: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); return node; - } } - return null; - } -} \ No newline at end of file + public static Exclusion parse(final Object value) { + assert value != null; + + if (value instanceof String) { + Exclusion node = new Exclusion(); + String[] items = ((String) value).split(":"); + switch (items.length) { + case 2: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + return node; + } + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionsFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionsFactory.java index ef3cadac..99a3059d 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionsFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExclusionsFactory.java @@ -8,11 +8,10 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.maven.model.Exclusion; /** * Builds exclusions nodes. @@ -22,49 +21,50 @@ * @since 0.7 */ public class ExclusionsFactory extends ListFactory { - public ExclusionsFactory() { - super("exclusions"); - } + public ExclusionsFactory() { + super("exclusions"); + } - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - if (value != null) { - node = parse(value); + if (value != null) { + node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); - } + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - return node; - } + return node; + } - public static List parse(final Object value) { - assert value != null; + public static List parse(final Object value) { + assert value != null; - if (value instanceof String) { - Exclusion child = ExclusionFactory.parse(value); - if (child != null) { - List node = new ArrayList(); - node.add(child); - return node; - } - } else if (value instanceof List) { - List node = new ArrayList(); - for (Object item : (List) value) { - Exclusion child = ExclusionFactory.parse(item); - if (child == null) { - return null; + if (value instanceof String) { + Exclusion child = ExclusionFactory.parse(value); + if (child != null) { + List node = new ArrayList(); + node.add(child); + return node; + } + } else if (value instanceof List) { + List node = new ArrayList(); + for (Object item : (List) value) { + Exclusion child = ExclusionFactory.parse(item); + if (child == null) { + return null; + } + node.add(child); + } + return node; } - node.add(child); - } - return node; - } - return null; - } -} \ No newline at end of file + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecuteFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecuteFactory.java index a6803b04..3175daf0 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecuteFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecuteFactory.java @@ -9,14 +9,13 @@ import groovy.lang.Closure; import groovy.util.FactoryBuilderSupport; +import java.util.List; +import java.util.Map; import org.apache.maven.model.Build; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; import org.sonatype.maven.polyglot.groovy.execute.GroovyExecuteTask; -import java.util.List; -import java.util.Map; - /** * Builds {@link GroovyExecuteTask}s. * @@ -25,45 +24,46 @@ * @since 0.7 */ public class ExecuteFactory extends NamedFactory { - public ExecuteFactory() { - super("$execute"); - } - - @Override - public boolean isHandlesNodeChildren() { - return true; - } + public ExecuteFactory() { + super("$execute"); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new GroovyExecuteTask(value, attrs); - } + @Override + public boolean isHandlesNodeChildren() { + return true; + } - @Override - public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { - if (parent instanceof Build) { - GroovyExecuteTask task = (GroovyExecuteTask) child; - List tasks = ((ModelBuilder) builder).getTasks(); - tasks.add(task); - } else { - throw new IllegalStateException("The " + getName() + " element must only be defined under 'build'"); + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new GroovyExecuteTask(value, attrs); } - } - @Override - public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { - GroovyExecuteTask task = (GroovyExecuteTask) node; - task.setClosure(content); - return false; - } + @Override + public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { + if (parent instanceof Build) { + GroovyExecuteTask task = (GroovyExecuteTask) child; + List tasks = ((ModelBuilder) builder).getTasks(); + tasks.add(task); + } else { + throw new IllegalStateException("The " + getName() + " element must only be defined under 'build'"); + } + } - @Override - public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { - GroovyExecuteTask task = (GroovyExecuteTask) node; - if (task.getId() == null) { - throw new IllegalStateException("Execute task is missing attribute 'id'"); + @Override + public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { + GroovyExecuteTask task = (GroovyExecuteTask) node; + task.setClosure(content); + return false; } - if (task.getPhase() == null) { - throw new IllegalStateException("Execute task is missing attribute 'phase'"); + + @Override + public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { + GroovyExecuteTask task = (GroovyExecuteTask) node; + if (task.getId() == null) { + throw new IllegalStateException("Execute task is missing attribute 'id'"); + } + if (task.getPhase() == null) { + throw new IllegalStateException("Execute task is missing attribute 'phase'"); + } } - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecutionFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecutionFactory.java index 6ea85a64..45ce4886 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecutionFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExecutionFactory.java @@ -8,11 +8,10 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.PluginExecution; - import java.util.Collections; import java.util.List; import java.util.Map; +import org.apache.maven.model.PluginExecution; /** * Builds {@link org.apache.maven.model.PluginExecution} nodes. @@ -21,33 +20,34 @@ * @since 0.7 */ public class ExecutionFactory extends NamedFactory { - public ExecutionFactory() { - super("execution"); - } + public ExecutionFactory() { + super("execution"); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new PluginExecution(); - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new PluginExecution(); + } - @Override - public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object current, Map attrs) { - PluginExecution node = (PluginExecution) current; + @Override + public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object current, Map attrs) { + PluginExecution node = (PluginExecution) current; - // Custom handling for 'goal' and 'goals' attributes - if (attrs.containsKey("goal")) { - Object value = attrs.get("goal"); - node.setGoals(Collections.singletonList(String.valueOf(value))); - attrs.remove("goal"); - } else if (attrs.containsKey("goals")) { - Object value = attrs.get("goals"); - if (value instanceof String) { - node.setGoals(Collections.singletonList(String.valueOf(value))); - } else if (value instanceof List) { - node.setGoals((List) value); - } - attrs.remove("goals"); - } + // Custom handling for 'goal' and 'goals' attributes + if (attrs.containsKey("goal")) { + Object value = attrs.get("goal"); + node.setGoals(Collections.singletonList(String.valueOf(value))); + attrs.remove("goal"); + } else if (attrs.containsKey("goals")) { + Object value = attrs.get("goals"); + if (value instanceof String) { + node.setGoals(Collections.singletonList(String.valueOf(value))); + } else if (value instanceof List) { + node.setGoals((List) value); + } + attrs.remove("goals"); + } - return true; - } -} \ No newline at end of file + return true; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionFactory.java index 96beff67..7a36b6f3 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionFactory.java @@ -8,9 +8,7 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.Map; - import org.apache.maven.model.Extension; /** @@ -21,44 +19,45 @@ * @since 0.8 */ public class ExtensionFactory extends NamedFactory { - public ExtensionFactory() { - super("extension"); - } - - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - Extension node; - - if (value != null) { - node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new Extension(); + public ExtensionFactory() { + super("extension"); } - return node; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + Extension node; - public static Extension parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new Extension(); + } - if (value instanceof String) { - Extension node = new Extension(); - String[] items = ((String) value).split(":"); - switch (items.length) { - case 2: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - return node; - case 3: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - node.setVersion(items[2]); return node; - } } - return null; - } -} \ No newline at end of file + public static Extension parse(final Object value) { + assert value != null; + + if (value instanceof String) { + Extension node = new Extension(); + String[] items = ((String) value).split(":"); + switch (items.length) { + case 2: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + return node; + case 3: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + node.setVersion(items[2]); + return node; + } + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionsFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionsFactory.java index 6082801d..c02a4f42 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionsFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ExtensionsFactory.java @@ -8,12 +8,10 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; -import org.apache.maven.model.Extension; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.maven.model.Extension; /** * Builds extensions nodes. @@ -23,59 +21,60 @@ * @since 0.8 */ public class ExtensionsFactory extends ListFactory { - public ExtensionsFactory() { - super("extensions"); - } + public ExtensionsFactory() { + super("extensions"); + } - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - Object node; + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + Object node; - if (value != null) { - node = parse(value); + if (value != null) { + node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); - } + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - return node; - } + return node; + } - public static Object parse(final Object value) { - assert value != null; + public static Object parse(final Object value) { + assert value != null; - // This first clause is a kludge. Maybe there is a better way - // but we're overloading "extensions" in POMs. - if (value instanceof String && isBoolean((String) value)) { - return value; - } else if (value instanceof String) { - Extension child = ExtensionFactory.parse(value); - if (child != null) { - List node = new ArrayList(); - node.add(child); - return node; - } - } else if (value instanceof List) { - List node = new ArrayList(); - for (Object item : (List) value) { - Extension child = ExtensionFactory.parse(item); - if (child == null) { - return null; + // This first clause is a kludge. Maybe there is a better way + // but we're overloading "extensions" in POMs. + if (value instanceof String && isBoolean((String) value)) { + return value; + } else if (value instanceof String) { + Extension child = ExtensionFactory.parse(value); + if (child != null) { + List node = new ArrayList(); + node.add(child); + return node; + } + } else if (value instanceof List) { + List node = new ArrayList(); + for (Object item : (List) value) { + Extension child = ExtensionFactory.parse(item); + if (child == null) { + return null; + } + node.add(child); + } + return node; } - node.add(child); - } - return node; - } - return null; - } + return null; + } - // TOB: Sure, some clever bastard is going to come along and tell me there - // is a simpler way to do this. Please, if you have a better solution fix this. - private static boolean isBoolean(String value) { - return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"); - } -} \ No newline at end of file + // TOB: Sure, some clever bastard is going to come along and tell me there + // is a simpler way to do this. Please, if you have a better solution fix this. + private static boolean isBoolean(String value) { + return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/GoalsFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/GoalsFactory.java index e8c442d3..a4d3a5d3 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/GoalsFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/GoalsFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -21,41 +20,42 @@ * @since 0.7 */ public class GoalsFactory extends ListFactory { - public GoalsFactory() { - super("goals"); - } - - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; - - if (value != null) { - node = parse(value); - - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); + public GoalsFactory() { + super("goals"); } - return node; - } - - public static List parse(final Object value) { - assert value != null; - - List node = new ArrayList(); - if (value instanceof String) { - node.add((String) value); - return node; - } else if (value instanceof List) { - for (Object item : (List) value) { - node.add(String.valueOf(item)); - } - return node; + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; + + if (value != null) { + node = parse(value); + + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } + + return node; } - return null; - } + public static List parse(final Object value) { + assert value != null; + + List node = new ArrayList(); + if (value instanceof String) { + node.add((String) value); + return node; + } else if (value instanceof List) { + for (Object item : (List) value) { + node.add(String.valueOf(item)); + } + return node; + } + + return null; + } } diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/IncludesFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/IncludesFactory.java index 0cfef1be..baaa6f7b 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/IncludesFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/IncludesFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -21,42 +20,43 @@ * @since 0.7 */ public class IncludesFactory extends ListFactory { - public IncludesFactory() { - super("includes"); - } - - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; - - if (value != null) { - node = parse(value); - - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); + public IncludesFactory() { + super("includes"); } - return node; - } + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - public static List parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); - List node = new ArrayList(); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - if (value instanceof String) { - node.add((String) value); - return node; - } else if (value instanceof List) { - for (Object item : (List) value) { - node.add(String.valueOf(item)); - } - return node; + return node; } - return null; - } -} \ No newline at end of file + public static List parse(final Object value) { + assert value != null; + + List node = new ArrayList(); + + if (value instanceof String) { + node.add((String) value); + return node; + } else if (value instanceof List) { + for (Object item : (List) value) { + node.add(String.valueOf(item)); + } + return node; + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ListFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ListFactory.java index 325b51e3..295ff237 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ListFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ListFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.ArrayList; import java.util.Map; @@ -20,11 +19,12 @@ * @since 0.7 */ public class ListFactory extends NamedFactory { - public ListFactory(final String name) { - super(name); - } + public ListFactory(final String name) { + super(name); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new ArrayList(); - } -} \ No newline at end of file + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new ArrayList(); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModelFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModelFactory.java index 73e4f0b5..c7d18d7d 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModelFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModelFactory.java @@ -8,14 +8,13 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; +import java.util.List; +import java.util.Map; import org.apache.maven.model.Model; import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; -import java.util.List; -import java.util.Map; - /** * Builds {@link Model} elements and handles registration of any {@link ExecuteTask}s. * @@ -24,22 +23,23 @@ * @since 0.7 */ public class ModelFactory extends NamedFactory { - public ModelFactory() { - super("project"); - } + public ModelFactory() { + super("project"); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new Model(); - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new Model(); + } - @Override - public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { - Model model = (Model) node; - ExecuteManager manager = ((ModelBuilder) builder).getExecuteManager(); - List tasks = ((ModelBuilder) builder).getTasks(); - manager.register(model, tasks); + @Override + public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { + Model model = (Model) node; + ExecuteManager manager = ((ModelBuilder) builder).getExecuteManager(); + List tasks = ((ModelBuilder) builder).getTasks(); + manager.register(model, tasks); - // Reset the tasks list for sanity - tasks.clear(); - } -} \ No newline at end of file + // Reset the tasks list for sanity + tasks.clear(); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModulesFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModulesFactory.java index 66f4897f..c6593478 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModulesFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ModulesFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -21,42 +20,43 @@ * @since 0.7 */ public class ModulesFactory extends ListFactory { - public ModulesFactory() { - super("modules"); - } - - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; - - if (value != null) { - node = parse(value); - - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); + public ModulesFactory() { + super("modules"); } - return node; - } + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - public static List parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); - List node = new ArrayList(); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - if (value instanceof String) { - node.add(value); - return node; - } else if (value instanceof List) { - for (Object item : (List) value) { - node.add(String.valueOf(item)); - } - return node; + return node; } - return null; - } -} \ No newline at end of file + public static List parse(final Object value) { + assert value != null; + + List node = new ArrayList(); + + if (value instanceof String) { + node.add(value); + return node; + } else if (value instanceof List) { + for (Object item : (List) value) { + node.add(String.valueOf(item)); + } + return node; + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/NamedFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/NamedFactory.java index 3dd978da..ba6c053c 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/NamedFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/NamedFactory.java @@ -9,9 +9,8 @@ import groovy.util.AbstractFactory; import groovy.util.FactoryBuilderSupport; -import org.codehaus.groovy.runtime.InvokerHelper; - import java.util.List; +import org.codehaus.groovy.runtime.InvokerHelper; /** * Support for named factories. @@ -21,36 +20,34 @@ * @since 0.7 */ public abstract class NamedFactory extends AbstractFactory { - private final String name; + private final String name; - protected NamedFactory(final String name) { - this.name = name; - } + protected NamedFactory(final String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - @SuppressWarnings({ - "unchecked" - }) - @Override - public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { - if (parent instanceof List) { - ((List) parent).add(child); - } else { - InvokerHelper.setProperty(parent, getName(), child); + @SuppressWarnings({"unchecked"}) + @Override + public void setParent(FactoryBuilderSupport builder, Object parent, Object child) { + if (parent instanceof List) { + ((List) parent).add(child); + } else { + InvokerHelper.setProperty(parent, getName(), child); + } } - } - protected static class NodeValueParseException extends IllegalArgumentException { - public NodeValueParseException(final NamedFactory factory, final Object value) { - super("Unable to parse " + factory.getName() + " for: " + value + " (" + value.getClass() + ")"); + protected static class NodeValueParseException extends IllegalArgumentException { + public NodeValueParseException(final NamedFactory factory, final Object value) { + super("Unable to parse " + factory.getName() + " for: " + value + " (" + value.getClass() + ")"); + } } - } - @Override - public String toString() { - return getClass().getSimpleName() + "{" + "name='" + name + '\'' + '}'; - } -} \ No newline at end of file + @Override + public String toString() { + return getClass().getSimpleName() + "{" + "name='" + name + '\'' + '}'; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ObjectFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ObjectFactory.java index b65bec61..d8902f73 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ObjectFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ObjectFactory.java @@ -11,10 +11,9 @@ import groovy.util.FactoryBuilderSupport; import groovy.util.Node; import groovy.util.NodeBuilder; -import org.codehaus.plexus.util.xml.Xpp3Dom; - import java.util.List; import java.util.Map; +import org.codehaus.plexus.util.xml.Xpp3Dom; /** * Builds object nodes. @@ -24,66 +23,67 @@ * @since 0.7 */ public class ObjectFactory extends NamedFactory { - public ObjectFactory(final String name) { - super(name); - } + public ObjectFactory(final String name) { + super(name); + } + + @Override + public boolean isHandlesNodeChildren() { + return true; + } - @Override - public boolean isHandlesNodeChildren() { - return true; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new Xpp3Dom(getName()); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new Xpp3Dom(getName()); - } + @Override + public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { + Xpp3Dom dom = (Xpp3Dom) node; - @Override - public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { - Xpp3Dom dom = (Xpp3Dom) node; + NodeBuilder nodes = new NodeBuilder() { + @Override + protected void setClosureDelegate(final Closure c, final Object o) { + c.setDelegate(this); + c.setResolveStrategy(Closure.DELEGATE_FIRST); + } - NodeBuilder nodes = new NodeBuilder() { - @Override - protected void setClosureDelegate(final Closure c, final Object o) { - c.setDelegate(this); - c.setResolveStrategy(Closure.DELEGATE_FIRST); - } + @Override + public void setProperty(final String name, final Object value) { + this.invokeMethod(name, value); + } + }; - @Override - public void setProperty(final String name, final Object value) { - this.invokeMethod(name, value); - } - }; + content.setDelegate(nodes); + content.setResolveStrategy(Closure.DELEGATE_FIRST); + Node root = (Node) nodes.invokeMethod(getName(), content); - content.setDelegate(nodes); - content.setResolveStrategy(Closure.DELEGATE_FIRST); - Node root = (Node) nodes.invokeMethod(getName(), content); + for (Node child : (List) root.children()) { + dom.addChild(nodeToXpp3(child)); + } - for (Node child : (List) root.children()) { - dom.addChild(nodeToXpp3(child)); + return false; } - return false; - } + private Xpp3Dom nodeToXpp3(final Node node) { + Xpp3Dom dom = new Xpp3Dom((String) node.name()); - private Xpp3Dom nodeToXpp3(final Node node) { - Xpp3Dom dom = new Xpp3Dom((String) node.name()); + Object value = node.value(); + if (value instanceof String) { + dom.setValue(String.valueOf(value)); + } - Object value = node.value(); - if (value instanceof String) { - dom.setValue(String.valueOf(value)); - } + Map attrs = node.attributes(); + for (Object key : attrs.keySet()) { + dom.setAttribute(String.valueOf(key), String.valueOf(attrs.get(key))); + } - Map attrs = node.attributes(); - for (Object key : attrs.keySet()) { - dom.setAttribute(String.valueOf(key), String.valueOf(attrs.get(key))); - } + for (Object child : node.children()) { + if (child instanceof Node) { + dom.addChild(nodeToXpp3((Node) child)); + } + } - for (Object child : node.children()) { - if (child instanceof Node) { - dom.addChild(nodeToXpp3((Node) child)); - } + return dom; } - - return dom; - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ParentFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ParentFactory.java index c035cab7..e99950c3 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ParentFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ParentFactory.java @@ -8,9 +8,8 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Parent; - import java.util.Map; +import org.apache.maven.model.Parent; /** * Builds {@link Parent} nodes. @@ -20,41 +19,42 @@ * @since 0.7 */ public class ParentFactory extends NamedFactory { - public ParentFactory() { - super("parent"); - } - - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - Parent node; - - if (value != null) { - node = parse(value); - - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new Parent(); + public ParentFactory() { + super("parent"); } - return node; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + Parent node; - public static Parent parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); + + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new Parent(); + } - if (value instanceof String) { - Parent node = new Parent(); - String[] items = ((String) value).split(":"); - switch (items.length) { - case 3: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - node.setVersion(items[2]); return node; - } } - return null; - } -} \ No newline at end of file + public static Parent parse(final Object value) { + assert value != null; + + if (value instanceof String) { + Parent node = new Parent(); + String[] items = ((String) value).split(":"); + switch (items.length) { + case 3: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + node.setVersion(items[2]); + return node; + } + } + + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PluginFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PluginFactory.java index 15f25ad9..9b4d5618 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PluginFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PluginFactory.java @@ -8,13 +8,12 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; +import java.util.Map; import org.apache.maven.model.Plugin; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Reporting; import org.sonatype.maven.polyglot.groovy.builder.ModelBuilder; -import java.util.Map; - /** * Builds {@link org.apache.maven.model.Plugin} nodes. * @@ -23,50 +22,51 @@ * @since 0.7 */ public class PluginFactory extends NamedFactory { - public PluginFactory() { - super("plugin"); - } + public PluginFactory() { + super("plugin"); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - if (((ModelBuilder) builder).findInContext(Reporting.class.getName()) != null) { - return new ReportPlugin(); - } else { - Plugin node; + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + if (((ModelBuilder) builder).findInContext(Reporting.class.getName()) != null) { + return new ReportPlugin(); + } else { + Plugin node; - if (value != null) { - node = parse(value); + if (value != null) { + node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new Plugin(); - } + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new Plugin(); + } - return node; + return node; + } } - } - public static Plugin parse(final Object value) { - assert value != null; + public static Plugin parse(final Object value) { + assert value != null; - if (value instanceof String) { - Plugin node = new Plugin(); - String[] items = ((String) value).split(":"); - switch (items.length) { - case 3: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - node.setVersion(items[2]); - return node; + if (value instanceof String) { + Plugin node = new Plugin(); + String[] items = ((String) value).split(":"); + switch (items.length) { + case 3: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + node.setVersion(items[2]); + return node; - case 2: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - return node; - } - } + case 2: + node.setGroupId(items[0]); + node.setArtifactId(items[1]); + return node; + } + } - return null; - } -} \ No newline at end of file + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PropertiesFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PropertiesFactory.java index 812bf1b8..a134298a 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PropertiesFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/PropertiesFactory.java @@ -11,7 +11,6 @@ import groovy.util.FactoryBuilderSupport; import groovy.util.Node; import groovy.util.NodeBuilder; - import java.util.List; import java.util.Map; import java.util.Properties; @@ -24,68 +23,69 @@ * @since 0.7 */ public class PropertiesFactory extends NamedFactory { - public PropertiesFactory(final String name) { - super(name); - } + public PropertiesFactory(final String name) { + super(name); + } + + @Override + public boolean isHandlesNodeChildren() { + return true; + } - @Override - public boolean isHandlesNodeChildren() { - return true; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + return new Properties(); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - return new Properties(); - } + @Override + public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { + Properties props = (Properties) node; - @Override - public boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure content) { - Properties props = (Properties) node; + NodeBuilder nodes = new NodeBuilder() { + @Override + protected void setClosureDelegate(final Closure c, final Object o) { + c.setDelegate(this); + c.setResolveStrategy(Closure.DELEGATE_FIRST); + } - NodeBuilder nodes = new NodeBuilder() { - @Override - protected void setClosureDelegate(final Closure c, final Object o) { - c.setDelegate(this); - c.setResolveStrategy(Closure.DELEGATE_FIRST); - } + @Override + public void setProperty(final String name, final Object value) { + this.invokeMethod(name, value); + } + }; - @Override - public void setProperty(final String name, final Object value) { - this.invokeMethod(name, value); - } - }; + content.setDelegate(nodes); + content.setResolveStrategy(Closure.DELEGATE_FIRST); + Node root = (Node) nodes.invokeMethod(getName(), content); - content.setDelegate(nodes); - content.setResolveStrategy(Closure.DELEGATE_FIRST); - Node root = (Node) nodes.invokeMethod(getName(), content); + for (Node child : (List) root.value()) { + merge(props, child, ""); + } - for (Node child : (List) root.value()) { - merge(props, child, ""); + return false; } - return false; - } - - private void merge(Properties props, Node node, String prefix) { - assert props != null; - assert node != null; - assert prefix != null; + private void merge(Properties props, Node node, String prefix) { + assert props != null; + assert node != null; + assert prefix != null; - String name = prefix + node.name(); + String name = prefix + node.name(); - Object value = node.value(); - if (value instanceof String) { - props.setProperty(name, String.valueOf(value)); - } + Object value = node.value(); + if (value instanceof String) { + props.setProperty(name, String.valueOf(value)); + } - Map attrs = node.attributes(); - for (Object key : attrs.keySet()) { - props.setProperty(name + "." + key, String.valueOf(attrs.get(key))); - } + Map attrs = node.attributes(); + for (Object key : attrs.keySet()) { + props.setProperty(name + "." + key, String.valueOf(attrs.get(key))); + } - for (Object child : node.children()) { - if (child instanceof Node) { - merge(props, (Node) child, name + "."); - } + for (Object child : node.children()) { + if (child instanceof Node) { + merge(props, (Node) child, name + "."); + } + } } - } -} \ No newline at end of file +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetFactory.java index 4826c1c2..366da70b 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetFactory.java @@ -8,10 +8,8 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; -import org.apache.maven.model.ReportSet; - import java.util.Map; +import org.apache.maven.model.ReportSet; /** * Builds {@link org.apache.maven.model.ReportSet} nodes. @@ -21,39 +19,39 @@ * @since 0.8 */ public class ReportSetFactory extends NamedFactory { - public ReportSetFactory() { - super("reportSet"); - } - - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - ReportSet node; - - if (value != null) { - node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ReportSet(); + public ReportSetFactory() { + super("reportSet"); } - return node; - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + ReportSet node; - public static ReportSet parse(final Object value) { - assert value != null; + if (value != null) { + node = parse(value); + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ReportSet(); + } - /** if (value instanceof String) { - ReportSet node = new ReportSEt(); - String[] items = ((String)value).split(":"); - switch (items.length) { - case 2: - node.setGroupId(items[0]); - node.setArtifactId(items[1]); - return node; - } - } **/ + return node; + } - return null; - } -} \ No newline at end of file + public static ReportSet parse(final Object value) { + assert value != null; + + /** if (value instanceof String) { + * ReportSet node = new ReportSEt(); + * String[] items = ((String)value).split(":"); + * switch (items.length) { + * case 2: + * node.setGroupId(items[0]); + * node.setArtifactId(items[1]); + * return node; + * } + * } **/ + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetsFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetsFactory.java index 37bb2053..576106e6 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetsFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportSetsFactory.java @@ -8,12 +8,10 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; -import org.apache.maven.model.ReportSet; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.maven.model.ReportSet; /** * Builds reportSets nodes. @@ -23,49 +21,50 @@ * @since 0.8 */ public class ReportSetsFactory extends ListFactory { - public ReportSetsFactory() { - super("reportSets"); - } + public ReportSetsFactory() { + super("reportSets"); + } - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - if (value != null) { - node = parse(value); + if (value != null) { + node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); - } + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - return node; - } + return node; + } - public static List parse(final Object value) { - assert value != null; + public static List parse(final Object value) { + assert value != null; - if (value instanceof String) { - ReportSet child = ReportSetFactory.parse(value); - if (child != null) { - List node = new ArrayList(); - node.add(child); - return node; - } - } else if (value instanceof List) { - List node = new ArrayList(); - for (Object item : (List) value) { - ReportSet child = ReportSetFactory.parse(item); - if (child == null) { - return null; + if (value instanceof String) { + ReportSet child = ReportSetFactory.parse(value); + if (child != null) { + List node = new ArrayList(); + node.add(child); + return node; + } + } else if (value instanceof List) { + List node = new ArrayList(); + for (Object item : (List) value) { + ReportSet child = ReportSetFactory.parse(item); + if (child == null) { + return null; + } + node.add(child); + } + return node; } - node.add(child); - } - return node; - } - return null; - } -} \ No newline at end of file + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportingFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportingFactory.java index 265cacf0..48a1e1be 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportingFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportingFactory.java @@ -8,9 +8,8 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Reporting; - import java.util.Map; +import org.apache.maven.model.Reporting; /** * Builds {@link org.apache.maven.model.Reporting} nodes. @@ -20,17 +19,18 @@ * @since 0.7 */ public class ReportingFactory extends NamedFactory { - public ReportingFactory() { - super("reporting"); - } + public ReportingFactory() { + super("reporting"); + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - builder.getContext().put(Reporting.class.getName(), true); - return new Reporting(); - } + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + builder.getContext().put(Reporting.class.getName(), true); + return new Reporting(); + } - @Override - public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { - builder.getContext().remove(Reporting.class.getName()); - } -} \ No newline at end of file + @Override + public void onNodeCompleted(FactoryBuilderSupport builder, Object parent, Object node) { + builder.getContext().remove(Reporting.class.getName()); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportsFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportsFactory.java index e71626ce..0a9a0679 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportsFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/ReportsFactory.java @@ -8,9 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; -import org.apache.maven.model.Exclusion; -import org.apache.maven.model.ReportSet; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -23,49 +20,50 @@ * @since 0.8 */ public class ReportsFactory extends ListFactory { - public ReportsFactory() { - super("reports"); - } + public ReportsFactory() { + super("reports"); + } - @Override - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) throws InstantiationException, IllegalAccessException { - List node; + @Override + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) + throws InstantiationException, IllegalAccessException { + List node; - if (value != null) { - node = parse(value); + if (value != null) { + node = parse(value); - if (node == null) { - throw new NodeValueParseException(this, value); - } - } else { - node = new ArrayList(); - } + if (node == null) { + throw new NodeValueParseException(this, value); + } + } else { + node = new ArrayList(); + } - return node; - } + return node; + } - public static List parse(final Object value) { - assert value != null; + public static List parse(final Object value) { + assert value != null; - if (value instanceof String) { - String child = (String) value; - if (child != null) { - List node = new ArrayList(); - node.add(child); - return node; - } - } else if (value instanceof List) { - List node = new ArrayList(); - for (Object item : (List) value) { - String child = (String) item; - if (child == null) { - return null; + if (value instanceof String) { + String child = (String) value; + if (child != null) { + List node = new ArrayList(); + node.add(child); + return node; + } + } else if (value instanceof List) { + List node = new ArrayList(); + for (Object item : (List) value) { + String child = (String) item; + if (child == null) { + return null; + } + node.add(child); + } + return node; } - node.add(child); - } - return node; - } - return null; - } -} \ No newline at end of file + return null; + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/StringFactory.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/StringFactory.java index fba63c4d..c30f412f 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/StringFactory.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/builder/factory/StringFactory.java @@ -8,7 +8,6 @@ package org.sonatype.maven.polyglot.groovy.builder.factory; import groovy.util.FactoryBuilderSupport; - import java.util.Map; /** @@ -19,16 +18,16 @@ * @since 0.7 */ public class StringFactory extends NamedFactory { - public StringFactory(final String name) { - super(name); - } + public StringFactory(final String name) { + super(name); + } - @Override - public boolean isLeaf() { - return true; - } + @Override + public boolean isLeaf() { + return true; + } - public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) { - return String.valueOf(value); - } -} \ No newline at end of file + public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attrs) { + return String.valueOf(value); + } +} diff --git a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/execute/GroovyExecuteTask.java b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/execute/GroovyExecuteTask.java index 8907f5e9..48069cc8 100644 --- a/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/execute/GroovyExecuteTask.java +++ b/polyglot-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/execute/GroovyExecuteTask.java @@ -8,13 +8,12 @@ package org.sonatype.maven.polyglot.groovy.execute; import groovy.lang.Closure; +import java.util.Map; import org.codehaus.groovy.runtime.StackTraceUtils; import org.sonatype.maven.polyglot.execute.ExecuteContext; import org.sonatype.maven.polyglot.execute.ExecuteTask; import org.sonatype.maven.polyglot.execute.ExecuteTaskSupport; -import java.util.Map; - /** * Encapsulates a Groovy {@link ExecuteTask}. * @@ -23,55 +22,56 @@ * @since 0.7 */ public class GroovyExecuteTask extends ExecuteTaskSupport { - private final Object value; + private final Object value; - private final Map attrs; + private final Map attrs; - private Closure closure; + private Closure closure; - public GroovyExecuteTask(final Object value, final Map attrs) { - this.value = value; - this.attrs = attrs; - } + public GroovyExecuteTask(final Object value, final Map attrs) { + this.value = value; + this.attrs = attrs; + } - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public Map getAttributes() { - return attrs; - } + public Map getAttributes() { + return attrs; + } - public Closure getClosure() { - return closure; - } + public Closure getClosure() { + return closure; + } - public void setClosure(final Closure closure) { - this.closure = closure; - } + public void setClosure(final Closure closure) { + this.closure = closure; + } - public void execute(final ExecuteContext context) throws Exception { - try { - getClosure().call(context); - } catch (Throwable t) { - t = StackTraceUtils.sanitize(t); + public void execute(final ExecuteContext context) throws Exception { + try { + getClosure().call(context); + } catch (Throwable t) { + t = StackTraceUtils.sanitize(t); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - if (t instanceof Exception) { - throw (Exception) t; - } - if (t instanceof Error) { - throw (Error) t; - } + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + if (t instanceof Exception) { + throw (Exception) t; + } + if (t instanceof Error) { + throw (Error) t; + } - throw new RuntimeException(t); + throw new RuntimeException(t); + } } - } - @Override - public String toString() { - return getClass().getSimpleName() + "{" + "id='" + getId() + '\'' + ", phase='" + getPhase() + '\'' + ", value=" + value + ", attrs=" + attrs + ", closure=" + closure + '}'; - } -} \ No newline at end of file + @Override + public String toString() { + return getClass().getSimpleName() + "{" + "id='" + getId() + '\'' + ", phase='" + getPhase() + '\'' + ", value=" + + value + ", attrs=" + attrs + ", closure=" + closure + '}'; + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaMapping.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaMapping.java index 8aa3e876..7b3befca 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaMapping.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaMapping.java @@ -7,11 +7,9 @@ */ package org.sonatype.maven.polyglot.java; +import java.util.Map; import javax.inject.Named; import javax.inject.Singleton; - -import java.util.Map; - import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -19,29 +17,29 @@ * */ @Singleton -@Named( "java" ) +@Named("java") public class JavaMapping extends MappingSupport { - public JavaMapping() { - super("java"); - setPomNames("pom.java"); - setAcceptLocationExtensions(".java"); - setAcceptOptionKeys("java:4.0.0"); - setPriority(-1); - } - - @Override - public boolean accept(Map options) { - if (options != null) { - - String location = getLocation(options); - if (location != null) { - if (location.endsWith(".java")) { - return true; - } - } - } - - return false; - } -} \ No newline at end of file + public JavaMapping() { + super("java"); + setPomNames("pom.java"); + setAcceptLocationExtensions(".java"); + setAcceptOptionKeys("java:4.0.0"); + setPriority(-1); + } + + @Override + public boolean accept(Map options) { + if (options != null) { + + String location = getLocation(options); + if (location != null) { + if (location.endsWith(".java")) { + return true; + } + } + } + + return false; + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelReader.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelReader.java index 074cf1ad..ab8d2a61 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelReader.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelReader.java @@ -7,6 +7,7 @@ */ package org.sonatype.maven.polyglot.java; +import com.google.common.io.Files; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -17,13 +18,11 @@ import java.util.Arrays; import java.util.Map; import java.util.UUID; - import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; - import org.apache.commons.io.FileUtils; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelParseException; @@ -34,134 +33,135 @@ import org.sonatype.maven.polyglot.io.ModelReaderSupport; import org.sonatype.maven.polyglot.java.dsl.ModelFactory; -import com.google.common.io.Files; - /** * Java model reader. * */ @Singleton -@Named( "java" ) +@Named("java") public class JavaModelReader extends ModelReaderSupport { - @Inject - private PlexusContainer container; - - protected Logger log = LoggerFactory.getLogger( JavaModelReader.class ); - - public JavaModelReader() { - } - - private String getClassPath() { - - String pathSeparator = System.getProperty("path.separator", ":"); - - StringBuilder sb = new StringBuilder(); - for (ClassRealm realm : container.getContainerRealm().getWorld().getRealms()) { - if (realm.getId().contains("io.takari.polyglot:polyglot-java")) { - for (URL jarURL : Arrays.asList(realm.getURLs())) { - if (sb.length() > 0) { - sb.append(pathSeparator); - } - sb.append(jarURL.getPath()); - } - } - if (realm.getId().contains("plexus.core")) { - for (URL jarURL : Arrays.asList(realm.getURLs())) { - if (jarURL.getPath().contains("commons-lang3") || jarURL.getPath().contains("plexus-utils") || jarURL.getPath().contains("maven-model-3")) { - if (sb.length() > 0) { - sb.append(pathSeparator); - } - sb.append(jarURL.getPath().replaceAll("/bin/..", "")); - } - } - } - } - String classPath = sb.toString(); - log.debug("Calculated classpath for dynamic POM.java compilation as " + classPath); - - return classPath; - } - - private String replaceClassNameInSrc(String src, String className) { - - int classWordEnd = src.indexOf("class") + "class".length(); - int extendsStart = src.indexOf("extends"); - String newSrc = src.substring(0, classWordEnd) + " " + className + " " + src.substring(extendsStart, src.length()); - log.debug("Replaced class name to be " + className + " full src =" + newSrc); - - return newSrc; - } - - @SuppressWarnings("unchecked") - private Model compileJavaCode(String src) { - - Model model = null; - - File tempDir = Files.createTempDir(); - String randomClassName = "POM" + UUID.randomUUID().toString().replaceAll("-", ""); - String filePath = tempDir.getAbsolutePath(); - if (!filePath.endsWith("/")) { - filePath = filePath + "/"; - } - filePath = filePath + randomClassName + ".java"; - - try { - Files.write(replaceClassNameInSrc(src, randomClassName), new File(filePath), Charset.defaultCharset()); - log.debug("Created temp file " + filePath + " to compile POM.java"); - } catch (IOException e) { - e.printStackTrace(); - log.debug("Error writing file " + filePath, e); - } - - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - compiler.run(null, null, null, "-parameters", "-classpath", getClassPath(), filePath); - log.debug("Dynamically compiled class " + filePath); - - try { - URL comiledClassFolderURL = new URL("file:" + tempDir.getAbsolutePath() + "/"); - - ClassRealm systemClassLoader = (ClassRealm) getClass().getClassLoader(); - systemClassLoader.addURL(comiledClassFolderURL); - - log.debug("Added URL " + comiledClassFolderURL + " to Maven class loader to load class dynamically"); - - Class pomClass = (Class)Class.forName(randomClassName, false, systemClassLoader); - - model = pomClass.newInstance().getModel(); - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | MalformedURLException e) { - log.error("Failed to dynamically load class " + randomClassName, e); - } finally { - try { - FileUtils.deleteDirectory(tempDir); - } catch (IOException e) { - log.error("Failed to delete temp folder " + tempDir, e); - } - } - - return model; - } - - @Override - public Model read(Reader reader, Map options) throws IOException, ModelParseException { - return compileJavaCode(readFile(reader)); - } - - private String readFile(Reader fileReader) { - StringBuilder content = new StringBuilder(); - try { - BufferedReader reader = new BufferedReader(fileReader); - String line; - while ((line = reader.readLine()) != null) { - content.append(line); - content.append(System.lineSeparator()); - } - reader.close(); - return content.toString(); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} \ No newline at end of file + @Inject + private PlexusContainer container; + + protected Logger log = LoggerFactory.getLogger(JavaModelReader.class); + + public JavaModelReader() {} + + private String getClassPath() { + + String pathSeparator = System.getProperty("path.separator", ":"); + + StringBuilder sb = new StringBuilder(); + for (ClassRealm realm : container.getContainerRealm().getWorld().getRealms()) { + if (realm.getId().contains("io.takari.polyglot:polyglot-java")) { + for (URL jarURL : Arrays.asList(realm.getURLs())) { + if (sb.length() > 0) { + sb.append(pathSeparator); + } + sb.append(jarURL.getPath()); + } + } + if (realm.getId().contains("plexus.core")) { + for (URL jarURL : Arrays.asList(realm.getURLs())) { + if (jarURL.getPath().contains("commons-lang3") + || jarURL.getPath().contains("plexus-utils") + || jarURL.getPath().contains("maven-model-3")) { + if (sb.length() > 0) { + sb.append(pathSeparator); + } + sb.append(jarURL.getPath().replaceAll("/bin/..", "")); + } + } + } + } + String classPath = sb.toString(); + log.debug("Calculated classpath for dynamic POM.java compilation as " + classPath); + + return classPath; + } + + private String replaceClassNameInSrc(String src, String className) { + + int classWordEnd = src.indexOf("class") + "class".length(); + int extendsStart = src.indexOf("extends"); + String newSrc = + src.substring(0, classWordEnd) + " " + className + " " + src.substring(extendsStart, src.length()); + log.debug("Replaced class name to be " + className + " full src =" + newSrc); + + return newSrc; + } + + @SuppressWarnings("unchecked") + private Model compileJavaCode(String src) { + + Model model = null; + + File tempDir = Files.createTempDir(); + String randomClassName = "POM" + UUID.randomUUID().toString().replaceAll("-", ""); + String filePath = tempDir.getAbsolutePath(); + if (!filePath.endsWith("/")) { + filePath = filePath + "/"; + } + filePath = filePath + randomClassName + ".java"; + + try { + Files.write(replaceClassNameInSrc(src, randomClassName), new File(filePath), Charset.defaultCharset()); + log.debug("Created temp file " + filePath + " to compile POM.java"); + } catch (IOException e) { + e.printStackTrace(); + log.debug("Error writing file " + filePath, e); + } + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + compiler.run(null, null, null, "-parameters", "-classpath", getClassPath(), filePath); + log.debug("Dynamically compiled class " + filePath); + + try { + URL comiledClassFolderURL = new URL("file:" + tempDir.getAbsolutePath() + "/"); + + ClassRealm systemClassLoader = (ClassRealm) getClass().getClassLoader(); + systemClassLoader.addURL(comiledClassFolderURL); + + log.debug("Added URL " + comiledClassFolderURL + " to Maven class loader to load class dynamically"); + + Class pomClass = + (Class) Class.forName(randomClassName, false, systemClassLoader); + + model = pomClass.newInstance().getModel(); + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | MalformedURLException e) { + log.error("Failed to dynamically load class " + randomClassName, e); + } finally { + try { + FileUtils.deleteDirectory(tempDir); + } catch (IOException e) { + log.error("Failed to delete temp folder " + tempDir, e); + } + } + + return model; + } + + @Override + public Model read(Reader reader, Map options) throws IOException, ModelParseException { + return compileJavaCode(readFile(reader)); + } + + private String readFile(Reader fileReader) { + StringBuilder content = new StringBuilder(); + try { + BufferedReader reader = new BufferedReader(fileReader); + String line; + while ((line = reader.readLine()) != null) { + content.append(line); + content.append(System.lineSeparator()); + } + reader.close(); + return content.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelWriter.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelWriter.java index 8b32ec7c..9885a77a 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelWriter.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/JavaModelWriter.java @@ -7,13 +7,11 @@ */ package org.sonatype.maven.polyglot.java; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Writer; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import org.sonatype.maven.polyglot.java.writer.ModelToJavaWriter; @@ -23,16 +21,15 @@ * */ @Singleton -@Named( "java" ) +@Named("java") public class JavaModelWriter extends ModelWriterSupport { - - public JavaModelWriter() { - } - public void write(Writer output, Map o, Model model) throws IOException { - - ModelToJavaWriter toJavaWriter = new ModelToJavaWriter(output, model); - toJavaWriter.write(); - output.flush(); - } + public JavaModelWriter() {} + + public void write(Writer output, Map o, Model model) throws IOException { + + ModelToJavaWriter toJavaWriter = new ModelToJavaWriter(output, model); + toJavaWriter.write(); + output.flush(); + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBaseBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBaseBuilder.java index cff537db..152a38a4 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBaseBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBaseBuilder.java @@ -3,138 +3,138 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.function.Consumer; - import org.apache.maven.model.BuildBase; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginManagement; import org.apache.maven.model.Resource; public class BuildBaseBuilder { - - private BuildBase build = new BuildBase(); - protected BuildBase getBuild() { - return build; + private BuildBase build = new BuildBase(); + + protected BuildBase getBuild() { + return build; } - + public BuildBaseBuilder defaultGoal(String defaultGoal) { - if (defaultGoal != null) { - getBuild().setDefaultGoal(defaultGoal); - } - return this; + if (defaultGoal != null) { + getBuild().setDefaultGoal(defaultGoal); + } + return this; } - + public BuildBaseBuilder directory(String directory) { - if (directory != null) { - getBuild().setDirectory(directory); - } - return this; + if (directory != null) { + getBuild().setDirectory(directory); + } + return this; } - + public BuildBaseBuilder finalName(String finalName) { - if (finalName != null) { - getBuild().setFinalName(finalName); - } - return this; + if (finalName != null) { + getBuild().setFinalName(finalName); + } + return this; } - + public BuildBaseBuilder filters(String... filters) { - if (filters != null) { - getBuild().setFilters(Arrays.asList(filters)); - } - return this; + if (filters != null) { + getBuild().setFilters(Arrays.asList(filters)); + } + return this; } - + public BuildBaseBuilder resources(Resource... resources) { - if (resources != null) { - if (getBuild().getResources() == null) { - getBuild().setResources(new ArrayList<>()); - } - for (Resource resource : Arrays.asList(resources)) { - getBuild().addResource(resource); - } - } - return this; + if (resources != null) { + if (getBuild().getResources() == null) { + getBuild().setResources(new ArrayList<>()); + } + for (Resource resource : Arrays.asList(resources)) { + getBuild().addResource(resource); + } + } + return this; } - + public BuildBaseBuilder resources(Consumer... resources) { - if (resources != null) { - if (getBuild().getResources() == null) { - getBuild().setResources(new ArrayList<>()); - } - for (Consumer consumer : Arrays.asList(resources)) { - ResourceDTO dto = new ResourceDTO(); - consumer.accept(dto); - getBuild().addResource(dto.getResource()); - } - } - return this; + if (resources != null) { + if (getBuild().getResources() == null) { + getBuild().setResources(new ArrayList<>()); + } + for (Consumer consumer : Arrays.asList(resources)) { + ResourceDTO dto = new ResourceDTO(); + consumer.accept(dto); + getBuild().addResource(dto.getResource()); + } + } + return this; } - + public BuildBaseBuilder resources(ResourceBuilder... resourceBuilders) { - if (resourceBuilders != null) { - if (getBuild().getResources() == null) { - getBuild().setResources(new ArrayList<>()); - } - for (ResourceBuilder resourceBuilder : Arrays.asList(resourceBuilders)) { - getBuild().addResource(resourceBuilder.endResource()); - } - } - return this; + if (resourceBuilders != null) { + if (getBuild().getResources() == null) { + getBuild().setResources(new ArrayList<>()); + } + for (ResourceBuilder resourceBuilder : Arrays.asList(resourceBuilders)) { + getBuild().addResource(resourceBuilder.endResource()); + } + } + return this; } - + public BuildBaseBuilder testResources(ResourceBuilder... resourceBuilders) { - if (resourceBuilders != null) { - if (getBuild().getTestResources() == null) { - getBuild().setTestResources(new ArrayList<>()); - } - for (ResourceBuilder resourceBuilder : Arrays.asList(resourceBuilders)) { - getBuild().addTestResource(resourceBuilder.endResource()); - } - } - return this; + if (resourceBuilders != null) { + if (getBuild().getTestResources() == null) { + getBuild().setTestResources(new ArrayList<>()); + } + for (ResourceBuilder resourceBuilder : Arrays.asList(resourceBuilders)) { + getBuild().addTestResource(resourceBuilder.endResource()); + } + } + return this; } - + public BuildBaseBuilder testResources(Resource... testResources) { - if (testResources != null) { - if (getBuild().getTestResources() == null) { - getBuild().setTestResources(new ArrayList<>()); - } - for (Resource testResource : Arrays.asList(testResources)) { - getBuild().addTestResource(testResource); - } - } - return this; + if (testResources != null) { + if (getBuild().getTestResources() == null) { + getBuild().setTestResources(new ArrayList<>()); + } + for (Resource testResource : Arrays.asList(testResources)) { + getBuild().addTestResource(testResource); + } + } + return this; } - + public BuildBaseBuilder plugins(PluginBuilder... builders) { - if (builders != null) { - if (getBuild().getPlugins() == null) { - getBuild().setPlugins(new ArrayList()); - } - - Arrays.asList(builders).stream().forEach(builder -> getBuild().addPlugin(builder.get())); - } - return this; + if (builders != null) { + if (getBuild().getPlugins() == null) { + getBuild().setPlugins(new ArrayList()); + } + + Arrays.asList(builders).stream().forEach(builder -> getBuild().addPlugin(builder.get())); + } + return this; } - + public BuildBaseBuilder pluginManagement(PluginBuilder... builders) { - if (builders != null) { - if (getBuild().getPluginManagement() == null) { - getBuild().setPluginManagement(new PluginManagement()); - getBuild().getPluginManagement().setPlugins(new ArrayList()); - } - - Arrays.asList(builders).stream().forEach(builder -> getBuild().getPluginManagement().addPlugin(builder.get())); - } - return this; + if (builders != null) { + if (getBuild().getPluginManagement() == null) { + getBuild().setPluginManagement(new PluginManagement()); + getBuild().getPluginManagement().setPlugins(new ArrayList()); + } + + Arrays.asList(builders).stream() + .forEach(builder -> getBuild().getPluginManagement().addPlugin(builder.get())); + } + return this; } - - public BuildBaseBuilder endBuild() { - return this; + + public BuildBaseBuilder endBuild() { + return this; } - public BuildBase get() { - return getBuild(); - } + public BuildBase get() { + return getBuild(); + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBuilder.java index bf35fc7d..2f1b3d39 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildBuilder.java @@ -1,69 +1,68 @@ package org.sonatype.maven.polyglot.java.dsl; import java.util.Arrays; - import org.apache.maven.model.Build; import org.apache.maven.model.Extension; import org.apache.maven.model.Model; public class BuildBuilder extends BuildBaseBuilder { - - private Model model; - private Build build; - - public BuildBuilder(Model model) { - super(); - this.model = model; - } - @Override - protected Build getBuild() { - if (build == null) { - build = new Build(); - model.setBuild(build); - } - return build; - } + private Model model; + private Build build; + + public BuildBuilder(Model model) { + super(); + this.model = model; + } + + @Override + protected Build getBuild() { + if (build == null) { + build = new Build(); + model.setBuild(build); + } + return build; + } + + public BuildBuilder sourceDirectory(String sourceDirectory) { + if (sourceDirectory != null) { + getBuild().setSourceDirectory(sourceDirectory); + } + return this; + } + + public BuildBuilder scriptSourceDirectory(String scriptSourceDirectory) { + if (scriptSourceDirectory != null) { + getBuild().setScriptSourceDirectory(scriptSourceDirectory); + } + return this; + } + + public BuildBuilder testSourceDirectory(String testSourceDirectory) { + if (testSourceDirectory != null) { + getBuild().setTestSourceDirectory(testSourceDirectory); + } + return this; + } + + public BuildBuilder outputDirectory(String outputDirectory) { + if (outputDirectory != null) { + getBuild().setOutputDirectory(outputDirectory); + } + return this; + } + + public BuildBuilder testOutputDirectory(String testOutputDirectory) { + if (testOutputDirectory != null) { + getBuild().setTestOutputDirectory(testOutputDirectory); + } + return this; + } - public BuildBuilder sourceDirectory(String sourceDirectory) { - if (sourceDirectory != null) { - getBuild().setSourceDirectory(sourceDirectory); - } - return this; - } - - public BuildBuilder scriptSourceDirectory(String scriptSourceDirectory) { - if (scriptSourceDirectory != null) { - getBuild().setScriptSourceDirectory(scriptSourceDirectory); - } - return this; - } - - public BuildBuilder testSourceDirectory(String testSourceDirectory) { - if (testSourceDirectory != null) { - getBuild().setTestSourceDirectory(testSourceDirectory); - } - return this; - } - - public BuildBuilder outputDirectory(String outputDirectory) { - if (outputDirectory != null) { - getBuild().setOutputDirectory(outputDirectory); - } - return this; - } - - public BuildBuilder testOutputDirectory(String testOutputDirectory) { - if (testOutputDirectory != null) { - getBuild().setTestOutputDirectory(testOutputDirectory); - } - return this; - } - - public BuildBuilder extensions(Extension... extensions) { - if (extensions != null) { - getBuild().setExtensions(Arrays.asList(extensions)); - } - return this; - } + public BuildBuilder extensions(Extension... extensions) { + if (extensions != null) { + getBuild().setExtensions(Arrays.asList(extensions)); + } + return this; + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildFactory.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildFactory.java index 772e5595..1bde4440 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildFactory.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/BuildFactory.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.Map; import java.util.function.Consumer; - import org.apache.maven.model.Extension; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginManagement; @@ -17,309 +16,315 @@ import org.sonatype.maven.polyglot.java.namedval.NamedValueProcessor; public interface BuildFactory extends PluginFactory { - - public default BuildBaseBuilder profileBuild() { - return new BuildBaseBuilder(); - } - - public default PluginManagementNamedValue pluginManagement(Plugin... plugins) { - PluginManagementNamedValue namedValue = new PluginManagementNamedValue(); - PluginManagement pluginManagement = new PluginManagement(); - - if (plugins != null) { - pluginManagement.setPlugins(asList(plugins)); - namedValue.setPluginManagement(pluginManagement); - return namedValue; - } - - return null; - } - - public default BuildFiltersNamedValue filters(String... filters) { - if (filters != null) { - BuildFiltersNamedValue namedValue = new BuildFiltersNamedValue(); - namedValue.setFilters(asList(filters)); - return namedValue; - } - return null; - } - - public default BuildPluginsNamedValue plugins(Plugin... plugins) { - BuildPluginsNamedValue namedValue = new BuildPluginsNamedValue(); - - if (plugins != null) { - namedValue.setPlugins(asList(plugins)); - return namedValue; - } - - return null; - } - - public default BuildExtensionNamedValue extensions(Extension... extensions) { - if (extensions != null) { - BuildExtensionNamedValue namedValue = new BuildExtensionNamedValue(); - namedValue.setExtensions(asList(extensions)); - return namedValue; - } - return null; - } - - public default Extension extension(NamedValue... keyValuePairs) { - return NamedValueProcessor.namedToObject(new Extension(), keyValuePairs); - } - - public default Extension extension(String groupId, String artifactId, String version) { - Extension extension = new Extension(); - extension.setGroupId(groupId); - extension.setArtifactId(artifactId); - extension.setVersion(version); - return extension; - } - - public default Extension extension(String classifier) { - Extension extension = new Extension(); - - String[] parts = classifier.split(":"); - if (parts.length == 2) { - extension.setGroupId(parts[0]); - extension.setArtifactId(parts[1]); - } else if (parts.length == 3) { - extension.setVersion(parts[2]); - } - - return extension; - } - - public default ResourceBuilder resource() { - return new ResourceBuilder(); - } - - public default Resource resource(String directory, String targetPath, boolean filtering, String[] includes, String[] excludes) { - return resource(directory, targetPath, filtering, Arrays.asList(includes), Arrays.asList(excludes)); - } - - public default Resource resource(String directory, String targetPath, boolean filtering, List includes, List excludes) { - Resource resource = new Resource(); - resource.setDirectory(directory); - if (targetPath != null) { - resource.setTargetPath(targetPath); - } - resource.setFiltering(filtering); - if (includes != null) { - resource.setIncludes(includes); - } - if (excludes != null) { - resource.setExcludes(excludes); - } - return resource; - } - - public default BuildResourcesNamedValue resources(Resource... resources) { - if (resources != null) { - BuildResourcesNamedValue namedValue = new BuildResourcesNamedValue(); - namedValue.setResources(asList(resources)); - return namedValue; - } - return null; - } - - public default Resource resource(Consumer resourceConsumer) { - ResourceDTO resource = new ResourceDTO(); - resourceConsumer.accept(resource); - return resource.getResource(); - } - - public default Resource resource(ResourcesNamedValue... keyValuePairs) { - Resource resource = new Resource(); - - Map map = new HashMap<>(); - asList(keyValuePairs).stream().filter(kvp -> kvp != null).filter(kvp -> !(kvp instanceof ResourcesIncludesNamedValue) && !(kvp instanceof ResourcesExcludesNamedValue)) - .forEach(kvp -> map.put(kvp.name(), kvp.value())); - NamedValueProcessor.mapToObject(resource, map); - - asList(keyValuePairs).stream().filter(kvp -> kvp != null).filter(kvp -> (kvp instanceof ResourcesIncludesNamedValue)) - .forEach(kvp -> resource.setIncludes(((ResourcesIncludesNamedValue)kvp).getIncludes())); - - asList(keyValuePairs).stream().filter(kvp -> kvp != null).filter(kvp -> (kvp instanceof ResourcesExcludesNamedValue)) - .forEach(kvp -> resource.setIncludes(((ResourcesExcludesNamedValue)kvp).getExcludes())); - - return resource; - } - - public default BuildTestResourcesNamedValue testResources(Resource... resources) { - if (resources != null) { - BuildTestResourcesNamedValue namedValue = new BuildTestResourcesNamedValue(); - namedValue.setResources(asList(resources)); - return namedValue; - } - return null; - } - - public default ResourcesIncludesNamedValue includes(String... includes) { - ResourcesIncludesNamedValue namedValue = new ResourcesIncludesNamedValue(); - if (includes != null) { - namedValue.setIncludes(asList(includes)); - } - return namedValue; - } - - public default ResourcesExcludesNamedValue excludes(String... excludes) { - ResourcesExcludesNamedValue namedValue = new ResourcesExcludesNamedValue(); - if (excludes != null) { - namedValue.setExcludes(asList(excludes)); - } - return namedValue; - } - - public interface ResourcesNamedValue extends NamedValue { - } - - public class ResourcesIncludesNamedValue implements ResourcesNamedValue { - - private List includes = new ArrayList<>(); - - public List getIncludes() { - return includes; - } - - public void setIncludes(List includes) { - this.includes = includes; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class ResourcesExcludesNamedValue implements ResourcesNamedValue { - - private List excludes; - - public List getExcludes() { - return excludes; - } - - public void setExcludes(List excludes) { - this.excludes = excludes; - } - - @Override - public String apply(String str) { - return str; - } - } - - public interface BuildNamedValue extends NamedValue { - } - - public interface BuildComplexTypeNamedValue extends BuildNamedValue { - } - - public class BuildPluginsNamedValue implements BuildComplexTypeNamedValue { - - private List plugins; - - public List getPlugins() { - return plugins; - } - - public void setPlugins(List plugins) { - this.plugins = plugins; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class PluginManagementNamedValue implements BuildComplexTypeNamedValue { - - private PluginManagement pluginManagement; - - public PluginManagement getPluginManagement() { - return pluginManagement; - } - - public void setPluginManagement(PluginManagement pluginManagement) { - this.pluginManagement = pluginManagement; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class BuildExtensionNamedValue implements BuildComplexTypeNamedValue { - - private List extensions; - - public List getExtensions() { - return extensions; - } - - public void setExtensions(List extensions) { - this.extensions = extensions; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class BuildFiltersNamedValue implements BuildComplexTypeNamedValue { - private List filters; - - public List getFilters() { - return filters; - } - - public void setFilters(List filters) { - this.filters = filters; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class BuildResourcesNamedValue implements BuildComplexTypeNamedValue { - - private List resources; - - public List getResources() { - return resources; - } - public void setResources(List resources) { - this.resources = resources; - } + public default BuildBaseBuilder profileBuild() { + return new BuildBaseBuilder(); + } + + public default PluginManagementNamedValue pluginManagement(Plugin... plugins) { + PluginManagementNamedValue namedValue = new PluginManagementNamedValue(); + PluginManagement pluginManagement = new PluginManagement(); + + if (plugins != null) { + pluginManagement.setPlugins(asList(plugins)); + namedValue.setPluginManagement(pluginManagement); + return namedValue; + } + + return null; + } + + public default BuildFiltersNamedValue filters(String... filters) { + if (filters != null) { + BuildFiltersNamedValue namedValue = new BuildFiltersNamedValue(); + namedValue.setFilters(asList(filters)); + return namedValue; + } + return null; + } + + public default BuildPluginsNamedValue plugins(Plugin... plugins) { + BuildPluginsNamedValue namedValue = new BuildPluginsNamedValue(); + + if (plugins != null) { + namedValue.setPlugins(asList(plugins)); + return namedValue; + } + + return null; + } + + public default BuildExtensionNamedValue extensions(Extension... extensions) { + if (extensions != null) { + BuildExtensionNamedValue namedValue = new BuildExtensionNamedValue(); + namedValue.setExtensions(asList(extensions)); + return namedValue; + } + return null; + } + + public default Extension extension(NamedValue... keyValuePairs) { + return NamedValueProcessor.namedToObject(new Extension(), keyValuePairs); + } + + public default Extension extension(String groupId, String artifactId, String version) { + Extension extension = new Extension(); + extension.setGroupId(groupId); + extension.setArtifactId(artifactId); + extension.setVersion(version); + return extension; + } + + public default Extension extension(String classifier) { + Extension extension = new Extension(); + + String[] parts = classifier.split(":"); + if (parts.length == 2) { + extension.setGroupId(parts[0]); + extension.setArtifactId(parts[1]); + } else if (parts.length == 3) { + extension.setVersion(parts[2]); + } + + return extension; + } + + public default ResourceBuilder resource() { + return new ResourceBuilder(); + } + + public default Resource resource( + String directory, String targetPath, boolean filtering, String[] includes, String[] excludes) { + return resource(directory, targetPath, filtering, Arrays.asList(includes), Arrays.asList(excludes)); + } + + public default Resource resource( + String directory, String targetPath, boolean filtering, List includes, List excludes) { + Resource resource = new Resource(); + resource.setDirectory(directory); + if (targetPath != null) { + resource.setTargetPath(targetPath); + } + resource.setFiltering(filtering); + if (includes != null) { + resource.setIncludes(includes); + } + if (excludes != null) { + resource.setExcludes(excludes); + } + return resource; + } + + public default BuildResourcesNamedValue resources(Resource... resources) { + if (resources != null) { + BuildResourcesNamedValue namedValue = new BuildResourcesNamedValue(); + namedValue.setResources(asList(resources)); + return namedValue; + } + return null; + } + + public default Resource resource(Consumer resourceConsumer) { + ResourceDTO resource = new ResourceDTO(); + resourceConsumer.accept(resource); + return resource.getResource(); + } + + public default Resource resource(ResourcesNamedValue... keyValuePairs) { + Resource resource = new Resource(); + + Map map = new HashMap<>(); + asList(keyValuePairs).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> + !(kvp instanceof ResourcesIncludesNamedValue) && !(kvp instanceof ResourcesExcludesNamedValue)) + .forEach(kvp -> map.put(kvp.name(), kvp.value())); + NamedValueProcessor.mapToObject(resource, map); + + asList(keyValuePairs).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> (kvp instanceof ResourcesIncludesNamedValue)) + .forEach(kvp -> resource.setIncludes(((ResourcesIncludesNamedValue) kvp).getIncludes())); + + asList(keyValuePairs).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> (kvp instanceof ResourcesExcludesNamedValue)) + .forEach(kvp -> resource.setIncludes(((ResourcesExcludesNamedValue) kvp).getExcludes())); + + return resource; + } + + public default BuildTestResourcesNamedValue testResources(Resource... resources) { + if (resources != null) { + BuildTestResourcesNamedValue namedValue = new BuildTestResourcesNamedValue(); + namedValue.setResources(asList(resources)); + return namedValue; + } + return null; + } + + public default ResourcesIncludesNamedValue includes(String... includes) { + ResourcesIncludesNamedValue namedValue = new ResourcesIncludesNamedValue(); + if (includes != null) { + namedValue.setIncludes(asList(includes)); + } + return namedValue; + } + + public default ResourcesExcludesNamedValue excludes(String... excludes) { + ResourcesExcludesNamedValue namedValue = new ResourcesExcludesNamedValue(); + if (excludes != null) { + namedValue.setExcludes(asList(excludes)); + } + return namedValue; + } + + public interface ResourcesNamedValue extends NamedValue {} + + public class ResourcesIncludesNamedValue implements ResourcesNamedValue { + + private List includes = new ArrayList<>(); + + public List getIncludes() { + return includes; + } + + public void setIncludes(List includes) { + this.includes = includes; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class ResourcesExcludesNamedValue implements ResourcesNamedValue { + + private List excludes; + + public List getExcludes() { + return excludes; + } + + public void setExcludes(List excludes) { + this.excludes = excludes; + } + + @Override + public String apply(String str) { + return str; + } + } + + public interface BuildNamedValue extends NamedValue {} + + public interface BuildComplexTypeNamedValue extends BuildNamedValue {} + + public class BuildPluginsNamedValue implements BuildComplexTypeNamedValue { + + private List plugins; + + public List getPlugins() { + return plugins; + } + + public void setPlugins(List plugins) { + this.plugins = plugins; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class PluginManagementNamedValue implements BuildComplexTypeNamedValue { + + private PluginManagement pluginManagement; + + public PluginManagement getPluginManagement() { + return pluginManagement; + } + + public void setPluginManagement(PluginManagement pluginManagement) { + this.pluginManagement = pluginManagement; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class BuildExtensionNamedValue implements BuildComplexTypeNamedValue { + + private List extensions; + + public List getExtensions() { + return extensions; + } + + public void setExtensions(List extensions) { + this.extensions = extensions; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class BuildFiltersNamedValue implements BuildComplexTypeNamedValue { + private List filters; + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class BuildResourcesNamedValue implements BuildComplexTypeNamedValue { + + private List resources; + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } - @Override - public String apply(String str) { - return str; - } - } + @Override + public String apply(String str) { + return str; + } + } - public class BuildTestResourcesNamedValue implements BuildComplexTypeNamedValue { + public class BuildTestResourcesNamedValue implements BuildComplexTypeNamedValue { - private List resources; + private List resources; - public List getResources() { - return resources; - } + public List getResources() { + return resources; + } - public void setResources(List resources) { - this.resources = resources; - } + public void setResources(List resources) { + this.resources = resources; + } - @Override - public String apply(String str) { - return str; - } - } -} \ No newline at end of file + @Override + public String apply(String str) { + return str; + } + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyDTO.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyDTO.java index 63b0c3b2..3b00a73d 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyDTO.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyDTO.java @@ -1,56 +1,55 @@ package org.sonatype.maven.polyglot.java.dsl; import java.util.List; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Exclusion; public class DependencyDTO { - public String groupId; - public String artifactId; - public String version; - public String type = "jar"; - public String classifier; - public String scope; - public String systemPath; - public List exclusions; - public boolean optional = false; - - public Dependency getDependency() { - Dependency dependency = new Dependency(); - - if (groupId != null) { - dependency.setGroupId(groupId); - } - if (artifactId != null) { - dependency.setArtifactId(artifactId); - } - if (version != null) { - dependency.setArtifactId(artifactId); - } - if (type != null) { - dependency.setType(type); - } - if (classifier != null) { - dependency.setClassifier(classifier); - } - if (scope != null) { - dependency.setScope(scope); - } - if (systemPath != null) { - dependency.setSystemPath(systemPath); - } - if (exclusions != null) { - for (String exclusionStr : exclusions) { - String[] parts = exclusionStr.split(":"); - Exclusion exclusion = new Exclusion(); - exclusion.setGroupId(parts[0]); - exclusion.setArtifactId(parts[1]); - dependency.addExclusion(exclusion); - } - } - dependency.setOptional(optional); - - return dependency; - } + public String groupId; + public String artifactId; + public String version; + public String type = "jar"; + public String classifier; + public String scope; + public String systemPath; + public List exclusions; + public boolean optional = false; + + public Dependency getDependency() { + Dependency dependency = new Dependency(); + + if (groupId != null) { + dependency.setGroupId(groupId); + } + if (artifactId != null) { + dependency.setArtifactId(artifactId); + } + if (version != null) { + dependency.setArtifactId(artifactId); + } + if (type != null) { + dependency.setType(type); + } + if (classifier != null) { + dependency.setClassifier(classifier); + } + if (scope != null) { + dependency.setScope(scope); + } + if (systemPath != null) { + dependency.setSystemPath(systemPath); + } + if (exclusions != null) { + for (String exclusionStr : exclusions) { + String[] parts = exclusionStr.split(":"); + Exclusion exclusion = new Exclusion(); + exclusion.setGroupId(parts[0]); + exclusion.setArtifactId(parts[1]); + dependency.addExclusion(exclusion); + } + } + dependency.setOptional(optional); + + return dependency; + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyFactory.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyFactory.java index 6a3830ea..2ebac1e5 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyFactory.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/DependencyFactory.java @@ -5,7 +5,6 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Exclusion; import org.apache.maven.model.Repository; @@ -14,20 +13,20 @@ import org.sonatype.maven.polyglot.java.namedval.NamedValueProcessor; public interface DependencyFactory { - - /** - * Factory method to create dependency. - *
- * Each key-value pair is a construct
- * key -> "value"
- * Where 'key' is the name of the property to set and "value" is it's string value.
- * - * All possible keys are:
- *
    - *
  • groupId - The project group that produced the dependency, e.g. org.apache.maven.
  • - *
  • artifactId - The unique id for an artifact produced by the project group, e.g. maven-artifact.
  • - *
  • version - The version of the dependency, e.g. 3.2.1.
  • - *
  • type - The type of dependency. While it + + /** + * Factory method to create dependency. + *
    + * Each key-value pair is a construct
    + * key -> "value"
    + * Where 'key' is the name of the property to set and "value" is it's string value.
    + * + * All possible keys are:
    + *
      + *
    • groupId - The project group that produced the dependency, e.g. org.apache.maven.
    • + *
    • artifactId - The unique id for an artifact produced by the project group, e.g. maven-artifact.
    • + *
    • version - The version of the dependency, e.g. 3.2.1.
    • + *
    • type - The type of dependency. While it * usually represents the extension on the filename * of the dependency, * that is not always the case. A type can be @@ -44,7 +43,7 @@ public interface DependencyFactory { * New types can be defined by plugins that set * extensions to true, so * this is not a complete list. Default value is "jar"
    • - *
    • classifier - The classifier of the dependency. It is appended + *
    • classifier - The classifier of the dependency. It is appended * to * the filename after the version. This allows: *
        @@ -59,7 +58,7 @@ public interface DependencyFactory { * For example, jdk14 and * jdk15. *
    • - *
    • scope - The scope of the dependency - + *
    • scope - The scope of the dependency - * compile, runtime, * test, system, and * provided. Used to @@ -72,7 +71,7 @@ public interface DependencyFactory { * href="https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html">the * dependency mechanism. The default scope is * compile.
    • - *
    • systemPath - FOR SYSTEM SCOPE ONLY. Note that use of this + *
    • systemPath - FOR SYSTEM SCOPE ONLY. Note that use of this * property is discouraged * and may be replaced in later versions. This * specifies the path on the filesystem @@ -93,172 +92,176 @@ public interface DependencyFactory { * Boolean. Default value is * false.
    • *
    • exclusions - see exmplanation below
    • - *
    - *

    - * In addition to key-value pairs described above you can also you special method to define exclusions: - *

      - *
    • exclusions - List of dependency exclusions. Each individual exclusion can have two properties - groupId and artifactId(optional since you can exclude entire group). - *
      -	 * {@code
      -	 * exclusions(
      -	 * 	exclusion(groupId -> "grpToExclude", artifactId -> "artifactToExclue"),
      -	 * 	exclusion(groupId -> "otherGrpToExclude", artifactId -> "otherArtifactToExclue")
      -	 * )
      -	 * }
      -	 * 
      - *
    • - *
    - * - * @param keyValuePairs - array of key -> "value" pairs. Example: dependency(groupId -> "junit", artifactId -> "junit", version -> "3.8.1", scope -> "test") - * @return defined Dependency - */ - public default Dependency dependency(NamedValue... keyValuePairs) { - - Dependency dependency = new Dependency(); - - Map map = new HashMap<>(); - asList(keyValuePairs).stream().filter(kvp -> kvp != null).filter(kvp -> !(kvp instanceof DependencyExclusions)) - .forEach(kvp -> map.put(kvp.name(), kvp.value())); - NamedValueProcessor.mapToObject(dependency, map); - - asList(keyValuePairs).stream().filter(kvp -> kvp != null).filter(kvp -> (kvp instanceof DependencyExclusions)) - .forEach(excl -> ((DependencyExclusions)excl).getExclusions().forEach(exclusion -> dependency.addExclusion(exclusion))); - - return dependency; - } - - public default Dependency dependency(String definition) { - return dependency(definition, null); - } - - public default Dependency compile(String definition) { - return dependency(definition, "compile"); - } - - public default Dependency provided(String definition) { - return dependency(definition, "provided"); - } - - public default Dependency runtime(String definition) { - return dependency(definition, "runtime"); - } - - public default Dependency test(String definition) { - return dependency(definition, "test"); - } - - public default Dependency dependency(String definition, String scope) { - - Dependency dependency = new Dependency(); - - String[] parts = definition.split(":"); - dependency.setGroupId(parts[0]); - dependency.setArtifactId(parts[1]); - - if (parts.length > 2) { - dependency.setVersion(parts[3]); - } - - if (scope != null) { - dependency.setScope(scope); - } - - return dependency; - } - - public default Repository repository(String id, String name, String url) { - return repository(id, name, url, null, null, null); - } - - /** - * Factory method to create repository. Used for both - "repositories" and "pluginRepositories" - *
    - * Each key-value pair is a construct
    - * key -> "value"
    - * Where 'key' is the name of the property to set and "value" is it's string value.
    - * - * All possible keys are:
    - *
      - *
    • id - A unique identifier for a repository. This is used to match the repository to configuration in the settings.xml file, for example. Furthermore, the identifier is used during POM inheritance and profile injection to detect repositories that should be merged.
    • - *
    • name - Human readable name of the repository.
    • - *
    • url - The url of the repository, in the form protocol://hostname/path
    • - *
    • layout - The type of layout this repository uses for locating and storing artifacts - can be legacy or default
    • - *
    - * @param keyValuePairs - array of key -> "value" pairs. Example: repository(id -> "my-repo", url -> "http://myserver/repo") - * @return defined Repository - */ - public default Repository repository(NamedValue... keyValuePairs) { - Repository repository = new Repository(); - NamedValueProcessor.namedToObject(repository, keyValuePairs); - return repository; - } - - public default Repository repository(String id, String name, String url, String layout, RepositoryPolicy releases, RepositoryPolicy snapshots) { - Repository repository = new Repository(); - if (id != null) { - repository.setId(id); - } - if (name != null) { - repository.setName(name); - } - if (url != null) { - repository.setUrl(url); - } - if (layout != null) { - repository.setLayout(layout); - } - if (releases != null) { - repository.setReleases(releases); - } - if (snapshots != null) { - repository.setSnapshots(snapshots); - } - return repository; - } - - public default RepositoryPolicy repositoryPolicy(boolean enabled, String updatePolicy, String checksumPolicy) { - RepositoryPolicy policy = new RepositoryPolicy(); - policy.setEnabled(enabled); - if (updatePolicy != null) { - policy.setUpdatePolicy(updatePolicy); - } - if (checksumPolicy != null) { - policy.setChecksumPolicy(checksumPolicy); - } - return policy; - } - - public default NamedValue exclusions(Exclusion... exclusions) { - - DependencyExclusions depExclusions = new DependencyExclusions(); - depExclusions.setExclusions(exclusions); - - return depExclusions; - } - - public default Exclusion exclusion(NamedValue... keyValuePairs) { - Exclusion exclusion = new Exclusion(); - return NamedValueProcessor.namedToObject(exclusion, keyValuePairs); - } - - - public class DependencyExclusions implements NamedValue { - - private Exclusion[] exclusions; - - - public Stream getExclusions(){ - return asList(exclusions).stream(); - } - - public void setExclusions(Exclusion[] exclusions) { - this.exclusions = exclusions; - } - - @Override - public String apply(String t) { - return t; - } - - } + *
+ *

+ * In addition to key-value pairs described above you can also you special method to define exclusions: + *

    + *
  • exclusions - List of dependency exclusions. Each individual exclusion can have two properties - groupId and artifactId(optional since you can exclude entire group). + *
    +     * {@code
    +     * exclusions(
    +     * 	exclusion(groupId -> "grpToExclude", artifactId -> "artifactToExclue"),
    +     * 	exclusion(groupId -> "otherGrpToExclude", artifactId -> "otherArtifactToExclue")
    +     * )
    +     * }
    +     * 
    + *
  • + *
+ * + * @param keyValuePairs - array of key -> "value" pairs. Example: dependency(groupId -> "junit", artifactId -> "junit", version -> "3.8.1", scope -> "test") + * @return defined Dependency + */ + public default Dependency dependency(NamedValue... keyValuePairs) { + + Dependency dependency = new Dependency(); + + Map map = new HashMap<>(); + asList(keyValuePairs).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> !(kvp instanceof DependencyExclusions)) + .forEach(kvp -> map.put(kvp.name(), kvp.value())); + NamedValueProcessor.mapToObject(dependency, map); + + asList(keyValuePairs).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> (kvp instanceof DependencyExclusions)) + .forEach(excl -> ((DependencyExclusions) excl) + .getExclusions() + .forEach(exclusion -> dependency.addExclusion(exclusion))); + + return dependency; + } + + public default Dependency dependency(String definition) { + return dependency(definition, null); + } + + public default Dependency compile(String definition) { + return dependency(definition, "compile"); + } + + public default Dependency provided(String definition) { + return dependency(definition, "provided"); + } + + public default Dependency runtime(String definition) { + return dependency(definition, "runtime"); + } + + public default Dependency test(String definition) { + return dependency(definition, "test"); + } + + public default Dependency dependency(String definition, String scope) { + + Dependency dependency = new Dependency(); + + String[] parts = definition.split(":"); + dependency.setGroupId(parts[0]); + dependency.setArtifactId(parts[1]); + + if (parts.length > 2) { + dependency.setVersion(parts[3]); + } + + if (scope != null) { + dependency.setScope(scope); + } + + return dependency; + } + + public default Repository repository(String id, String name, String url) { + return repository(id, name, url, null, null, null); + } + + /** + * Factory method to create repository. Used for both - "repositories" and "pluginRepositories" + *
+ * Each key-value pair is a construct
+ * key -> "value"
+ * Where 'key' is the name of the property to set and "value" is it's string value.
+ * + * All possible keys are:
+ *
    + *
  • id - A unique identifier for a repository. This is used to match the repository to configuration in the settings.xml file, for example. Furthermore, the identifier is used during POM inheritance and profile injection to detect repositories that should be merged.
  • + *
  • name - Human readable name of the repository.
  • + *
  • url - The url of the repository, in the form protocol://hostname/path
  • + *
  • layout - The type of layout this repository uses for locating and storing artifacts - can be legacy or default
  • + *
+ * @param keyValuePairs - array of key -> "value" pairs. Example: repository(id -> "my-repo", url -> "http://myserver/repo") + * @return defined Repository + */ + public default Repository repository(NamedValue... keyValuePairs) { + Repository repository = new Repository(); + NamedValueProcessor.namedToObject(repository, keyValuePairs); + return repository; + } + + public default Repository repository( + String id, String name, String url, String layout, RepositoryPolicy releases, RepositoryPolicy snapshots) { + Repository repository = new Repository(); + if (id != null) { + repository.setId(id); + } + if (name != null) { + repository.setName(name); + } + if (url != null) { + repository.setUrl(url); + } + if (layout != null) { + repository.setLayout(layout); + } + if (releases != null) { + repository.setReleases(releases); + } + if (snapshots != null) { + repository.setSnapshots(snapshots); + } + return repository; + } + + public default RepositoryPolicy repositoryPolicy(boolean enabled, String updatePolicy, String checksumPolicy) { + RepositoryPolicy policy = new RepositoryPolicy(); + policy.setEnabled(enabled); + if (updatePolicy != null) { + policy.setUpdatePolicy(updatePolicy); + } + if (checksumPolicy != null) { + policy.setChecksumPolicy(checksumPolicy); + } + return policy; + } + + public default NamedValue exclusions(Exclusion... exclusions) { + + DependencyExclusions depExclusions = new DependencyExclusions(); + depExclusions.setExclusions(exclusions); + + return depExclusions; + } + + public default Exclusion exclusion(NamedValue... keyValuePairs) { + Exclusion exclusion = new Exclusion(); + return NamedValueProcessor.namedToObject(exclusion, keyValuePairs); + } + + public class DependencyExclusions implements NamedValue { + + private Exclusion[] exclusions; + + public Stream getExclusions() { + return asList(exclusions).stream(); + } + + public void setExclusions(Exclusion[] exclusions) { + this.exclusions = exclusions; + } + + @Override + public String apply(String t) { + return t; + } + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ModelFactory.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ModelFactory.java index 2ec5c722..0c43c223 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ModelFactory.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ModelFactory.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; - import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; @@ -19,213 +18,215 @@ public class ModelFactory implements DependencyFactory, PropertyFactory, BuildFactory { - protected Model model = new Model(); - - protected String modelVersion; - protected String groupId; - protected String artifactId; - protected String version; - protected String packaging; - protected String name; - protected String description; - protected String url; - protected String inceptionYear; - protected String modelEncoding; - - // Field descriptor #98 Lorg/apache/maven/model/Organization; - private org.apache.maven.model.Organization organization; - - // Field descriptor #100 Ljava/util/List; - // Signature: Ljava/util/List; - private java.util.List licenses; - - // Field descriptor #100 Ljava/util/List; - // Signature: Ljava/util/List; - private java.util.List developers; - - // Field descriptor #100 Ljava/util/List; - // Signature: Ljava/util/List; - private java.util.List contributors; - - // Field descriptor #100 Ljava/util/List; - // Signature: Ljava/util/List; - private java.util.List mailingLists; - - // Field descriptor #110 Lorg/apache/maven/model/Prerequisites; - private org.apache.maven.model.Prerequisites prerequisites; - - // Field descriptor #112 Lorg/apache/maven/model/Scm; - private org.apache.maven.model.Scm scm; - - // Field descriptor #114 Lorg/apache/maven/model/IssueManagement; - private org.apache.maven.model.IssueManagement issueManagement; - - // Field descriptor #116 Lorg/apache/maven/model/CiManagement; - private org.apache.maven.model.CiManagement ciManagement; - - // Field descriptor #68 Lorg/apache/maven/model/DistributionManagement; - private org.apache.maven.model.DistributionManagement distributionManagement; - - // Field descriptor #79 Ljava/lang/Object; - private java.lang.Object reports; - - // Field descriptor #81 Lorg/apache/maven/model/Reporting; - private org.apache.maven.model.Reporting reporting; - - public void parent(NamedValue... keyValuePairs) { - Parent parent = new Parent(); - parent = NamedValueProcessor.namedToObject(parent, keyValuePairs); - model.setParent(parent); - } - - public void repositories(Repository... repositories) { - asList(repositories).forEach(repo -> { - model.addRepository(repo); - }); - } - - public void pluginRepositories(Repository... repositories) { - asList(repositories).forEach(repo -> { - model.addPluginRepository(repo); - }); - } - - public void dependencies(Dependency... dependencies) { - asList(dependencies).forEach(dep -> { - model.addDependency(dep); - }); - } - - public void dependencies(Consumer... dependencies) { - if (dependencies != null) { - for (Consumer consumer : Arrays.asList(dependencies)) { - DependencyDTO dto = new DependencyDTO(); - consumer.accept(dto); - model.addDependency(dto.getDependency()); - } - } + protected Model model = new Model(); + + protected String modelVersion; + protected String groupId; + protected String artifactId; + protected String version; + protected String packaging; + protected String name; + protected String description; + protected String url; + protected String inceptionYear; + protected String modelEncoding; + + // Field descriptor #98 Lorg/apache/maven/model/Organization; + private org.apache.maven.model.Organization organization; + + // Field descriptor #100 Ljava/util/List; + // Signature: Ljava/util/List; + private java.util.List licenses; + + // Field descriptor #100 Ljava/util/List; + // Signature: Ljava/util/List; + private java.util.List developers; + + // Field descriptor #100 Ljava/util/List; + // Signature: Ljava/util/List; + private java.util.List contributors; + + // Field descriptor #100 Ljava/util/List; + // Signature: Ljava/util/List; + private java.util.List mailingLists; + + // Field descriptor #110 Lorg/apache/maven/model/Prerequisites; + private org.apache.maven.model.Prerequisites prerequisites; + + // Field descriptor #112 Lorg/apache/maven/model/Scm; + private org.apache.maven.model.Scm scm; + + // Field descriptor #114 Lorg/apache/maven/model/IssueManagement; + private org.apache.maven.model.IssueManagement issueManagement; + + // Field descriptor #116 Lorg/apache/maven/model/CiManagement; + private org.apache.maven.model.CiManagement ciManagement; + + // Field descriptor #68 Lorg/apache/maven/model/DistributionManagement; + private org.apache.maven.model.DistributionManagement distributionManagement; + + // Field descriptor #79 Ljava/lang/Object; + private java.lang.Object reports; + + // Field descriptor #81 Lorg/apache/maven/model/Reporting; + private org.apache.maven.model.Reporting reporting; + + public void parent(NamedValue... keyValuePairs) { + Parent parent = new Parent(); + parent = NamedValueProcessor.namedToObject(parent, keyValuePairs); + model.setParent(parent); + } + + public void repositories(Repository... repositories) { + asList(repositories).forEach(repo -> { + model.addRepository(repo); + }); + } + + public void pluginRepositories(Repository... repositories) { + asList(repositories).forEach(repo -> { + model.addPluginRepository(repo); + }); + } + + public void dependencies(Dependency... dependencies) { + asList(dependencies).forEach(dep -> { + model.addDependency(dep); + }); + } + + public void dependencies(Consumer... dependencies) { + if (dependencies != null) { + for (Consumer consumer : Arrays.asList(dependencies)) { + DependencyDTO dto = new DependencyDTO(); + consumer.accept(dto); + model.addDependency(dto.getDependency()); + } + } + } + + public void dependencyManagement(Dependency... dependencies) { + if (model.getDependencyManagement() == null) { + DependencyManagement dependencyManagement = new DependencyManagement(); + dependencyManagement.setDependencies(new ArrayList()); + model.setDependencyManagement(dependencyManagement); + } + asList(dependencies).forEach(dep -> { + model.getDependencyManagement().addDependency(dep); + }); + } + + public void dependencyManagement(Consumer... dependencies) { + if (model.getDependencyManagement() == null) { + DependencyManagement dependencyManagement = new DependencyManagement(); + dependencyManagement.setDependencies(new ArrayList()); + model.setDependencyManagement(dependencyManagement); + } + if (dependencies != null) { + for (Consumer consumer : Arrays.asList(dependencies)) { + DependencyDTO dto = new DependencyDTO(); + consumer.accept(dto); + model.getDependencyManagement().addDependency(dto.getDependency()); + } + } + } + + public BuildBuilder build() { + return new BuildBuilder(model); + } + + public void modules(String... modules) { + if (modules != null) { + Arrays.asList(modules).forEach(module -> model.addModule(module)); + } + } + + public void build(BuildNamedValue... namedValues) { + Build build = new Build(); + + Map map = new HashMap<>(); + asList(namedValues).stream() + .filter(kvp -> kvp != null) + .filter(kvp -> !(kvp instanceof BuildComplexTypeNamedValue)) + .forEach(kvp -> map.put(kvp.name(), kvp.value())); + NamedValueProcessor.mapToObject(build, map); + + for (BuildNamedValue namedvalue : asList(namedValues)) { + if (namedvalue instanceof BuildPluginsNamedValue) { + build.setPlugins(((BuildPluginsNamedValue) namedvalue).getPlugins()); + } + + if (namedvalue instanceof PluginManagementNamedValue) { + build.setPluginManagement(((PluginManagementNamedValue) namedvalue).getPluginManagement()); + } + + if (namedvalue instanceof BuildExtensionNamedValue) { + build.setExtensions(((BuildExtensionNamedValue) namedvalue).getExtensions()); + } + + if (namedvalue instanceof BuildFiltersNamedValue) { + build.setFilters(((BuildFiltersNamedValue) namedvalue).getFilters()); + } + + if (namedvalue instanceof BuildResourcesNamedValue) { + build.setResources(((BuildResourcesNamedValue) namedvalue).getResources()); + } + + if (namedvalue instanceof BuildTestResourcesNamedValue) { + build.setTestResources(((BuildTestResourcesNamedValue) namedvalue).getResources()); + } + } + + model.setBuild(build); + } + + public void properties(PropertyFactory.Property... properties) { + asList(properties).forEach(prop -> { + model.addProperty(prop.getName(), prop.getValue()); + }); + } + + public ProfileBuilder profile(String id) { + ProfileBuilder builder = new ProfileBuilder(model, id); + return builder; } - public void dependencyManagement(Dependency... dependencies) { - if (model.getDependencyManagement() == null) { - DependencyManagement dependencyManagement = new DependencyManagement(); - dependencyManagement.setDependencies(new ArrayList()); - model.setDependencyManagement(dependencyManagement); - } - asList(dependencies).forEach(dep -> { - model.getDependencyManagement().addDependency(dep); - }); - } - - public void dependencyManagement(Consumer... dependencies) { - if (model.getDependencyManagement() == null) { - DependencyManagement dependencyManagement = new DependencyManagement(); - dependencyManagement.setDependencies(new ArrayList()); - model.setDependencyManagement(dependencyManagement); - } - if (dependencies != null) { - for (Consumer consumer : Arrays.asList(dependencies)) { - DependencyDTO dto = new DependencyDTO(); - consumer.accept(dto); - model.getDependencyManagement().addDependency(dto.getDependency()); - } - } + public void project() {} + + public Model getModel() { + + project(); + + if (modelVersion != null) { + model.setModelVersion(modelVersion); + } + if (groupId != null) { + model.setGroupId(groupId); + } + if (artifactId != null) { + model.setArtifactId(artifactId); + } + if (version != null) { + model.setVersion(version); + } + if (packaging != null) { + model.setPackaging(packaging); + } + if (name != null) { + model.setName(name); + } + if (description != null) { + model.setDescription(description); + } + if (url != null) { + model.setUrl(url); + } + if (inceptionYear != null) { + model.setInceptionYear(inceptionYear); + } + if (modelEncoding != null) { + model.setModelEncoding(modelEncoding); + } + return model; } - - public BuildBuilder build() { - return new BuildBuilder(model); - } - - public void modules(String... modules) { - if (modules != null) { - Arrays.asList(modules).forEach(module -> model.addModule(module)); - } - } - - public void build(BuildNamedValue... namedValues) { - Build build = new Build(); - - Map map = new HashMap<>(); - asList(namedValues).stream().filter(kvp -> kvp != null).filter(kvp -> !(kvp instanceof BuildComplexTypeNamedValue)) - .forEach(kvp -> map.put(kvp.name(), kvp.value())); - NamedValueProcessor.mapToObject(build, map); - - for (BuildNamedValue namedvalue : asList(namedValues)) { - if (namedvalue instanceof BuildPluginsNamedValue) { - build.setPlugins(((BuildPluginsNamedValue)namedvalue).getPlugins()); - } - - if (namedvalue instanceof PluginManagementNamedValue) { - build.setPluginManagement(((PluginManagementNamedValue)namedvalue).getPluginManagement()); - } - - if (namedvalue instanceof BuildExtensionNamedValue) { - build.setExtensions(((BuildExtensionNamedValue)namedvalue).getExtensions()); - } - - if (namedvalue instanceof BuildFiltersNamedValue) { - build.setFilters(((BuildFiltersNamedValue)namedvalue).getFilters()); - } - - if (namedvalue instanceof BuildResourcesNamedValue) { - build.setResources(((BuildResourcesNamedValue)namedvalue).getResources()); - } - - if (namedvalue instanceof BuildTestResourcesNamedValue) { - build.setTestResources(((BuildTestResourcesNamedValue)namedvalue).getResources()); - } - } - - model.setBuild(build); - } - - public void properties(PropertyFactory.Property... properties) { - asList(properties).forEach(prop -> { - model.addProperty(prop.getName(), prop.getValue()); - }); - } - - public ProfileBuilder profile(String id) { - ProfileBuilder builder = new ProfileBuilder(model, id); - return builder; - } - - public void project() {} - - public Model getModel() { - - project(); - - if (modelVersion != null) { - model.setModelVersion(modelVersion); - } - if (groupId != null) { - model.setGroupId(groupId); - } - if (artifactId != null) { - model.setArtifactId(artifactId); - } - if (version != null) { - model.setVersion(version); - } - if (packaging != null) { - model.setPackaging(packaging); - } - if (name != null) { - model.setName(name); - } - if (description != null) { - model.setDescription(description); - } - if (url != null) { - model.setUrl(url); - } - if (inceptionYear != null) { - model.setInceptionYear(inceptionYear); - } - if (modelEncoding != null) { - model.setModelEncoding(modelEncoding); - } - return model; - } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginBuilder.java index 606a1c74..dd585c7c 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginBuilder.java @@ -2,94 +2,93 @@ import java.util.ArrayList; import java.util.Arrays; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; public class PluginBuilder { - - private Plugin plugin; - + + private Plugin plugin; + public PluginBuilder(String groupId, String artifactId, String version) { - plugin = new Plugin(); - plugin.setGroupId(groupId); - plugin.setArtifactId(artifactId); - plugin.setVersion(version); + plugin = new Plugin(); + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + plugin.setVersion(version); } - + public PluginBuilder(String groupId, String artifactId) { - plugin = new Plugin(); - plugin.setGroupId(groupId); - plugin.setArtifactId(artifactId); + plugin = new Plugin(); + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); } - + public PluginBuilder(String classifier) { - plugin = new Plugin(); - String[] parts = classifier.split(":"); - if (parts.length == 2) { - plugin.setGroupId(parts[0]); - plugin.setArtifactId(parts[1]); - } else if (parts.length == 3) { - plugin.setVersion(parts[2]); - } + plugin = new Plugin(); + String[] parts = classifier.split(":"); + if (parts.length == 2) { + plugin.setGroupId(parts[0]); + plugin.setArtifactId(parts[1]); + } else if (parts.length == 3) { + plugin.setVersion(parts[2]); + } } - + public PluginBuilder configuration(Xpp3Dom configuration) { - if (configuration != null) { - plugin.setConfiguration(configuration); - } - return this; + if (configuration != null) { + plugin.setConfiguration(configuration); + } + return this; } - + public PluginBuilder extensions(boolean extensions) { - plugin.setExtensions(extensions); - return this; + plugin.setExtensions(extensions); + return this; } - + public PluginBuilder inherited(boolean inherited) { - plugin.setInherited(inherited); - return this; + plugin.setInherited(inherited); + return this; } public PluginBuilder dependencies(Dependency... dependencies) { - if (dependencies != null) { - plugin.setDependencies(Arrays.asList(dependencies)); - } - return this; - } - + if (dependencies != null) { + plugin.setDependencies(Arrays.asList(dependencies)); + } + return this; + } + public PluginBuilder executions(PluginExecutionBuilder... builders) { - if (builders != null) { - for (PluginExecutionBuilder executionBuilder : Arrays.asList(builders)) { - if (plugin.getExecutions() == null) { - plugin.setExecutions(new ArrayList<>()); - } - plugin.addExecution((executionBuilder.get())); - } - } - return this; - } - + if (builders != null) { + for (PluginExecutionBuilder executionBuilder : Arrays.asList(builders)) { + if (plugin.getExecutions() == null) { + plugin.setExecutions(new ArrayList<>()); + } + plugin.addExecution((executionBuilder.get())); + } + } + return this; + } + public PluginBuilder endPlugin() { - return this; + return this; + } + + public Plugin get() { + return plugin; + } + + public static class WrapperPluginBuilder extends PluginBuilder { + private Plugin plugin; + + public WrapperPluginBuilder(Plugin plugin) { + super(null, null); + this.plugin = plugin; + } + + @Override + public Plugin get() { + return plugin; + } } - - public Plugin get() { - return plugin; - } - - static public class WrapperPluginBuilder extends PluginBuilder { - private Plugin plugin; - - public WrapperPluginBuilder(Plugin plugin) { - super(null, null); - this.plugin = plugin; - } - - @Override - public Plugin get() { - return plugin; - } - } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginExecutionBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginExecutionBuilder.java index edf88842..a72fe9c9 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginExecutionBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginExecutionBuilder.java @@ -1,104 +1,101 @@ package org.sonatype.maven.polyglot.java.dsl; import java.util.Arrays; - import org.apache.maven.model.PluginExecution; import org.codehaus.plexus.util.xml.Xpp3Dom; public class PluginExecutionBuilder { - - private String id = "default"; + + private String id = "default"; private String phase; private int priority = 0; private java.util.List goals; private Xpp3Dom configuration; private boolean inherited = true; - + public PluginExecutionBuilder(String id) { - super(); - this.id = id; - } - + super(); + this.id = id; + } + public PluginExecutionBuilder(String id, String phase) { - super(); - this.id = id; - this.phase = phase; - } - + super(); + this.id = id; + this.phase = phase; + } + public PluginExecutionBuilder(String phase, int priority) { - super(); - this.phase = phase; - this.priority = priority; - } - - public PluginExecutionBuilder(String id, String phase, int priority) { - super(); - this.id = id; - this.phase = phase; - this.priority = priority; - } - - public PluginExecutionBuilder phase(String phase) { - this.phase = phase; - return this; - } - - public PluginExecutionBuilder priority(int priority) { - this.priority = priority; - return this; - } - + super(); + this.phase = phase; + this.priority = priority; + } + + public PluginExecutionBuilder(String id, String phase, int priority) { + super(); + this.id = id; + this.phase = phase; + this.priority = priority; + } + + public PluginExecutionBuilder phase(String phase) { + this.phase = phase; + return this; + } + + public PluginExecutionBuilder priority(int priority) { + this.priority = priority; + return this; + } + public PluginExecutionBuilder goals(String... goals) { - if (goals != null) { - this.goals = Arrays.asList(goals); - } - return this; + if (goals != null) { + this.goals = Arrays.asList(goals); + } + return this; } - + public PluginExecutionBuilder configuration(Xpp3Dom configuration) { - if (configuration != null) { - this.configuration = configuration; - } - return this; + if (configuration != null) { + this.configuration = configuration; + } + return this; } - + public PluginExecutionBuilder inherited(boolean inherited) { - this.inherited = inherited; - return this; + this.inherited = inherited; + return this; } - + public PluginExecution get() { - PluginExecution execution = new PluginExecution(); - - if (configuration != null) { - execution.setConfiguration(configuration); - } - if (goals != null) { - execution.setGoals(goals); - } - execution.setId(id); - execution.setInherited(inherited); - execution.setPhase(phase); - execution.setPriority(priority); - - return execution; + PluginExecution execution = new PluginExecution(); + + if (configuration != null) { + execution.setConfiguration(configuration); + } + if (goals != null) { + execution.setGoals(goals); + } + execution.setId(id); + execution.setInherited(inherited); + execution.setPhase(phase); + execution.setPriority(priority); + + return execution; } - + public static class WrapperPluginExecutionBuilder extends PluginExecutionBuilder { - private PluginExecution pluginExecution; - - public WrapperPluginExecutionBuilder(PluginExecution pluginExecution) { - super(null); - - this.pluginExecution = pluginExecution; - } - - @Override - public PluginExecution get() { - return pluginExecution; - } - } -} + private PluginExecution pluginExecution; + public WrapperPluginExecutionBuilder(PluginExecution pluginExecution) { + super(null); + this.pluginExecution = pluginExecution; + } + + @Override + public PluginExecution get() { + return pluginExecution; + } + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginFactory.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginFactory.java index 412d1ac8..dc547b60 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginFactory.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PluginFactory.java @@ -6,7 +6,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -18,185 +17,181 @@ import org.sonatype.maven.polyglot.java.xml.ConfiugrationXmlBuilder; public interface PluginFactory extends DependencyFactory { - - public default PluginExecutionBuilder execution(String id) { - return new PluginExecutionBuilder(id); - } - - public default PluginExecutionBuilder execution(String id, String phase) { - return new PluginExecutionBuilder(id, phase); - } - - public default PluginExecutionBuilder execution(String phase, int priority) { - return new PluginExecutionBuilder(phase, priority); - } - - public default PluginExecutionBuilder execution(String id, String phase, int priority) { - return new PluginExecutionBuilder(id, phase, priority); - } - - public default PluginBuilder plugin(String groupId, String artifactId, String version) { - return new PluginBuilder(groupId, artifactId, version); - } - - public default PluginBuilder plugin(String groupId, String artifactId) { - return new PluginBuilder(groupId, artifactId); - } - - public default PluginBuilder plugin(String classifier) { - return new PluginBuilder(classifier); - } - + + public default PluginExecutionBuilder execution(String id) { + return new PluginExecutionBuilder(id); + } + + public default PluginExecutionBuilder execution(String id, String phase) { + return new PluginExecutionBuilder(id, phase); + } + + public default PluginExecutionBuilder execution(String phase, int priority) { + return new PluginExecutionBuilder(phase, priority); + } + + public default PluginExecutionBuilder execution(String id, String phase, int priority) { + return new PluginExecutionBuilder(id, phase, priority); + } + + public default PluginBuilder plugin(String groupId, String artifactId, String version) { + return new PluginBuilder(groupId, artifactId, version); + } + + public default PluginBuilder plugin(String groupId, String artifactId) { + return new PluginBuilder(groupId, artifactId); + } + + public default PluginBuilder plugin(String classifier) { + return new PluginBuilder(classifier); + } + public default PluginExecutionGoalsNamedValue goals(String... goals) { - if (goals != null) { - PluginExecutionGoalsNamedValue container = new PluginExecutionGoalsNamedValue(); - container.setGoals(Arrays.asList(goals)); - return container; - } - return null; - } - - public default WrapperPluginBuilder plugin(PluginNamedValue... namedValues) { - Plugin plugin = new Plugin(); - - Map map = new HashMap<>(); - for (PluginNamedValue kvp : namedValues) { - if (kvp instanceof ConfigurationNamedValue) { - plugin.setConfiguration(((ConfigurationNamedValue)kvp).getConfiguration()); - } else if (kvp instanceof ExecutionsNamedValue) { - plugin.setExecutions(((ExecutionsNamedValue)kvp).getExecutions()); - } else if (kvp instanceof DependenciesNamedValue) { - plugin.setDependencies(((DependenciesNamedValue)kvp).getDependencies()); - } else { - map.put(kvp.name(), kvp.value()); - NamedValueProcessor.mapToObject(plugin, map); - } - } - - return new WrapperPluginBuilder(plugin); - } - - public interface PluginNamedValue extends NamedValue { - - } - - public interface PluginExecutionNamedValue extends NamedValue { - - } - - public default PluginNamedValue pluginDependencies(Dependency... dependencies) { - - DependenciesNamedValue deps = new DependenciesNamedValue(); - deps.setDependencies(asList(dependencies)); - return deps; - } - - public default PluginNamedValue executions(PluginExecution... executions) { - - ExecutionsNamedValue exec = new ExecutionsNamedValue(); - exec.setExecutions(asList(executions)); - return exec; - } - - public default WrapperPluginExecutionBuilder execution(PluginExecutionNamedValue... namedValues) { - PluginExecution execution = new PluginExecution(); - - Map map = new HashMap<>(); - for (PluginExecutionNamedValue kvp : namedValues) { - if (kvp instanceof ConfigurationNamedValue) { - execution.setConfiguration(((ConfigurationNamedValue) kvp).getConfiguration()); - } else if (kvp instanceof PluginExecutionGoalsNamedValue) { - execution.setGoals(((PluginExecutionGoalsNamedValue)kvp).getGoals()); - } else { - map.put(kvp.name(), kvp.value()); - NamedValueProcessor.mapToObject(execution, map); - } - } - - return new WrapperPluginExecutionBuilder(execution); - } - - public default ConfiugrationXmlBuilder startXML() { - return new ConfiugrationXmlBuilder().startXML(); - } - - public default ConfigurationNamedValue configuration(Xpp3Dom configuration) { - - ConfigurationNamedValue conf = new ConfigurationNamedValue(); - conf.setConfiguration(configuration); - - return conf; - } - - public class PluginExecutionGoalsNamedValue implements PluginExecutionNamedValue { - - private List goals; - - public List getGoals() { - return goals; - } - - public void setGoals(List goals) { - this.goals = goals; - } - - @Override - public String apply(String str) { - return str; - } - } - - public class ConfigurationNamedValue implements PluginNamedValue, PluginExecutionNamedValue { - - private Xpp3Dom configuration; - - public Xpp3Dom getConfiguration() { - return configuration; - } - - public void setConfiguration(Xpp3Dom configuration) { - this.configuration = configuration; - } - - @Override - public String apply(String t) { - return t; - } - } - - public class ExecutionsNamedValue implements PluginNamedValue { - - private List executions; - - public List getExecutions() { - return executions; - } - - public void setExecutions(List executions) { - this.executions = executions; - } - - @Override - public String apply(String t) { - return t; - } - } - - public class DependenciesNamedValue implements PluginNamedValue { - - private List dependencies; - - public List getDependencies() { - return dependencies; - } - - public void setDependencies(List dependencies) { - this.dependencies = dependencies; - } - - @Override - public String apply(String t) { - return t; - } - } + if (goals != null) { + PluginExecutionGoalsNamedValue container = new PluginExecutionGoalsNamedValue(); + container.setGoals(Arrays.asList(goals)); + return container; + } + return null; + } + + public default WrapperPluginBuilder plugin(PluginNamedValue... namedValues) { + Plugin plugin = new Plugin(); + + Map map = new HashMap<>(); + for (PluginNamedValue kvp : namedValues) { + if (kvp instanceof ConfigurationNamedValue) { + plugin.setConfiguration(((ConfigurationNamedValue) kvp).getConfiguration()); + } else if (kvp instanceof ExecutionsNamedValue) { + plugin.setExecutions(((ExecutionsNamedValue) kvp).getExecutions()); + } else if (kvp instanceof DependenciesNamedValue) { + plugin.setDependencies(((DependenciesNamedValue) kvp).getDependencies()); + } else { + map.put(kvp.name(), kvp.value()); + NamedValueProcessor.mapToObject(plugin, map); + } + } + + return new WrapperPluginBuilder(plugin); + } + + public interface PluginNamedValue extends NamedValue {} + + public interface PluginExecutionNamedValue extends NamedValue {} + + public default PluginNamedValue pluginDependencies(Dependency... dependencies) { + + DependenciesNamedValue deps = new DependenciesNamedValue(); + deps.setDependencies(asList(dependencies)); + return deps; + } + + public default PluginNamedValue executions(PluginExecution... executions) { + + ExecutionsNamedValue exec = new ExecutionsNamedValue(); + exec.setExecutions(asList(executions)); + return exec; + } + + public default WrapperPluginExecutionBuilder execution(PluginExecutionNamedValue... namedValues) { + PluginExecution execution = new PluginExecution(); + + Map map = new HashMap<>(); + for (PluginExecutionNamedValue kvp : namedValues) { + if (kvp instanceof ConfigurationNamedValue) { + execution.setConfiguration(((ConfigurationNamedValue) kvp).getConfiguration()); + } else if (kvp instanceof PluginExecutionGoalsNamedValue) { + execution.setGoals(((PluginExecutionGoalsNamedValue) kvp).getGoals()); + } else { + map.put(kvp.name(), kvp.value()); + NamedValueProcessor.mapToObject(execution, map); + } + } + + return new WrapperPluginExecutionBuilder(execution); + } + + public default ConfiugrationXmlBuilder startXML() { + return new ConfiugrationXmlBuilder().startXML(); + } + + public default ConfigurationNamedValue configuration(Xpp3Dom configuration) { + + ConfigurationNamedValue conf = new ConfigurationNamedValue(); + conf.setConfiguration(configuration); + + return conf; + } + + public class PluginExecutionGoalsNamedValue implements PluginExecutionNamedValue { + + private List goals; + + public List getGoals() { + return goals; + } + + public void setGoals(List goals) { + this.goals = goals; + } + + @Override + public String apply(String str) { + return str; + } + } + + public class ConfigurationNamedValue implements PluginNamedValue, PluginExecutionNamedValue { + + private Xpp3Dom configuration; + + public Xpp3Dom getConfiguration() { + return configuration; + } + + public void setConfiguration(Xpp3Dom configuration) { + this.configuration = configuration; + } + + @Override + public String apply(String t) { + return t; + } + } + + public class ExecutionsNamedValue implements PluginNamedValue { + + private List executions; + + public List getExecutions() { + return executions; + } + + public void setExecutions(List executions) { + this.executions = executions; + } + + @Override + public String apply(String t) { + return t; + } + } + + public class DependenciesNamedValue implements PluginNamedValue { + + private List dependencies; + + public List getDependencies() { + return dependencies; + } + + public void setDependencies(List dependencies) { + this.dependencies = dependencies; + } + + @Override + public String apply(String t) { + return t; + } + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ProfileBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ProfileBuilder.java index bedcf4e8..a528f5fb 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ProfileBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ProfileBuilder.java @@ -3,7 +3,6 @@ import static java.util.Arrays.asList; import java.util.Arrays; - import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationFile; import org.apache.maven.model.ActivationOS; @@ -18,129 +17,130 @@ public class ProfileBuilder { - private Model model; - - private String id = "default"; - - /** - * not covered yet - */ - private BuildBase build; - private DistributionManagement distributionManagement; - private ActivationOS os; // probably will not support this for activation - - public ProfileBuilder(Model model, String id) { - super(); - this.model = model; - this.id = id; - } - - public ProfileBuilder modules(String... modules) { - if (modules != null) { - getProfile().setModules(Arrays.asList(modules)); - } - return this; - } - - public ProfileBuilder dependencies(Dependency... dependencies) { - if (dependencies != null) { - getProfile().setDependencies(Arrays.asList(dependencies)); - } - return this; - } - - public ProfileBuilder dependencyManagement(Dependency... dependencies) { - if (dependencies != null) { - DependencyManagement dependencyManagement = new DependencyManagement(); - dependencyManagement.setDependencies(Arrays.asList(dependencies)); - getProfile().setDependencyManagement(dependencyManagement); - } - return this; - } - - public ProfileBuilder repositories(Repository... repositories) { - if (repositories != null) { - getProfile().setRepositories(Arrays.asList(repositories)); - } - return this; - } - - public ProfileBuilder pluginRepositories(Repository... pluginRepositories) { - if (pluginRepositories != null) { - getProfile().setPluginRepositories(Arrays.asList(pluginRepositories)); - } - return this; - } - - public ProfileBuilder properties(PropertyFactory.Property... properties) { - if (properties != null) { - asList(properties).forEach(prop -> { - getProfile().addProperty(prop.getName(), prop.getValue()); - }); - } - return this; - } - - public ProfileBuilder activeByDefault(boolean activeByDefault) { - getActivation().setActiveByDefault(activeByDefault); - return this; - } - - public ProfileBuilder activeForJDK(String jdk) { - getActivation().setJdk(jdk); - return this; - } - - public ProfileBuilder activeForPropertyValue(String name, String value) { - ActivationProperty activationProperty = new ActivationProperty(); - activationProperty.setName(name); - activationProperty.setValue(value); - getActivation().setProperty(activationProperty); - return this; - } - - public ProfileBuilder activeForFile(String exists, String missing) { - ActivationFile activationFile = new ActivationFile(); - if (exists != null) { - activationFile.setExists(exists); - } - if (missing != null) { - activationFile.setMissing(missing); - } - getActivation().setFile(activationFile); - return this; - } - - public ProfileBuilder build(BuildBaseBuilder buildBaseBuilder) { - if (buildBaseBuilder != null) { - build = buildBaseBuilder.get(); - } - return this; - } - - private Activation getActivation() { - if (getProfile().getActivation() == null) { - getProfile().setActivation(new Activation()); - } - return getProfile().getActivation(); - } - - public ProfileBuilder endProfile() { - return this; - } - - private Profile getProfile() { - if (model.getProfiles() != null) { - for (Profile profile : model.getProfiles()) { - if (profile.getId().equals(id)) { - return profile; - } - } - } - - Profile profile = new Profile(); - profile.setId(id); - model.addProfile(profile); - return profile; - } + private Model model; + + private String id = "default"; + + /** + * not covered yet + */ + private BuildBase build; + + private DistributionManagement distributionManagement; + private ActivationOS os; // probably will not support this for activation + + public ProfileBuilder(Model model, String id) { + super(); + this.model = model; + this.id = id; + } + + public ProfileBuilder modules(String... modules) { + if (modules != null) { + getProfile().setModules(Arrays.asList(modules)); + } + return this; + } + + public ProfileBuilder dependencies(Dependency... dependencies) { + if (dependencies != null) { + getProfile().setDependencies(Arrays.asList(dependencies)); + } + return this; + } + + public ProfileBuilder dependencyManagement(Dependency... dependencies) { + if (dependencies != null) { + DependencyManagement dependencyManagement = new DependencyManagement(); + dependencyManagement.setDependencies(Arrays.asList(dependencies)); + getProfile().setDependencyManagement(dependencyManagement); + } + return this; + } + + public ProfileBuilder repositories(Repository... repositories) { + if (repositories != null) { + getProfile().setRepositories(Arrays.asList(repositories)); + } + return this; + } + + public ProfileBuilder pluginRepositories(Repository... pluginRepositories) { + if (pluginRepositories != null) { + getProfile().setPluginRepositories(Arrays.asList(pluginRepositories)); + } + return this; + } + + public ProfileBuilder properties(PropertyFactory.Property... properties) { + if (properties != null) { + asList(properties).forEach(prop -> { + getProfile().addProperty(prop.getName(), prop.getValue()); + }); + } + return this; + } + + public ProfileBuilder activeByDefault(boolean activeByDefault) { + getActivation().setActiveByDefault(activeByDefault); + return this; + } + + public ProfileBuilder activeForJDK(String jdk) { + getActivation().setJdk(jdk); + return this; + } + + public ProfileBuilder activeForPropertyValue(String name, String value) { + ActivationProperty activationProperty = new ActivationProperty(); + activationProperty.setName(name); + activationProperty.setValue(value); + getActivation().setProperty(activationProperty); + return this; + } + + public ProfileBuilder activeForFile(String exists, String missing) { + ActivationFile activationFile = new ActivationFile(); + if (exists != null) { + activationFile.setExists(exists); + } + if (missing != null) { + activationFile.setMissing(missing); + } + getActivation().setFile(activationFile); + return this; + } + + public ProfileBuilder build(BuildBaseBuilder buildBaseBuilder) { + if (buildBaseBuilder != null) { + build = buildBaseBuilder.get(); + } + return this; + } + + private Activation getActivation() { + if (getProfile().getActivation() == null) { + getProfile().setActivation(new Activation()); + } + return getProfile().getActivation(); + } + + public ProfileBuilder endProfile() { + return this; + } + + private Profile getProfile() { + if (model.getProfiles() != null) { + for (Profile profile : model.getProfiles()) { + if (profile.getId().equals(id)) { + return profile; + } + } + } + + Profile profile = new Profile(); + profile.setId(id); + model.addProfile(profile); + return profile; + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PropertyFactory.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PropertyFactory.java index 862b5831..0a6f9b96 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PropertyFactory.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/PropertyFactory.java @@ -3,46 +3,49 @@ import org.sonatype.maven.polyglot.java.namedval.NamedValue; public interface PropertyFactory { - - public default Property property(String name, String value) { - Property property = new Property(); - property.name = name; - property.value = value; - return property; - } - - /** - * Factory method to define property. - *
- * Key-value pair is a construct
- * key -> "value"
- * Where 'key' is the name of the property to set and "value" is it's string value.
- * - * @param keyValuePair - combination of key -> "value" pairs. Example: property(name1 -> "property_1") - * @return defined property - */ - public default Property property(NamedValue keyValuePair) { - Property property = new Property(); - property.name = keyValuePair.name(); - property.value = keyValuePair.value(); - return property; - } - - public class Property { - private String name; - private String value; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } - } + + public default Property property(String name, String value) { + Property property = new Property(); + property.name = name; + property.value = value; + return property; + } + + /** + * Factory method to define property. + *
+ * Key-value pair is a construct
+ * key -> "value"
+ * Where 'key' is the name of the property to set and "value" is it's string value.
+ * + * @param keyValuePair - combination of key -> "value" pairs. Example: property(name1 -> "property_1") + * @return defined property + */ + public default Property property(NamedValue keyValuePair) { + Property property = new Property(); + property.name = keyValuePair.name(); + property.value = keyValuePair.value(); + return property; + } + + public class Property { + private String name; + private String value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceBuilder.java index 68b2aeb8..ddb752d8 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceBuilder.java @@ -1,49 +1,48 @@ package org.sonatype.maven.polyglot.java.dsl; import java.util.Arrays; - import org.apache.maven.model.Resource; public class ResourceBuilder { - - private Resource resource = new Resource(); - + + private Resource resource = new Resource(); + public ResourceBuilder directory(String directory) { - if (directory != null) { - resource.setDirectory(directory); - } - return this; + if (directory != null) { + resource.setDirectory(directory); + } + return this; } - + public ResourceBuilder targetPath(String targetPath) { - if (targetPath != null) { - resource.setTargetPath(targetPath); - } - return this; + if (targetPath != null) { + resource.setTargetPath(targetPath); + } + return this; } - + public ResourceBuilder filtering(boolean filtering) { - resource.setFiltering(filtering); - return this; + resource.setFiltering(filtering); + return this; } - + public ResourceBuilder includes(String... includes) { - if (includes != null) { - resource.setIncludes(Arrays.asList(includes)); - } - - return this; + if (includes != null) { + resource.setIncludes(Arrays.asList(includes)); + } + + return this; } - + public ResourceBuilder excludes(String... excludes) { - if (excludes != null) { - resource.setExcludes(Arrays.asList(excludes)); - } - - return this; + if (excludes != null) { + resource.setExcludes(Arrays.asList(excludes)); + } + + return this; } - + public Resource endResource() { - return resource; + return resource; } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceDTO.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceDTO.java index 4786792a..51f498fe 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceDTO.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/dsl/ResourceDTO.java @@ -1,34 +1,33 @@ package org.sonatype.maven.polyglot.java.dsl; import java.util.Arrays; - import org.apache.maven.model.Resource; public class ResourceDTO { - public String targetPath; - public boolean filtering = false; - public String directory; - public String includes; - public String excludes; - - public Resource getResource() { - Resource resource = new Resource(); - - if (targetPath != null) { - resource.setTargetPath(targetPath); - } - resource.setFiltering(filtering); - - if (directory != null) { - resource.setDirectory(directory); - } - if (includes != null) { - resource.setIncludes(Arrays.asList(includes.split(","))); - } - if (excludes != null) { - resource.setExcludes(Arrays.asList(excludes.split(","))); - } - - return resource; - } + public String targetPath; + public boolean filtering = false; + public String directory; + public String includes; + public String excludes; + + public Resource getResource() { + Resource resource = new Resource(); + + if (targetPath != null) { + resource.setTargetPath(targetPath); + } + resource.setFiltering(filtering); + + if (directory != null) { + resource.setDirectory(directory); + } + if (includes != null) { + resource.setIncludes(Arrays.asList(includes.split(","))); + } + if (excludes != null) { + resource.setExcludes(Arrays.asList(excludes.split(","))); + } + + return resource; + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/DefaultValue.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/DefaultValue.java index 706fc705..4f08a600 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/DefaultValue.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/DefaultValue.java @@ -5,17 +5,18 @@ public class DefaultValue { private static Map, Object> defaultValues = new HashMap<>(); + static { defaultValues.put(int.class, 0); defaultValues.put(Integer.class, 0); defaultValues.put(boolean.class, false); defaultValues.put(Boolean.class, false); - defaultValues.put(byte.class, (byte)0); + defaultValues.put(byte.class, (byte) 0); defaultValues.put(Byte.class, 0); defaultValues.put(char.class, ' '); defaultValues.put(Character.class, ' '); - defaultValues.put(short.class, (short)0.0); - defaultValues.put(Short.class, (short)0.0); + defaultValues.put(short.class, (short) 0.0); + defaultValues.put(Short.class, (short) 0.0); defaultValues.put(long.class, 0l); defaultValues.put(Long.class, 0L); defaultValues.put(float.class, 0.0f); diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/MethodFinder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/MethodFinder.java index dc916b2c..65d1c7ff 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/MethodFinder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/MethodFinder.java @@ -1,13 +1,13 @@ package org.sonatype.maven.polyglot.java.namedval; +import static java.util.Arrays.asList; + import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Objects; -import static java.util.Arrays.asList; - public interface MethodFinder extends Serializable { default SerializedLambda serialized() { try { @@ -31,8 +31,7 @@ default Class getContainingClass() { default Method method() { SerializedLambda lambda = serialized(); Class containingClass = getContainingClass(); - return asList(containingClass.getDeclaredMethods()) - .stream() + return asList(containingClass.getDeclaredMethods()).stream() .filter(method -> Objects.equals(method.getName(), lambda.getImplMethodName())) .findFirst() .orElseThrow(UnableToGuessMethodException::new); diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValue.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValue.java index c0e8ff40..a4f698b6 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValue.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValue.java @@ -8,9 +8,11 @@ default String name() { checkParametersEnabled(); return parameter(0).getName(); } + default void checkParametersEnabled() { if (Objects.equals("arg0", parameter(0).getName())) { - throw new IllegalStateException("You need to compile with javac -parameters for parameter reflection to work; You also need java 8u60 or newer to use it with lambdas"); + throw new IllegalStateException( + "You need to compile with javac -parameters for parameter reflection to work; You also need java 8u60 or newer to use it with lambdas"); } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValueProcessor.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValueProcessor.java index 85b4d25c..b50aa4c6 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValueProcessor.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/namedval/NamedValueProcessor.java @@ -4,28 +4,26 @@ import java.util.HashMap; import java.util.Map; - import org.apache.commons.beanutils.BeanMap; public class NamedValueProcessor { - public static Map namedToMap(NamedValue[] keyValuePairs) { - Map map = new HashMap<>(); - asList(keyValuePairs).stream().filter(kvp -> kvp != null) - .forEach(kvp -> map.put(kvp.name(), kvp.value())); - - return map; - } - - public static E namedToObject(E entity, NamedValue[] keyValuePairs) { - BeanMap beanMap = new BeanMap(entity); - beanMap.putAll(namedToMap(keyValuePairs)); - return entity; - } - - public static E mapToObject(E entity, Map map) { - BeanMap beanMap = new BeanMap(entity); - beanMap.putAll(map); - return entity; - } + public static Map namedToMap(NamedValue[] keyValuePairs) { + Map map = new HashMap<>(); + asList(keyValuePairs).stream().filter(kvp -> kvp != null).forEach(kvp -> map.put(kvp.name(), kvp.value())); + + return map; + } + + public static E namedToObject(E entity, NamedValue[] keyValuePairs) { + BeanMap beanMap = new BeanMap(entity); + beanMap.putAll(namedToMap(keyValuePairs)); + return entity; + } + + public static E mapToObject(E entity, Map map) { + BeanMap beanMap = new BeanMap(entity); + beanMap.putAll(map); + return entity; + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest.java index 13db88a2..c73de471 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest.java @@ -1,185 +1,150 @@ package org.sonatype.maven.polyglot.java.test; import java.util.Arrays; - import org.apache.maven.model.Resource; import org.sonatype.maven.polyglot.java.dsl.ModelFactory; public class ModelTest extends ModelFactory { - - @SuppressWarnings({ "unchecked"}) - public void project() { - - modelVersion = "4.0"; - groupId = "my-grp"; - artifactId = "my-art"; - version = "1.0"; - - parent( - artifactId -> "artf_id", - version -> "v1", - relativePath -> "../..", - groupId -> "grp-id-1" - ); - - dependencies( - dep -> {dep.groupId = "grpid1"; dep.artifactId = "art1";}, - dep -> {dep.groupId = "grpid2"; dep.artifactId = "art2"; dep.version = "1.0"; dep.exclusions = Arrays.asList("exclgr1:artifact1", "exclgr2:art2"); } - ); - - dependencies( - dependency( - groupId -> "dep1grp", - artifactId -> "art2", - exclusions( - exclusion(groupId -> "grpToExclude", artifactId -> "artifactToExclue") - ), - version -> "v2" - ), - dependency(groupId -> "gr2", artifactId -> "art3"), - test("org.junit:junit") - ); - - repositories( - repository(id -> "my-repo", url -> "http://myserver/repo") - ); - - build( - artifactId -> "artf_id", - version -> "v1", - plugins( - plugin( - artifactId -> "org.apache.maven.plugins", - groupId -> "maven-jar-plugin", - version -> "2.6", - - configuration( - startXML() - .tag("classifier", tag -> tag.content("pre-process")) - .endXML() - ), - - executions( - execution( - id -> "pre-process-classes", - phase -> "pre-process", - configuration( - startXML() - .tag("classifier", tag -> tag.content("pre-process")) - .endXML() - ) - ).get() - ), - - pluginDependencies( - dependency( - artifactId -> "org.apache.maven.plugins", - groupId -> "maven-jar-plugin", - version -> "2.6" - ) - ) - ).get() - ), - resources( - resource( - targetPath -> "d:/", - filtering -> "true" - ) - ), - testResources((Resource[]) null) - ); - - - - build() - - .resources( - res -> {res.directory="c://foodir"; res.filtering=true; res.targetPath="c://bardir"; res.includes="*.a"; res.excludes="*.b";}, - res -> {res.directory="src/main/resources"; res.filtering=true; res.targetPath="target ";} - ) - .resources( - resource( - directory -> "c://foodir", - filtering -> "true", - targetPath -> "c://bardir", - includes("*.a"), - excludes("*.b") - ), - resource() - .directory("c://foodir").filtering(true).targetPath("c://bardir").includes("*.a").excludes("*.b") - .endResource(), - resource(r -> {r.directory="c://foodir"; r.filtering=true; r.targetPath="c://bardir"; r.includes="*.a"; r.excludes="*.b";}) - ) - .pluginManagement( - plugin("org.apache.rat:apache-rat-plugin") - .configuration( - startXML() - .tag("excludes", excludes -> { - excludes.child("exclude", exclude -> exclude.content("src/test/resources*/**")); - excludes.child("exclude", exclude -> exclude.content("src/test/projects/**")); - excludes.child("exclude", exclude -> exclude.content("src/test/remote-repo/**")); - excludes.child("exclude", exclude -> exclude.content("**/*.odg")); - }) - .endXML() - ), - plugin(groupId -> "org.apache.maven.plugins", artifactId -> "maven-checkstyle-plugin", version -> "2.14") - ) - .plugins( - plugin("org.codehaus.mojo", "animal-sniffer-maven-plugin", "1.14") - .configuration( - startXML() - .tag("signature", signature -> { - signature.child("groupId", groupId -> groupId.content("org.codehaus.mojo.signature")); - signature.child("artifactId", artifactId -> artifactId.content("java17")); - signature.child("version", version -> version.content("1.0")); - }) - .endXML() - ) - .executions( - execution( - id -> "check-java-1.6-compat", - phase -> "process-classes", - goals("check") - ) - ,execution("check-java-1.6-compat").phase("process-classes").goals("check") - ) - ); - - profile("jboss") - .activeByDefault(true) - .activeForFile("exists", "missing") - - .dependencies( - dependency(groupId -> "gr1", artifactId -> "art1"), - dependency(groupId -> "gr2", artifactId -> "art2") - ) - - .modules("a", "ss") - - .properties( - property(name1 -> "prop1"), - property(name2 -> "prop2") - ) - - .build( - profileBuild() - .plugins( - plugin("") - .configuration( - startXML() - .tag("classifier", tag -> tag.content("pre-process")) - .endXML() - ) - ) - .resources( - resource("directory", "targetPath", true, new String[]{"*"}, null) - ) - ); - - properties( - property(name1 -> "property_1"), - property(name2 -> "property_2") - ); - } -} \ No newline at end of file + @SuppressWarnings({"unchecked"}) + public void project() { + + modelVersion = "4.0"; + groupId = "my-grp"; + artifactId = "my-art"; + version = "1.0"; + + parent(artifactId -> "artf_id", version -> "v1", relativePath -> "../..", groupId -> "grp-id-1"); + + dependencies( + dep -> { + dep.groupId = "grpid1"; + dep.artifactId = "art1"; + }, + dep -> { + dep.groupId = "grpid2"; + dep.artifactId = "art2"; + dep.version = "1.0"; + dep.exclusions = Arrays.asList("exclgr1:artifact1", "exclgr2:art2"); + }); + + dependencies( + dependency( + groupId -> "dep1grp", + artifactId -> "art2", + exclusions(exclusion(groupId -> "grpToExclude", artifactId -> "artifactToExclue")), + version -> "v2"), + dependency(groupId -> "gr2", artifactId -> "art3"), + test("org.junit:junit")); + + repositories(repository(id -> "my-repo", url -> "http://myserver/repo")); + + build( + artifactId -> "artf_id", + version -> "v1", + plugins(plugin( + artifactId -> "org.apache.maven.plugins", + groupId -> "maven-jar-plugin", + version -> "2.6", + configuration(startXML() + .tag("classifier", tag -> tag.content("pre-process")) + .endXML()), + executions(execution( + id -> "pre-process-classes", + phase -> "pre-process", + configuration(startXML() + .tag("classifier", tag -> tag.content("pre-process")) + .endXML())) + .get()), + pluginDependencies(dependency( + artifactId -> "org.apache.maven.plugins", + groupId -> "maven-jar-plugin", + version -> "2.6"))) + .get()), + resources(resource(targetPath -> "d:/", filtering -> "true")), + testResources((Resource[]) null)); + + build().resources( + res -> { + res.directory = "c://foodir"; + res.filtering = true; + res.targetPath = "c://bardir"; + res.includes = "*.a"; + res.excludes = "*.b"; + }, + res -> { + res.directory = "src/main/resources"; + res.filtering = true; + res.targetPath = "target "; + }) + .resources( + resource( + directory -> "c://foodir", + filtering -> "true", + targetPath -> "c://bardir", + includes("*.a"), + excludes("*.b")), + resource() + .directory("c://foodir") + .filtering(true) + .targetPath("c://bardir") + .includes("*.a") + .excludes("*.b") + .endResource(), + resource(r -> { + r.directory = "c://foodir"; + r.filtering = true; + r.targetPath = "c://bardir"; + r.includes = "*.a"; + r.excludes = "*.b"; + })) + .pluginManagement( + plugin("org.apache.rat:apache-rat-plugin") + .configuration(startXML() + .tag("excludes", excludes -> { + excludes.child( + "exclude", exclude -> exclude.content("src/test/resources*/**")); + excludes.child( + "exclude", exclude -> exclude.content("src/test/projects/**")); + excludes.child( + "exclude", exclude -> exclude.content("src/test/remote-repo/**")); + excludes.child("exclude", exclude -> exclude.content("**/*.odg")); + }) + .endXML()), + plugin( + groupId -> "org.apache.maven.plugins", + artifactId -> "maven-checkstyle-plugin", + version -> "2.14")) + .plugins(plugin("org.codehaus.mojo", "animal-sniffer-maven-plugin", "1.14") + .configuration(startXML() + .tag("signature", signature -> { + signature.child( + "groupId", groupId -> groupId.content("org.codehaus.mojo.signature")); + signature.child("artifactId", artifactId -> artifactId.content("java17")); + signature.child("version", version -> version.content("1.0")); + }) + .endXML()) + .executions( + execution(id -> "check-java-1.6-compat", phase -> "process-classes", goals("check")), + execution("check-java-1.6-compat") + .phase("process-classes") + .goals("check"))); + + profile("jboss") + .activeByDefault(true) + .activeForFile("exists", "missing") + .dependencies( + dependency(groupId -> "gr1", artifactId -> "art1"), + dependency(groupId -> "gr2", artifactId -> "art2")) + .modules("a", "ss") + .properties(property(name1 -> "prop1"), property(name2 -> "prop2")) + .build(profileBuild() + .plugins(plugin("") + .configuration(startXML() + .tag("classifier", tag -> tag.content("pre-process")) + .endXML())) + .resources(resource("directory", "targetPath", true, new String[] {"*"}, null))); + + properties(property(name1 -> "property_1"), property(name2 -> "property_2")); + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest2.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest2.java index cb493e49..45bd33f8 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest2.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/test/ModelTest2.java @@ -4,16 +4,14 @@ public class ModelTest2 extends ModelFactory { - public void project() { + public void project() { - modelVersion = "4.0.0"; - groupId = "org.sample1"; - artifactId = "project1"; - packaging = "jar"; - version = "1.0-SNAPSHOT"; - - dependencies( - dependency(groupId -> "junit", artifactId -> "junit", version -> "3.8.1", scope -> "test") - ); - } + modelVersion = "4.0.0"; + groupId = "org.sample1"; + artifactId = "project1"; + packaging = "jar"; + version = "1.0-SNAPSHOT"; + + dependencies(dependency(groupId -> "junit", artifactId -> "junit", version -> "3.8.1", scope -> "test")); + } } diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/writer/ModelToJavaWriter.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/writer/ModelToJavaWriter.java index df251f79..bf7b996c 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/writer/ModelToJavaWriter.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/writer/ModelToJavaWriter.java @@ -5,8 +5,6 @@ import java.util.List; import java.util.Properties; import java.util.stream.Collectors; - -import org.codehaus.plexus.util.xml.Xpp3Dom; import org.apache.maven.model.Activation; import org.apache.maven.model.Build; import org.apache.maven.model.BuildBase; @@ -19,444 +17,458 @@ import org.apache.maven.model.Profile; import org.apache.maven.model.Repository; import org.apache.maven.model.Resource; +import org.codehaus.plexus.util.xml.Xpp3Dom; public class ModelToJavaWriter { - - private Writer out; - private Model model; - private String br = System.lineSeparator(); - - public ModelToJavaWriter(Writer out, Model model) { - super(); - this.out = out; - this.model = model; - } - - public void write() { - try { - writeFileStar(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private void writeFileStar() throws IOException { - out.write("public class pom extends org.sonatype.maven.polyglot.java.dsl.ModelFactory {" + br); - out.write(" public void project() {" + br); - - writeHeader(); - } - - private void writeFileEnd() throws IOException { - out.write(" }" + br); - out.write("}"); - } - - private void writeHeader() throws IOException { - out.write(" modelVersion = \"" + model.getModelVersion() + "\";" + br); - out.write(" groupId = \"" + model.getGroupId() + "\";" + br); - out.write(" artifactId = \"" + model.getArtifactId() + "\";" + br); - out.write(" packaging = \"" + model.getPackaging() + "\";" + br); - out.write(" version = \"" + model.getVersion() + "\";" + br); - - writeParent(); - } - - private void writeParent() throws IOException { - Parent parent = model.getParent(); - if (parent != null) { - out.write(" parent(" + br); - out.write(" groupId -> \"" + parent.getGroupId() + "\"," + br); - out.write(" artifactId -> \"" + parent.getArtifactId() + "\""); - if (parent.getVersion() != null) { - out.write("," + br); - out.write(" version -> \"" + parent.getVersion()+ "\""); - } - if (parent.getRelativePath() != null) { - out.write("," + br); - out.write(" relativePath -> \"" + parent.getRelativePath()+ "\"" + br); - } - out.write(" );" + br); - } - - writeProperties(); - } - - private void writeProperties() throws IOException { - Properties props = model.getProperties(); - if (props != null && !props.isEmpty()) { - out.write(" properties(" + br); - int propertyNumber = 1; - for (Object prop : props.keySet()) { - out.write(" property(\"" + prop.toString() + "\", \"" + props.get(prop) + "\")"); - if (propertyNumber < props.size()) { - out.write("," + br); - } else { - out.write(br); - } - propertyNumber++; - } - out.write(" );" + br); - } - - writeRepositories(); - } - - private void writeRepositories() throws IOException { - - if (model.getRepositories() != null && !model.getRepositories().isEmpty()) { - out.write(" " + "repositories(" + br); - - int repositoryOrderNum = 1; - for (Repository repository : model.getRepositories()) { - - out.write(" " + " " + "repository("); - if (repository.getUrl() != null) { - out.write("url -> \"" + repository.getUrl() + "\""); - } - if (repository.getName() != null) { - out.write(", name -> \"" + repository.getName() + "\""); - } - if (repository.getId() != null) { - out.write(", id -> \"" + repository.getId() + "\""); - } - - out.write(")" + br); - - if (repositoryOrderNum < model.getRepositories().size()) { - out.write(" " + "," + br); - } - repositoryOrderNum++; - } - - out.write(" " +");" + br); - } - - writeDependencies(); - } - - private void writeDependencies() throws IOException { - - if (model.getDependencyManagement() != null && model.getDependencyManagement().getDependencies() != null && !model.getDependencyManagement().getDependencies().isEmpty()) { - writeDependencies(model.getDependencyManagement().getDependencies(), "dependencyManagement"); - } - writeDependencies(model.getDependencies(), "dependencies"); - writeBuild(); - } - - private void writeDependencies(List dependencies, String methodName) throws IOException { - if (dependencies != null && !dependencies.isEmpty()) { - out.write(" " + methodName + "(" + br); - int dependencyNumber = 1; - for (Dependency dependency : dependencies) { - writeDependency(dependency, " "); - if (dependencyNumber < dependencies.size()) { - out.write("," + br); - } - dependencyNumber++; - } - out.write(br + " );" + br); - } - } - - private void writeDependency(Dependency dependency, String indent) throws IOException { - out.write(indent + " dependency(" + br); - out.write(indent + " groupId -> \"" + dependency.getGroupId() + "\"," + br); - out.write(indent + " artifactId -> \"" + dependency.getArtifactId() + "\""); - if (dependency.getVersion() != null) { - out.write("," + br); - out.write(indent + " version -> \"" + dependency.getVersion() + "\""); - } - if (dependency.getScope() != null) { - out.write("," + br); - out.write(indent + " scope -> \"" + dependency.getScope() + "\""); - } - if (dependency.getOptional() != null) { - out.write("," + br); - out.write(indent + " optional -> \"" + dependency.getOptional() + "\""); - } - if (dependency.getType() != null) { - out.write("," + br); - out.write(indent + " type -> \"" + dependency.getType() + "\""); - } - if (dependency.getSystemPath() != null) { - out.write("," + br); - out.write(indent + " systemPath -> \"" + dependency.getSystemPath() + "\""); - } - if (dependency.getExclusions() != null && !dependency.getExclusions().isEmpty()) { - out.write("," + br); - out.write(indent + " exclusions("); - for (Exclusion exclusion : dependency.getExclusions()) { - out.write(indent + " exclusion(groupId -> \"" + exclusion.getGroupId()); - if (exclusion.getArtifactId() != null) { - out.write(", artifactId -> \"" + exclusion.getArtifactId()); - } - out.write("\")" + br); - } - out.write(br + indent + " )"); - } - out.write(br + indent + " )"); - } - - private void writeBuild() throws IOException { - Build build = model.getBuild(); - if (build != null) { - out.write(" build()" + br); - - if (build.getSourceDirectory() != null) { - out.write(" .sourceDirectory(\"" + build.getSourceDirectory() + "\")" + br); - } - if (build.getScriptSourceDirectory() != null) { - out.write(" .scriptSourceDirectory(\"" + build.getScriptSourceDirectory() + "\")" + br); - } - if (build.getTestSourceDirectory() != null) { - out.write(" .testSourceDirectory(\"" + build.getTestSourceDirectory() + "\")" + br); - } - if (build.getOutputDirectory() != null) { - out.write(" .outputDirectory(\"" + build.getOutputDirectory() + "\")" + br); - } - if (build.getTestOutputDirectory() != null) { - out.write(" .testOutputDirectory(\"" + build.getTestOutputDirectory() + "\")" + br); - } - List extensions = build.getExtensions(); - if (extensions != null && !extensions.isEmpty()) { - out.write(" .extensions(" + br); - int extensionNumber = 1; - for (Extension extension : extensions) { - out.write(" extension(" + br); - out.write(" groupId -> \"" + extension.getGroupId() + "\"," + br); - out.write(" artifactId -> \"" + extension.getArtifactId() + "\""); - if (extension.getVersion() != null) { - out.write("," + br); - out.write(" version -> \"" + extension.getVersion() + "\""); - } - out.write(br + " )"); - if (extensionNumber < extensions.size()) { - out.write("," + br); - } - extensionNumber++; - } - out.write(br + " )" + br); - } - - writeBuildBase(build, " "); - - out.write(" .endBuild();" + br); - } - - writeProfiles(); - } - - private void writeBuildBase(BuildBase build, String indent) throws IOException { - - if (build.getDefaultGoal() != null) { - out.write(indent + ".defaultGoal(\"" + build.getDefaultGoal() + "\")" + br); - } - if (build.getDirectory() != null) { - out.write(indent + ".directory(\"" + build.getDirectory() + "\")" + br); - } - if (build.getFinalName() != null) { - out.write(indent + ".finalName(\"" + build.getFinalName() + "\")" + br); - } - if (build.getFilters() != null && !build.getFilters().isEmpty()) { - out.write(indent + ".filters(\"" + build.getFilters().stream().collect(Collectors.joining("\",\"")) + "\")" + br); - } - - if (build.getPluginManagement() != null) { - writePlugins(build.getPluginManagement().getPlugins(), indent, "pluginManagement"); - } - - writePlugins(build.getPlugins(), indent, "plugins"); - - writeResources(build.getResources(), indent, "resources"); - writeResources(build.getTestResources(), indent, "testResources"); - } - - private void writeResources(List resources, String indent, String methodName) throws IOException { - if (resources != null && !resources.isEmpty()) { - out.write(indent + "." + methodName + "("+ br); - - int pluginOrderNum = 1; - for (Resource resource : resources) { - writeResource(resource, indent + " "); - - if (pluginOrderNum < resources.size()) { - out.write(indent + " ," + br); - } - pluginOrderNum++; - } - - out.write(indent + ")"+ br); - } - } - - private void writeResource(Resource resource, String indent) throws IOException { - out.write(indent + "resource()" + br); - out.write(indent + " "); - if (resource.getDirectory() != null) { - out.write(".directory(\"" + resource.getDirectory() + "\")"); - } - if (resource.getFiltering() != null) { - out.write(".filtering(" + resource.getFiltering() + ")"); - } - if (resource.getTargetPath() != null) { - out.write(".targetPath(\"" + resource.getTargetPath() + "\")"); - } - if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { - out.write(".includes(\"" + resource.getIncludes().stream().collect(Collectors.joining("\",\"")) + "\")"); - } - if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { - out.write(".excludes(\"" + resource.getExcludes().stream().collect(Collectors.joining("\",\"")) + "\")"); - } - out.write(br + indent + ".endResource()" + br); - } - - private void writePlugins(List plugins, String indent, String methodName) throws IOException { - if (plugins != null && !plugins.isEmpty()) { - out.write(indent + "." + methodName + "("+ br); - int pluginOrderNum = 1; - for (Plugin plugin : plugins) { - writePlugin(plugin, indent + " "); - - if (pluginOrderNum < plugins.size()) { - out.write(indent + " ," + br); - } - pluginOrderNum++; - } - out.write(indent + ") //end of plugins section"+ br); - } - } - - private void writePlugin(Plugin plugin, String indent) throws IOException { - StringBuilder sb = new StringBuilder(); - sb.append(plugin.getGroupId() + ":" + plugin.getArtifactId()); - if (plugin.getVersion() != null) { - sb.append(":" + plugin.getVersion()); - } - out.write(indent + "plugin(\"" + sb.toString() + "\")" + br); - if (plugin.getExtensions() != null) { - out.write(indent + " .extensions(" + plugin.getExtensions() + ")" + br); - } - if (plugin.getInherited() != null) { - out.write(indent + " .inherited(" + plugin.getInherited() + ")" + br); - } - if (plugin.getDependencies() != null && !plugin.getDependencies().isEmpty()) { - out.write(indent + " " + ".dependencies(" + br); - writePluginDependency(plugin.getDependencies(), indent); - out.write(indent + " " + ")" + br); - } - writeConfiguration((Xpp3Dom)plugin.getConfiguration(), indent); - - out.write(indent + ".endPlugin()" + br); - } - - private void writeConfiguration(Xpp3Dom configuration, String indent) throws IOException { - if (configuration != null) { - out.write(indent + " " + ".configuration(" + br); - out.write(indent + " " + "startXML()" + br); - - StringBuilder sb = new StringBuilder(); - generateConfig(configuration, sb, indent + " "); - - out.write(sb.toString()); - - out.write(indent + " " + ".endXML()" + br); - out.write(indent + " " + ") // end of configuration section" + br); - } - } - - private void generateConfig(Xpp3Dom node, StringBuilder sb, String indent) { - String tagName = node.getName(); - String tagValue = node.getValue(); - if (node.getParent() == null) { - sb.append(indent + ".tag(\"" + tagName + "\", " + tagName + " -> {" + br); - } - - if (tagValue != null) { - sb.append(indent + " " + calculateXMLIndent(node) + tagName + ".content(\"" + tagValue + "\");" + br); - } - String[] attributeNames = node.getAttributeNames(); - for (int i = 0; i < attributeNames.length; i++) { - String attributeName = attributeNames[i]; - sb.append(indent + calculateXMLIndent(node) + " " + tagName + ".attribute(\"" + attributeName + "\", \"" + node.getAttribute(attributeName) + "\");" + br); - } - Xpp3Dom[] children = node.getChildren(); - for (int i = 0; i < children.length; i++) { - Xpp3Dom child = children[i]; - sb.append(indent + calculateXMLIndent(child) + child.getParent().getName() + ".child(\"" + child.getName() + "\"," + child.getName() + " -> {" + br); - - generateConfig(child, sb, indent); - - sb.append(indent + calculateXMLIndent(child) + "});" + br); - } - - if (node.getParent() == null) { - sb.append(indent + calculateXMLIndent(node) + "})" + br); - } - } - - private int calculateXMlHierarchyLevel(Xpp3Dom node, int level) { - if (node.getParent() == null) { - return level; - } else { - return calculateXMlHierarchyLevel(node.getParent(), level + 1); - } - } - - private String calculateXMLIndent(Xpp3Dom node) { - String indent = ""; - for (int i = 0; i < calculateXMlHierarchyLevel(node, 0); i++) { - indent = indent + " "; - } - return indent; - } - - private void writePluginDependency(List dependencies, String indent) throws IOException { - int dependencyNumber = 1; - for (Dependency dependency : dependencies) { - writeDependency(dependency, indent + " "); - out.write(br); - if (dependencyNumber < dependencies.size()) { - out.write(indent + " ," + br); - } - dependencyNumber++; - } - } - - private void writeProfiles() throws IOException { - if (model.getProfiles() != null) { - for (Profile profile : model.getProfiles()) { - out.write(" " + "profile(\"" + profile.getId() + "\")" + br); - Activation activation = profile.getActivation(); - if (activation != null) { - out.write(" " + " " + ".activeByDefault(" + activation.isActiveByDefault() + ")" + br); - - if (activation.getJdk() != null) { - out.write(" " + " " + ".activeByDefault(" + activation.isActiveByDefault() + ")" + br); - } - if (activation.getProperty() != null) { - String propertyValue = activation.getProperty().getValue() == null ? "null" : "\"" + activation.getProperty().getValue() + "\""; - out.write(" " + " " + ".activeForPropertyValue(\"" + activation.getProperty().getName() + "\"," + propertyValue + ")" + br); - } - if (activation.getFile() != null) { - String exists = activation.getFile().getExists() == null ? "null" : "\"" + activation.getFile().getExists() + "\""; - String missing = activation.getFile().getMissing() == null ? "null" : "\"" + activation.getFile().getMissing() + "\""; - out.write(" " + " " + ".activeForFile(" + exists + "," + missing + ")" + br); - } - } - - if (profile.getBuild() != null) { - out.write(" " + " " + ".build(" + br); - out.write(" " + " " + "profileBuild()" + br); - writeBuildBase(profile.getBuild(), " " + " "); - out.write(" " + " " + ".endBuild()" + br); - out.write(" " + " " + ") //end of profile build section" + br); - } - - out.write(" " + ".endProfile();" + br); - } - } - - writeFileEnd(); - } -} \ No newline at end of file + + private Writer out; + private Model model; + private String br = System.lineSeparator(); + + public ModelToJavaWriter(Writer out, Model model) { + super(); + this.out = out; + this.model = model; + } + + public void write() { + try { + writeFileStar(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void writeFileStar() throws IOException { + out.write("public class pom extends org.sonatype.maven.polyglot.java.dsl.ModelFactory {" + br); + out.write(" public void project() {" + br); + + writeHeader(); + } + + private void writeFileEnd() throws IOException { + out.write(" }" + br); + out.write("}"); + } + + private void writeHeader() throws IOException { + out.write(" modelVersion = \"" + model.getModelVersion() + "\";" + br); + out.write(" groupId = \"" + model.getGroupId() + "\";" + br); + out.write(" artifactId = \"" + model.getArtifactId() + "\";" + br); + out.write(" packaging = \"" + model.getPackaging() + "\";" + br); + out.write(" version = \"" + model.getVersion() + "\";" + br); + + writeParent(); + } + + private void writeParent() throws IOException { + Parent parent = model.getParent(); + if (parent != null) { + out.write(" parent(" + br); + out.write(" groupId -> \"" + parent.getGroupId() + "\"," + br); + out.write(" artifactId -> \"" + parent.getArtifactId() + "\""); + if (parent.getVersion() != null) { + out.write("," + br); + out.write(" version -> \"" + parent.getVersion() + "\""); + } + if (parent.getRelativePath() != null) { + out.write("," + br); + out.write(" relativePath -> \"" + parent.getRelativePath() + "\"" + br); + } + out.write(" );" + br); + } + + writeProperties(); + } + + private void writeProperties() throws IOException { + Properties props = model.getProperties(); + if (props != null && !props.isEmpty()) { + out.write(" properties(" + br); + int propertyNumber = 1; + for (Object prop : props.keySet()) { + out.write(" property(\"" + prop.toString() + "\", \"" + props.get(prop) + "\")"); + if (propertyNumber < props.size()) { + out.write("," + br); + } else { + out.write(br); + } + propertyNumber++; + } + out.write(" );" + br); + } + + writeRepositories(); + } + + private void writeRepositories() throws IOException { + + if (model.getRepositories() != null && !model.getRepositories().isEmpty()) { + out.write(" " + "repositories(" + br); + + int repositoryOrderNum = 1; + for (Repository repository : model.getRepositories()) { + + out.write(" " + " " + "repository("); + if (repository.getUrl() != null) { + out.write("url -> \"" + repository.getUrl() + "\""); + } + if (repository.getName() != null) { + out.write(", name -> \"" + repository.getName() + "\""); + } + if (repository.getId() != null) { + out.write(", id -> \"" + repository.getId() + "\""); + } + + out.write(")" + br); + + if (repositoryOrderNum < model.getRepositories().size()) { + out.write(" " + "," + br); + } + repositoryOrderNum++; + } + + out.write(" " + ");" + br); + } + + writeDependencies(); + } + + private void writeDependencies() throws IOException { + + if (model.getDependencyManagement() != null + && model.getDependencyManagement().getDependencies() != null + && !model.getDependencyManagement().getDependencies().isEmpty()) { + writeDependencies(model.getDependencyManagement().getDependencies(), "dependencyManagement"); + } + writeDependencies(model.getDependencies(), "dependencies"); + writeBuild(); + } + + private void writeDependencies(List dependencies, String methodName) throws IOException { + if (dependencies != null && !dependencies.isEmpty()) { + out.write(" " + methodName + "(" + br); + int dependencyNumber = 1; + for (Dependency dependency : dependencies) { + writeDependency(dependency, " "); + if (dependencyNumber < dependencies.size()) { + out.write("," + br); + } + dependencyNumber++; + } + out.write(br + " );" + br); + } + } + + private void writeDependency(Dependency dependency, String indent) throws IOException { + out.write(indent + " dependency(" + br); + out.write(indent + " groupId -> \"" + dependency.getGroupId() + "\"," + br); + out.write(indent + " artifactId -> \"" + dependency.getArtifactId() + "\""); + if (dependency.getVersion() != null) { + out.write("," + br); + out.write(indent + " version -> \"" + dependency.getVersion() + "\""); + } + if (dependency.getScope() != null) { + out.write("," + br); + out.write(indent + " scope -> \"" + dependency.getScope() + "\""); + } + if (dependency.getOptional() != null) { + out.write("," + br); + out.write(indent + " optional -> \"" + dependency.getOptional() + "\""); + } + if (dependency.getType() != null) { + out.write("," + br); + out.write(indent + " type -> \"" + dependency.getType() + "\""); + } + if (dependency.getSystemPath() != null) { + out.write("," + br); + out.write(indent + " systemPath -> \"" + dependency.getSystemPath() + "\""); + } + if (dependency.getExclusions() != null && !dependency.getExclusions().isEmpty()) { + out.write("," + br); + out.write(indent + " exclusions("); + for (Exclusion exclusion : dependency.getExclusions()) { + out.write(indent + " exclusion(groupId -> \"" + exclusion.getGroupId()); + if (exclusion.getArtifactId() != null) { + out.write(", artifactId -> \"" + exclusion.getArtifactId()); + } + out.write("\")" + br); + } + out.write(br + indent + " )"); + } + out.write(br + indent + " )"); + } + + private void writeBuild() throws IOException { + Build build = model.getBuild(); + if (build != null) { + out.write(" build()" + br); + + if (build.getSourceDirectory() != null) { + out.write(" .sourceDirectory(\"" + build.getSourceDirectory() + "\")" + br); + } + if (build.getScriptSourceDirectory() != null) { + out.write(" .scriptSourceDirectory(\"" + build.getScriptSourceDirectory() + "\")" + br); + } + if (build.getTestSourceDirectory() != null) { + out.write(" .testSourceDirectory(\"" + build.getTestSourceDirectory() + "\")" + br); + } + if (build.getOutputDirectory() != null) { + out.write(" .outputDirectory(\"" + build.getOutputDirectory() + "\")" + br); + } + if (build.getTestOutputDirectory() != null) { + out.write(" .testOutputDirectory(\"" + build.getTestOutputDirectory() + "\")" + br); + } + List extensions = build.getExtensions(); + if (extensions != null && !extensions.isEmpty()) { + out.write(" .extensions(" + br); + int extensionNumber = 1; + for (Extension extension : extensions) { + out.write(" extension(" + br); + out.write(" groupId -> \"" + extension.getGroupId() + "\"," + br); + out.write(" artifactId -> \"" + extension.getArtifactId() + "\""); + if (extension.getVersion() != null) { + out.write("," + br); + out.write(" version -> \"" + extension.getVersion() + "\""); + } + out.write(br + " )"); + if (extensionNumber < extensions.size()) { + out.write("," + br); + } + extensionNumber++; + } + out.write(br + " )" + br); + } + + writeBuildBase(build, " "); + + out.write(" .endBuild();" + br); + } + + writeProfiles(); + } + + private void writeBuildBase(BuildBase build, String indent) throws IOException { + + if (build.getDefaultGoal() != null) { + out.write(indent + ".defaultGoal(\"" + build.getDefaultGoal() + "\")" + br); + } + if (build.getDirectory() != null) { + out.write(indent + ".directory(\"" + build.getDirectory() + "\")" + br); + } + if (build.getFinalName() != null) { + out.write(indent + ".finalName(\"" + build.getFinalName() + "\")" + br); + } + if (build.getFilters() != null && !build.getFilters().isEmpty()) { + out.write(indent + ".filters(\"" + build.getFilters().stream().collect(Collectors.joining("\",\"")) + "\")" + + br); + } + + if (build.getPluginManagement() != null) { + writePlugins(build.getPluginManagement().getPlugins(), indent, "pluginManagement"); + } + + writePlugins(build.getPlugins(), indent, "plugins"); + + writeResources(build.getResources(), indent, "resources"); + writeResources(build.getTestResources(), indent, "testResources"); + } + + private void writeResources(List resources, String indent, String methodName) throws IOException { + if (resources != null && !resources.isEmpty()) { + out.write(indent + "." + methodName + "(" + br); + + int pluginOrderNum = 1; + for (Resource resource : resources) { + writeResource(resource, indent + " "); + + if (pluginOrderNum < resources.size()) { + out.write(indent + " ," + br); + } + pluginOrderNum++; + } + + out.write(indent + ")" + br); + } + } + + private void writeResource(Resource resource, String indent) throws IOException { + out.write(indent + "resource()" + br); + out.write(indent + " "); + if (resource.getDirectory() != null) { + out.write(".directory(\"" + resource.getDirectory() + "\")"); + } + if (resource.getFiltering() != null) { + out.write(".filtering(" + resource.getFiltering() + ")"); + } + if (resource.getTargetPath() != null) { + out.write(".targetPath(\"" + resource.getTargetPath() + "\")"); + } + if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { + out.write(".includes(\"" + resource.getIncludes().stream().collect(Collectors.joining("\",\"")) + "\")"); + } + if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { + out.write(".excludes(\"" + resource.getExcludes().stream().collect(Collectors.joining("\",\"")) + "\")"); + } + out.write(br + indent + ".endResource()" + br); + } + + private void writePlugins(List plugins, String indent, String methodName) throws IOException { + if (plugins != null && !plugins.isEmpty()) { + out.write(indent + "." + methodName + "(" + br); + int pluginOrderNum = 1; + for (Plugin plugin : plugins) { + writePlugin(plugin, indent + " "); + + if (pluginOrderNum < plugins.size()) { + out.write(indent + " ," + br); + } + pluginOrderNum++; + } + out.write(indent + ") //end of plugins section" + br); + } + } + + private void writePlugin(Plugin plugin, String indent) throws IOException { + StringBuilder sb = new StringBuilder(); + sb.append(plugin.getGroupId() + ":" + plugin.getArtifactId()); + if (plugin.getVersion() != null) { + sb.append(":" + plugin.getVersion()); + } + out.write(indent + "plugin(\"" + sb.toString() + "\")" + br); + if (plugin.getExtensions() != null) { + out.write(indent + " .extensions(" + plugin.getExtensions() + ")" + br); + } + if (plugin.getInherited() != null) { + out.write(indent + " .inherited(" + plugin.getInherited() + ")" + br); + } + if (plugin.getDependencies() != null && !plugin.getDependencies().isEmpty()) { + out.write(indent + " " + ".dependencies(" + br); + writePluginDependency(plugin.getDependencies(), indent); + out.write(indent + " " + ")" + br); + } + writeConfiguration((Xpp3Dom) plugin.getConfiguration(), indent); + + out.write(indent + ".endPlugin()" + br); + } + + private void writeConfiguration(Xpp3Dom configuration, String indent) throws IOException { + if (configuration != null) { + out.write(indent + " " + ".configuration(" + br); + out.write(indent + " " + "startXML()" + br); + + StringBuilder sb = new StringBuilder(); + generateConfig(configuration, sb, indent + " "); + + out.write(sb.toString()); + + out.write(indent + " " + ".endXML()" + br); + out.write(indent + " " + ") // end of configuration section" + br); + } + } + + private void generateConfig(Xpp3Dom node, StringBuilder sb, String indent) { + String tagName = node.getName(); + String tagValue = node.getValue(); + if (node.getParent() == null) { + sb.append(indent + ".tag(\"" + tagName + "\", " + tagName + " -> {" + br); + } + + if (tagValue != null) { + sb.append(indent + " " + calculateXMLIndent(node) + tagName + ".content(\"" + tagValue + "\");" + br); + } + String[] attributeNames = node.getAttributeNames(); + for (int i = 0; i < attributeNames.length; i++) { + String attributeName = attributeNames[i]; + sb.append(indent + calculateXMLIndent(node) + " " + tagName + ".attribute(\"" + attributeName + "\", \"" + + node.getAttribute(attributeName) + "\");" + br); + } + Xpp3Dom[] children = node.getChildren(); + for (int i = 0; i < children.length; i++) { + Xpp3Dom child = children[i]; + sb.append(indent + calculateXMLIndent(child) + child.getParent().getName() + ".child(\"" + child.getName() + + "\"," + child.getName() + " -> {" + br); + + generateConfig(child, sb, indent); + + sb.append(indent + calculateXMLIndent(child) + "});" + br); + } + + if (node.getParent() == null) { + sb.append(indent + calculateXMLIndent(node) + "})" + br); + } + } + + private int calculateXMlHierarchyLevel(Xpp3Dom node, int level) { + if (node.getParent() == null) { + return level; + } else { + return calculateXMlHierarchyLevel(node.getParent(), level + 1); + } + } + + private String calculateXMLIndent(Xpp3Dom node) { + String indent = ""; + for (int i = 0; i < calculateXMlHierarchyLevel(node, 0); i++) { + indent = indent + " "; + } + return indent; + } + + private void writePluginDependency(List dependencies, String indent) throws IOException { + int dependencyNumber = 1; + for (Dependency dependency : dependencies) { + writeDependency(dependency, indent + " "); + out.write(br); + if (dependencyNumber < dependencies.size()) { + out.write(indent + " ," + br); + } + dependencyNumber++; + } + } + + private void writeProfiles() throws IOException { + if (model.getProfiles() != null) { + for (Profile profile : model.getProfiles()) { + out.write(" " + "profile(\"" + profile.getId() + "\")" + br); + Activation activation = profile.getActivation(); + if (activation != null) { + out.write(" " + " " + ".activeByDefault(" + activation.isActiveByDefault() + ")" + br); + + if (activation.getJdk() != null) { + out.write( + " " + " " + ".activeByDefault(" + activation.isActiveByDefault() + ")" + br); + } + if (activation.getProperty() != null) { + String propertyValue = activation.getProperty().getValue() == null + ? "null" + : "\"" + activation.getProperty().getValue() + "\""; + out.write(" " + " " + ".activeForPropertyValue(\"" + + activation.getProperty().getName() + "\"," + propertyValue + ")" + br); + } + if (activation.getFile() != null) { + String exists = activation.getFile().getExists() == null + ? "null" + : "\"" + activation.getFile().getExists() + "\""; + String missing = activation.getFile().getMissing() == null + ? "null" + : "\"" + activation.getFile().getMissing() + "\""; + out.write(" " + " " + ".activeForFile(" + exists + "," + missing + ")" + br); + } + } + + if (profile.getBuild() != null) { + out.write(" " + " " + ".build(" + br); + out.write(" " + " " + "profileBuild()" + br); + writeBuildBase(profile.getBuild(), " " + " "); + out.write(" " + " " + ".endBuild()" + br); + out.write(" " + " " + ") //end of profile build section" + br); + } + + out.write(" " + ".endProfile();" + br); + } + } + + writeFileEnd(); + } +} diff --git a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/xml/ConfiugrationXmlBuilder.java b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/xml/ConfiugrationXmlBuilder.java index 6241ad43..066e784a 100644 --- a/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/xml/ConfiugrationXmlBuilder.java +++ b/polyglot-java/src/main/java/org/sonatype/maven/polyglot/java/xml/ConfiugrationXmlBuilder.java @@ -5,11 +5,9 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; - import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; - import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -20,9 +18,7 @@ public class ConfiugrationXmlBuilder { ByteArrayOutputStream outputStream; XMLStreamWriter writer; - public ConfiugrationXmlBuilder() { - - } + public ConfiugrationXmlBuilder() {} protected XMLStreamWriter createWriter(OutputStream outputStream) { try { @@ -37,12 +33,12 @@ protected XMLOutputFactory createFactory() { } public ConfiugrationXmlBuilder startXML() { - - this.outputStream = new ByteArrayOutputStream(); - this.writer = createWriter(outputStream); - + + this.outputStream = new ByteArrayOutputStream(); + this.writer = createWriter(outputStream); + try { - writer.writeStartDocument(); + writer.writeStartDocument(); return this; } catch (XMLStreamException e) { throw new RuntimeException(e); @@ -50,19 +46,19 @@ public ConfiugrationXmlBuilder startXML() { } public Xpp3Dom endXML() { - try { + try { writer.writeEndDocument(); writer.flush(); - writer.close(); + writer.close(); Xpp3Dom dom = null; try { - dom = Xpp3DomBuilder.build(new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray()))); - } catch (XmlPullParserException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } + dom = Xpp3DomBuilder.build(new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray()))); + } catch (XmlPullParserException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } return dom; } catch (XMLStreamException e) { throw new RuntimeException(e); @@ -136,6 +132,5 @@ public TagContext cdata(Object content) { throw new RuntimeException(e); } } - } } diff --git a/polyglot-kotlin/pom.xml b/polyglot-kotlin/pom.xml index a5473455..862574ea 100644 --- a/polyglot-kotlin/pom.xml +++ b/polyglot-kotlin/pom.xml @@ -22,6 +22,14 @@ takari-maven-component Polyglot :: Kotlin + + UTF-8 + 2.0.0 + 3.8.1 + false + ${skipTests} + + io.takari.polyglot @@ -58,6 +66,10 @@ kotlin-script-runtime ${kotlin.version} + + org.apache.commons + commons-lang3 + @@ -84,17 +96,7 @@ - - UTF-8 - 2.0.0 - 3.8.1 - false - ${skipTests} - - - src/main/kotlin - src/test/kotlin org.apache.maven.plugins @@ -116,7 +118,9 @@ true false true - verify + + verify + @@ -128,17 +132,17 @@ compile - process-sources compile + process-sources test-compile - process-test-sources test-compile + process-test-sources @@ -146,24 +150,35 @@ com.google.code.maven-replacer-plugin replacer 1.5.3 + + ${project.build.testOutputDirectory} + **/pom.xml + @{*} + false + takari-polyglot-version + ${project.version} + - test-compile replace + test-compile + + + com.diffplug.spotless + spotless-maven-plugin - ${project.build.testOutputDirectory} - **/pom.xml - @{*} - false - takari-polyglot-version - ${project.version} + + + + src/main/kotlin + src/test/kotlin diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMapping.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMapping.kt index 6aa4ef98..dd4d0bff 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMapping.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMapping.kt @@ -1,17 +1,17 @@ package org.sonatype.maven.polyglot.kotlin -import org.sonatype.maven.polyglot.mapping.MappingSupport import javax.inject.Named import javax.inject.Singleton +import org.sonatype.maven.polyglot.mapping.MappingSupport @Singleton -@Named( "kotlin" ) +@Named("kotlin") class KotlinMapping : MappingSupport("kotlin") { - init { - setPomNames("pom.kts") - setAcceptLocationExtensions(".kts") - setAcceptOptionKeys("kotlin:4.0.0", "kts:4.0.0") - priority = 1f - } + init { + setPomNames("pom.kts") + setAcceptLocationExtensions(".kts") + setAcceptOptionKeys("kotlin:4.0.0", "kts:4.0.0") + priority = 1f + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReader.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReader.kt index d99c6e3d..2c909b78 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReader.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReader.kt @@ -1,53 +1,52 @@ package org.sonatype.maven.polyglot.kotlin -import org.apache.maven.model.Model -import org.apache.maven.model.building.ModelProcessor -import org.apache.maven.model.io.ModelReader -import org.sonatype.maven.polyglot.execute.ExecuteManager -import org.sonatype.maven.polyglot.kotlin.dsl.Project -import org.sonatype.maven.polyglot.kotlin.engine.ScriptHost import java.io.File import java.io.InputStream import java.io.Reader import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton +import org.apache.maven.model.Model +import org.apache.maven.model.building.ModelProcessor +import org.apache.maven.model.io.ModelReader +import org.sonatype.maven.polyglot.execute.ExecuteManager +import org.sonatype.maven.polyglot.kotlin.dsl.Project +import org.sonatype.maven.polyglot.kotlin.engine.ScriptHost @Singleton -@Named( "kotlin" ) +@Named("kotlin") class KotlinModelReader : ModelReader { - @Inject - private lateinit var executeManager: ExecuteManager + @Inject private lateinit var executeManager: ExecuteManager - override fun read(input: File, options: Map): Model { - val source = options[ModelProcessor.SOURCE].toString() - val sourceFile = File(source) - val basedir = sourceFile.parentFile.canonicalFile - val model = Project(input) - ScriptHost.eval(input, basedir, model) - val tasks = ArrayList(model.tasks) - executeManager.register(model, tasks) - executeManager.install(model, options) - model.tasks.clear() // Must be cleared or Maven goes into an infinitely repeatable introspection - return model - } + override fun read(input: File, options: Map): Model { + val source = options[ModelProcessor.SOURCE].toString() + val sourceFile = File(source) + val basedir = sourceFile.parentFile.canonicalFile + val model = Project(input) + ScriptHost.eval(input, basedir, model) + val tasks = ArrayList(model.tasks) + executeManager.register(model, tasks) + executeManager.install(model, options) + model.tasks.clear() // Must be cleared or Maven goes into an infinitely repeatable introspection + return model + } - override fun read(input: Reader, options: MutableMap): Model { - val temp = File.createTempFile("pom", ".kts") - temp.deleteOnExit() - temp.writer().use { input.copyTo(it) } - val model = read(temp, options) - temp.delete() - return model - } + override fun read(input: Reader, options: MutableMap): Model { + val temp = File.createTempFile("pom", ".kts") + temp.deleteOnExit() + temp.writer().use { input.copyTo(it) } + val model = read(temp, options) + temp.delete() + return model + } - override fun read(input: InputStream, options: MutableMap): Model { - val temp = File.createTempFile("pom", ".kts") - temp.deleteOnExit() - temp.outputStream().use { input.copyTo(it) } - val model = read(temp, options) - temp.delete() - return model - } + override fun read(input: InputStream, options: MutableMap): Model { + val temp = File.createTempFile("pom", ".kts") + temp.deleteOnExit() + temp.outputStream().use { input.copyTo(it) } + val model = read(temp, options) + temp.delete() + return model + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriter.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriter.kt index dd5f54af..038232fc 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriter.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriter.kt @@ -1,39 +1,46 @@ package org.sonatype.maven.polyglot.kotlin -import org.apache.maven.model.Model -import org.apache.maven.project.MavenProject -import org.slf4j.LoggerFactory -import org.sonatype.maven.polyglot.io.ModelWriterSupport -import org.sonatype.maven.polyglot.kotlin.serialization.ModelScriptWriter import java.io.StringWriter import java.io.Writer import javax.inject.Inject import javax.inject.Named import javax.inject.Provider import javax.inject.Singleton +import org.apache.maven.model.Model +import org.apache.maven.project.MavenProject +import org.slf4j.LoggerFactory +import org.sonatype.maven.polyglot.io.ModelWriterSupport +import org.sonatype.maven.polyglot.kotlin.serialization.ModelScriptWriter @Singleton -@Named( "kotlin" ) +@Named("kotlin") class KotlinModelWriter : ModelWriterSupport() { - private var log = LoggerFactory.getLogger( KotlinModelWriter::class.java ) + private var log = LoggerFactory.getLogger(KotlinModelWriter::class.java) - @Inject - private lateinit var projectProvider: Provider + @Inject private lateinit var projectProvider: Provider - override fun write(output: Writer, options: Map, model: Model) { - output.write(with(StringWriter(1024)) { - val config = HashMap(options) - config.putIfAbsent("xml.dsl.enabled", projectProvider.get()?.properties?.getProperty("polyglot-kotlin.xml-dsl-enabled", "true") ?: "true") - config.putIfAbsent("flavor", projectProvider.get()?.properties?.getProperty("polyglot-kotlin.flavor", "mixed") ?: "mixed") - ModelScriptWriter(this, config).write(model) - val kotlinScript = toString() - if (log.isDebugEnabled) { - log.debug(({ "POM model converted from XML: \n$kotlinScript\n" })()) - } - kotlinScript + override fun write(output: Writer, options: Map, model: Model) { + output.write( + with(StringWriter(1024)) { + val config = HashMap(options) + config.putIfAbsent( + "xml.dsl.enabled", + projectProvider + .get() + ?.properties + ?.getProperty("polyglot-kotlin.xml-dsl-enabled", "true") ?: "true") + config.putIfAbsent( + "flavor", + projectProvider.get()?.properties?.getProperty("polyglot-kotlin.flavor", "mixed") + ?: "mixed") + ModelScriptWriter(this, config).write(model) + val kotlinScript = toString() + if (log.isDebugEnabled) { + log.debug(({ "POM model converted from XML: \n$kotlinScript\n" })()) + } + kotlinScript }) - output.flush() - } - + output.flush() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Activation.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Activation.kt index da6d363c..b31a55e1 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Activation.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Activation.kt @@ -3,44 +3,40 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Activation : org.apache.maven.model.Activation(), Cloneable { - @PomDsl - fun os(name: String? = null, block: ActivationOS.(ActivationOS) -> Unit) { - val os = ActivationOS().apply { - this.name = name - } - block(os, os) - this.os = os - } + @PomDsl + fun os(name: String? = null, block: ActivationOS.(ActivationOS) -> Unit) { + val os = ActivationOS().apply { this.name = name } + block(os, os) + this.os = os + } - @PomDsl - fun property(name: String? = null, block: ActivationProperty.(ActivationProperty) -> Unit) { - val property = ActivationProperty().apply { - this.name = name - } - block(property, property) - this.property = property - } + @PomDsl + fun property(name: String? = null, block: ActivationProperty.(ActivationProperty) -> Unit) { + val property = ActivationProperty().apply { this.name = name } + block(property, property) + this.property = property + } - @PomDsl - fun file(block: ActivationFile.(ActivationFile) -> Unit) { - val file = ActivationFile() - block(file, file) - this.file = file - } + @PomDsl + fun file(block: ActivationFile.(ActivationFile) -> Unit) { + val file = ActivationFile() + block(file, file) + this.file = file + } - @PomDsl - fun jdk(jdk: String): Activation { - this.jdk = jdk - return this - } + @PomDsl + fun jdk(jdk: String): Activation { + this.jdk = jdk + return this + } - @PomDsl - fun activeByDefault(activeByDefault: Boolean = true): Activation { - this.isActiveByDefault = activeByDefault - return this - } + @PomDsl + fun activeByDefault(activeByDefault: Boolean = true): Activation { + this.isActiveByDefault = activeByDefault + return this + } - override fun clone(): org.apache.maven.model.Activation { - return super.clone() - } + override fun clone(): org.apache.maven.model.Activation { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationFile.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationFile.kt index cc6ddab2..ed20bcf1 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationFile.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationFile.kt @@ -3,19 +3,19 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ActivationFile : org.apache.maven.model.ActivationFile(), Cloneable { - @PomDsl - fun missing(missing: String): ActivationFile { - this.missing = missing - return this - } + @PomDsl + fun missing(missing: String): ActivationFile { + this.missing = missing + return this + } - @PomDsl - fun exists(exists: String): ActivationFile { - this.exists = exists - return this - } + @PomDsl + fun exists(exists: String): ActivationFile { + this.exists = exists + return this + } - override fun clone(): org.apache.maven.model.ActivationFile { - return super.clone() - } + override fun clone(): org.apache.maven.model.ActivationFile { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationOS.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationOS.kt index 467d9fea..fe9e3d4b 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationOS.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationOS.kt @@ -3,31 +3,31 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ActivationOS : org.apache.maven.model.ActivationOS(), Cloneable { - @PomDsl - fun name(name: String): ActivationOS { - this.name = name - return this - } + @PomDsl + fun name(name: String): ActivationOS { + this.name = name + return this + } - @PomDsl - fun family(family: String): ActivationOS { - this.family = family - return this - } + @PomDsl + fun family(family: String): ActivationOS { + this.family = family + return this + } - @PomDsl - fun arch(arch: String): ActivationOS { - this.arch = arch - return this - } + @PomDsl + fun arch(arch: String): ActivationOS { + this.arch = arch + return this + } - @PomDsl - fun version(version: String): ActivationOS { - this.version = version - return this - } + @PomDsl + fun version(version: String): ActivationOS { + this.version = version + return this + } - override fun clone(): org.apache.maven.model.ActivationOS { - return super.clone() - } + override fun clone(): org.apache.maven.model.ActivationOS { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationProperty.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationProperty.kt index eadc2987..38fcec1c 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationProperty.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ActivationProperty.kt @@ -3,19 +3,19 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ActivationProperty : org.apache.maven.model.ActivationProperty(), Cloneable { - @PomDsl - fun name(name: String): ActivationProperty { - this.name = name - return this - } + @PomDsl + fun name(name: String): ActivationProperty { + this.name = name + return this + } - @PomDsl - fun value(value: String): ActivationProperty { - this.value = value - return this - } + @PomDsl + fun value(value: String): ActivationProperty { + this.value = value + return this + } - override fun clone(): org.apache.maven.model.ActivationProperty { - return super.clone() - } + override fun clone(): org.apache.maven.model.ActivationProperty { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Build.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Build.kt index fb5da6ce..7be9d4d2 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Build.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Build.kt @@ -3,109 +3,110 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl open class Build : org.apache.maven.model.Build(), Cloneable { - @PomDsl - fun sourceDirectory(sourceDirectory: String): Build { - this.sourceDirectory = sourceDirectory - return this - } - - @PomDsl - fun scriptSourceDirectory(scriptSourceDirectory: String): Build { - this.scriptSourceDirectory = scriptSourceDirectory - return this - } - - @PomDsl - fun testSourceDirectory(testSourceDirectory: String): Build { - this.testSourceDirectory = testSourceDirectory - return this - } - - @PomDsl - fun outputDirectory(outputDirectory: String): Build { - this.outputDirectory = outputDirectory - return this - } - - @PomDsl - fun testOutputDirectory(testOutputDirectory: String): Build { - this.testOutputDirectory = testOutputDirectory - return this - } - - @PomDsl - fun defaultGoal(defaultGoal: String): Build { - this.defaultGoal = defaultGoal - return this - } - - @PomDsl - fun directory(directory: String): Build { - this.directory = directory - return this - } - - @PomDsl - fun finalName(finalName: String): Build { - this.finalName = finalName - return this - } - - @PomDsl - fun resources(block: ResourceList.(ResourceList) -> Unit) { - val resources = ResourceList() - block(resources, resources) - this.resources = resources - } - - @PomDsl - fun testResources(block: TestResourceList.(TestResourceList) -> Unit) { - val testResources = TestResourceList() - block(testResources, testResources) - this.testResources = testResources - } - - @PomDsl - fun extensions(block: ExtensionList.(ExtensionList) -> Unit) { - val extensions = ExtensionList() - block(extensions, extensions) - this.extensions = extensions - } - - @PomDsl - fun pluginManagement(block: PluginManagement.(PluginManagement) -> Unit) { - val pluginManagement = PluginManagement() - block.invoke(pluginManagement, pluginManagement) - this.pluginManagement = pluginManagement - } - - @PomDsl - fun plugins(block: PluginList.(PluginList) -> Unit) { - val plugins = PluginList() - block.invoke(plugins, plugins) - this.plugins = plugins - } - - @PomDsl - fun extensions(vararg gav: String): Build { - this.extensions = gav.map { value -> - val (groupId, artifactId, version) = splitCoordinates(value) - Extension().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - } + @PomDsl + fun sourceDirectory(sourceDirectory: String): Build { + this.sourceDirectory = sourceDirectory + return this + } + + @PomDsl + fun scriptSourceDirectory(scriptSourceDirectory: String): Build { + this.scriptSourceDirectory = scriptSourceDirectory + return this + } + + @PomDsl + fun testSourceDirectory(testSourceDirectory: String): Build { + this.testSourceDirectory = testSourceDirectory + return this + } + + @PomDsl + fun outputDirectory(outputDirectory: String): Build { + this.outputDirectory = outputDirectory + return this + } + + @PomDsl + fun testOutputDirectory(testOutputDirectory: String): Build { + this.testOutputDirectory = testOutputDirectory + return this + } + + @PomDsl + fun defaultGoal(defaultGoal: String): Build { + this.defaultGoal = defaultGoal + return this + } + + @PomDsl + fun directory(directory: String): Build { + this.directory = directory + return this + } + + @PomDsl + fun finalName(finalName: String): Build { + this.finalName = finalName + return this + } + + @PomDsl + fun resources(block: ResourceList.(ResourceList) -> Unit) { + val resources = ResourceList() + block(resources, resources) + this.resources = resources + } + + @PomDsl + fun testResources(block: TestResourceList.(TestResourceList) -> Unit) { + val testResources = TestResourceList() + block(testResources, testResources) + this.testResources = testResources + } + + @PomDsl + fun extensions(block: ExtensionList.(ExtensionList) -> Unit) { + val extensions = ExtensionList() + block(extensions, extensions) + this.extensions = extensions + } + + @PomDsl + fun pluginManagement(block: PluginManagement.(PluginManagement) -> Unit) { + val pluginManagement = PluginManagement() + block.invoke(pluginManagement, pluginManagement) + this.pluginManagement = pluginManagement + } + + @PomDsl + fun plugins(block: PluginList.(PluginList) -> Unit) { + val plugins = PluginList() + block.invoke(plugins, plugins) + this.plugins = plugins + } + + @PomDsl + fun extensions(vararg gav: String): Build { + this.extensions = + gav.map { value -> + val (groupId, artifactId, version) = splitCoordinates(value) + Extension().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + } } - return this - } - - @PomDsl - fun filters(vararg filters: String): Build { - this.filters = filters.asList() - return this - } - - override fun clone(): org.apache.maven.model.Build { - return super.clone() - } + return this + } + + @PomDsl + fun filters(vararg filters: String): Build { + this.filters = filters.asList() + return this + } + + override fun clone(): org.apache.maven.model.Build { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/CiManagement.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/CiManagement.kt index d343bc76..145c69f3 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/CiManagement.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/CiManagement.kt @@ -3,29 +3,27 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class CiManagement : org.apache.maven.model.CiManagement(), Cloneable { - @PomDsl - fun system(system: String): CiManagement { - this.system = system - return this - } + @PomDsl + fun system(system: String): CiManagement { + this.system = system + return this + } - @PomDsl - fun url(url: String): CiManagement { - this.url = url - return this - } + @PomDsl + fun url(url: String): CiManagement { + this.url = url + return this + } - /** - * Provides a callback for defining a list of notifiers. - */ - @PomDsl - fun notifiers(block: NotifierList.(NotifierList) -> Unit) { - val notifiers = NotifierList() - block.invoke(notifiers, notifiers) - this.notifiers = notifiers - } + /** Provides a callback for defining a list of notifiers. */ + @PomDsl + fun notifiers(block: NotifierList.(NotifierList) -> Unit) { + val notifiers = NotifierList() + block.invoke(notifiers, notifiers) + this.notifiers = notifiers + } - override fun clone(): org.apache.maven.model.CiManagement { - return super.clone() - } + override fun clone(): org.apache.maven.model.CiManagement { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Contributor.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Contributor.kt index 8d3e5473..a6797bff 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Contributor.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Contributor.kt @@ -3,61 +3,57 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Contributor : org.apache.maven.model.Contributor(), Cloneable { - @PomDsl - fun name(name: String): Contributor { - this.name = name - return this - } - - @PomDsl - fun email(email: String): Contributor { - this.email = email - return this - } - - @PomDsl - fun url(url: String): Contributor { - this.url = url - return this - } - - @PomDsl - fun organization(organization: String): Contributor { - this.organization = organization - return this - } - - @PomDsl - fun organizationUrl(organizationUrl: String): Contributor { - this.organizationUrl = organizationUrl - return this - } - - @PomDsl - fun roles(vararg roles: String): Contributor { - this.roles = roles.asList() - return this - } - - @PomDsl - fun timezone(timezone: String): Contributor { - this.timezone = timezone - return this - } - - /** - * Provides a callback for defining additional contributor properties. - */ - @PomDsl - fun properties(block: Properties.(Properties) -> Unit) { - val properties = Properties() - block.invoke(properties, properties) - this.properties = propertiesFactory().apply { - putAll(properties.entries()) - } - } - - override fun clone(): org.apache.maven.model.Contributor { - return super.clone() - } + @PomDsl + fun name(name: String): Contributor { + this.name = name + return this + } + + @PomDsl + fun email(email: String): Contributor { + this.email = email + return this + } + + @PomDsl + fun url(url: String): Contributor { + this.url = url + return this + } + + @PomDsl + fun organization(organization: String): Contributor { + this.organization = organization + return this + } + + @PomDsl + fun organizationUrl(organizationUrl: String): Contributor { + this.organizationUrl = organizationUrl + return this + } + + @PomDsl + fun roles(vararg roles: String): Contributor { + this.roles = roles.asList() + return this + } + + @PomDsl + fun timezone(timezone: String): Contributor { + this.timezone = timezone + return this + } + + /** Provides a callback for defining additional contributor properties. */ + @PomDsl + fun properties(block: Properties.(Properties) -> Unit) { + val properties = Properties() + block.invoke(properties, properties) + this.properties = propertiesFactory().apply { putAll(properties.entries()) } + } + + override fun clone(): org.apache.maven.model.Contributor { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ContributorList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ContributorList.kt index d7ce0e2c..bbe9c2a4 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ContributorList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ContributorList.kt @@ -3,39 +3,40 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ContributorList : ArrayList(), Cloneable { - private val nameAndEmailRegex: Regex = Regex("""([^<]+?)\s*<\s*(([^>@]+)@[^>]+)\s*>""") - private val emailRegex: Regex = Regex("""([^@]+)@.+""") + private val nameAndEmailRegex: Regex = Regex("""([^<]+?)\s*<\s*(([^>@]+)@[^>]+)\s*>""") + private val emailRegex: Regex = Regex("""([^@]+)@.+""") - /** - * Provides a callback for defining a new contributor entry. If formatted as `name `, the name will be - * extracted from the first part of the string, and the email from the second. - * - * @param name the name of the contributor - */ - @PomDsl - fun contributor(name: String? = null, block: (Contributor.(Contributor) -> Unit)? = null) { - val contributor = Contributor().apply { - if (name != null) { - val nameAndEmailMatch = this@ContributorList.nameAndEmailRegex.matchEntire(name) - if (nameAndEmailMatch != null) { - this.name = nameAndEmailMatch.groupValues[1] - this.email = nameAndEmailMatch.groupValues[2] - } else { - val emailMatch = this@ContributorList.emailRegex.matchEntire(name) - if (emailMatch != null) { - this.name = emailMatch.groupValues[1] - this.email = emailMatch.groupValues[0] - } else { - this.name = name - } - } + /** + * Provides a callback for defining a new contributor entry. If formatted as `name `, the + * name will be extracted from the first part of the string, and the email from the second. + * + * @param name the name of the contributor + */ + @PomDsl + fun contributor(name: String? = null, block: (Contributor.(Contributor) -> Unit)? = null) { + val contributor = + Contributor().apply { + if (name != null) { + val nameAndEmailMatch = this@ContributorList.nameAndEmailRegex.matchEntire(name) + if (nameAndEmailMatch != null) { + this.name = nameAndEmailMatch.groupValues[1] + this.email = nameAndEmailMatch.groupValues[2] + } else { + val emailMatch = this@ContributorList.emailRegex.matchEntire(name) + if (emailMatch != null) { + this.name = emailMatch.groupValues[1] + this.email = emailMatch.groupValues[0] + } else { + this.name = name + } } + } } - block?.invoke(contributor, contributor) - add(contributor) - } + block?.invoke(contributor, contributor) + add(contributor) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupport.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupport.kt index d2181277..e1272801 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupport.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupport.kt @@ -9,39 +9,40 @@ private val coordinatesDelimiter = Regex(":") /** * Splits the supplied artifact identifier into its constituent parts. * - * @param coordinates an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` + * @param coordinates an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` * @param size the size of the array to be returned */ fun splitCoordinates(coordinates: String?, size: Int = 5): Array { - val list = Array(size) { null } - coordinates?.split(coordinatesDelimiter, size)?.forEachIndexed { i, str -> - list[i] = if (str.isBlank()) null else str.trim() - } - return list + val list = Array(size) { null } + coordinates?.split(coordinatesDelimiter, size)?.forEachIndexed { i, str -> + list[i] = if (str.isBlank()) null else str.trim() + } + return list } fun MutableCollection.addAll(vararg t: T) { - t.forEach { add(it) } + t.forEach { add(it) } } fun MutableCollection.addFirstNonNull(vararg t: T?) { - val first = t.firstOrNull { it != null } - if (first != null) add(first) + val first = t.firstOrNull { it != null } + if (first != null) add(first) } fun MutableCollection.addAllNonNull(vararg t: T?) { - t.forEach { if (it != null) add(it) } + t.forEach { if (it != null) add(it) } } @Suppress("UNCHECKED_CAST") fun cast(o: Any): T { - return o as T + return o as T } fun escape(text: String): String { - return escapeJava(text).replace("\$", "\\\$") + return escapeJava(text).replace("\$", "\\\$") } fun escapeRaw(text: String): String { - return text.replace("""$""", """${'$'}{'$'}""") + return text.replace("""$""", """${'$'}{'$'}""") } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Dependency.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Dependency.kt index 447e6210..a8783e03 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Dependency.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Dependency.kt @@ -3,81 +3,81 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Dependency : org.apache.maven.model.Dependency(), Cloneable { - @PomDsl - fun groupId(groupId: String): Dependency { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): Dependency { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): Dependency { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): Dependency { + this.artifactId = artifactId + return this + } - @PomDsl - fun version(version: String): Dependency { - this.version = version - return this - } + @PomDsl + fun version(version: String): Dependency { + this.version = version + return this + } - @PomDsl - fun type(type: String): Dependency { - this.type = type - return this - } + @PomDsl + fun type(type: String): Dependency { + this.type = type + return this + } - @PomDsl - fun classifier(classifier: String): Dependency { - this.classifier = classifier - return this - } + @PomDsl + fun classifier(classifier: String): Dependency { + this.classifier = classifier + return this + } - @PomDsl - fun scope(scope: String): Dependency { - this.scope = scope - return this - } + @PomDsl + fun scope(scope: String): Dependency { + this.scope = scope + return this + } - @PomDsl - fun systemPath(systemPath: String): Dependency { - this.systemPath = systemPath - return this - } + @PomDsl + fun systemPath(systemPath: String): Dependency { + this.systemPath = systemPath + return this + } - @PomDsl - fun optional(optional: Boolean = true): Dependency { - this.isOptional = optional - return this - } + @PomDsl + fun optional(optional: Boolean = true): Dependency { + this.isOptional = optional + return this + } - /** - * Provides a callback for defining dependency exclusions. - */ - @PomDsl - fun exclusions(block: ExclusionList.(ExclusionList) -> Unit): Dependency { - val exclusionList = ExclusionList() - block(exclusionList, exclusionList) - this.exclusions = exclusionList - return this - } + /** Provides a callback for defining dependency exclusions. */ + @PomDsl + fun exclusions(block: ExclusionList.(ExclusionList) -> Unit): Dependency { + val exclusionList = ExclusionList() + block(exclusionList, exclusionList) + this.exclusions = exclusionList + return this + } - /** - * Excludes the artifacts having the specified `groupId:artifactId`. The wildcard `*` character can be used to - * exclude matching artifacts. - */ - @PomDsl - fun exclusions(vararg ga: String): Dependency { - this.exclusions = ga.map { splitCoordinates(it) }.map { (groupId, artifactId) -> - Exclusion().apply { + /** + * Excludes the artifacts having the specified `groupId:artifactId`. The wildcard `*` character + * can be used to exclude matching artifacts. + */ + @PomDsl + fun exclusions(vararg ga: String): Dependency { + this.exclusions = + ga.map { splitCoordinates(it) } + .map { (groupId, artifactId) -> + Exclusion().apply { this.groupId = groupId this.artifactId = artifactId + } } - } - return this - } + return this + } - override fun clone(): org.apache.maven.model.Dependency { - return super.clone() - } + override fun clone(): org.apache.maven.model.Dependency { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyList.kt index 71e7c889..df2716ce 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyList.kt @@ -3,163 +3,177 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl open class DependencyList : ArrayList(), Cloneable { - /** - * Adds a dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun dependency(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - val (groupId, artifactId, version, type, classifier) = splitCoordinates(gavtc) - return Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - if (type != null) this.type = type - this.classifier = classifier - this@DependencyList.add(this) - block?.invoke(this, this) - } + /** + * Adds a dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun dependency( + gavtc: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + val (groupId, artifactId, version, type, classifier) = splitCoordinates(gavtc) + return Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + if (type != null) this.type = type + this.classifier = classifier + this@DependencyList.add(this) + block?.invoke(this, this) } + } - /** - * Adds a "compile" scope dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun compile(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.scope = "compile" - } - } + /** + * Adds a "compile" scope dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun compile(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { + return dependency(gavtc, block).apply { this.scope = "compile" } + } - /** - * Adds a "test" scope dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun test(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.scope = "test" - } - } + /** + * Adds a "test" scope dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun test(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { + return dependency(gavtc, block).apply { this.scope = "test" } + } - /** - * Adds a "provided" scope dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun provided(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.scope = "provided" - } - } + /** + * Adds a "provided" scope dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun provided( + gavtc: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency(gavtc, block).apply { this.scope = "provided" } + } - /** - * Adds a "runtime" scope dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun runtime(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.scope = "runtime" - } - } + /** + * Adds a "runtime" scope dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun runtime(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { + return dependency(gavtc, block).apply { this.scope = "runtime" } + } - /** - * Adds a "system" scope dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param systemPath the location of the system dependency, relative to `${basedir}` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun system(gavtc: String? = null, systemPath: String, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.scope = "system" - this.systemPath = systemPath - } + /** + * Adds a "system" scope dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param systemPath the location of the system dependency, relative to `${basedir}` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun system( + gavtc: String? = null, + systemPath: String, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency(gavtc, block).apply { + this.scope = "system" + this.systemPath = systemPath } + } - /** - * Adds an optional (non-transitive) dependency identified by the supplied coordinates. - * - * @param gavtc an artifact identifier in the form `groupId:artifactId[:version][:type][:classifier]` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun optional(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gavtc, block).apply { - this.isOptional = true - } - } + /** + * Adds an optional (non-transitive) dependency identified by the supplied coordinates. + * + * @param gavtc an artifact identifier in the form + * `groupId:artifactId[:version][:type][:classifier]` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun optional( + gavtc: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency(gavtc, block).apply { this.isOptional = true } + } - /** - * Adds a dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param scope the dependency scope ("compile", "runtime", "test", "provided", "system") - * @param systemPath the dependency system path when the scope is "system" - * @param block a callback for performing additional initialization - */ - @PomDsl - fun dependency(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - scope: String? = null, - systemPath: String? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - this.type = type - this.classifier = classifier - if (optional != null) this.isOptional = optional - this.scope = scope - this.systemPath = systemPath - this@DependencyList.add(this) - block?.invoke(this, this) - } + /** + * Adds a dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param scope the dependency scope ("compile", "runtime", "test", "provided", "system") + * @param systemPath the dependency system path when the scope is "system" + * @param block a callback for performing additional initialization + */ + @PomDsl + fun dependency( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + scope: String? = null, + systemPath: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + this.type = type + this.classifier = classifier + if (optional != null) this.isOptional = optional + this.scope = scope + this.systemPath = systemPath + this@DependencyList.add(this) + block?.invoke(this, this) } + } - /** - * Adds a "compile" scope dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param block a callback for performing additional initialization - */ - @PomDsl - fun compile(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + /** + * Adds a "compile" scope dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param block a callback for performing additional initialization + */ + @PomDsl + fun compile( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, @@ -168,31 +182,31 @@ open class DependencyList : ArrayList(), Clon optional = optional, scope = "compile", block = block) - .apply { - scope = "compile" - } - } + .apply { scope = "compile" } + } - /** - * Adds a "test" scope dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param block a callback for performing additional initialization - */ - @PomDsl - fun test(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + /** + * Adds a "test" scope dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param block a callback for performing additional initialization + */ + @PomDsl + fun test( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, @@ -201,31 +215,31 @@ open class DependencyList : ArrayList(), Clon optional = optional, scope = "test", block = block) - .apply { - scope = "test" - } - } + .apply { scope = "test" } + } - /** - * Adds a "provided" scope dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param block a callback for performing additional initialization - */ - @PomDsl - fun provided(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + /** + * Adds a "provided" scope dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param block a callback for performing additional initialization + */ + @PomDsl + fun provided( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, @@ -234,31 +248,31 @@ open class DependencyList : ArrayList(), Clon optional = optional, scope = "provided", block = block) - .apply { - this.scope = "provided" - } - } + .apply { this.scope = "provided" } + } - /** - * Adds a "runtime" scope dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param block a callback for performing additional initialization - */ - @PomDsl - fun runtime(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + /** + * Adds a "runtime" scope dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param block a callback for performing additional initialization + */ + @PomDsl + fun runtime( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, @@ -267,33 +281,33 @@ open class DependencyList : ArrayList(), Clon optional = optional, scope = "runtime", block = block) - .apply { - this.scope = "runtime" - } - } + .apply { this.scope = "runtime" } + } - /** - * Adds a "system" scope dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) - * @param systemPath the location of the system dependency relative to `${basedir}` - * @param block a callback for performing additional initialization - */ - @PomDsl - fun system(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - systemPath: String, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + /** + * Adds a "system" scope dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param optional a boolean flag indicating whether the dependency is optional (non-transitive) + * @param systemPath the location of the system dependency relative to `${basedir}` + * @param block a callback for performing additional initialization + */ + @PomDsl + fun system( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + systemPath: String, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, @@ -303,42 +317,44 @@ open class DependencyList : ArrayList(), Clon scope = "system", systemPath = systemPath, block = block) - .apply { - this.scope = "system" - this.systemPath = systemPath - } - } + .apply { + this.scope = "system" + this.systemPath = systemPath + } + } - /** - * Adds an optional dependency identified by the supplied coordinate parameters. - * - * @param groupId the dependency groupId - * @param artifactId the dependency artifactId - * @param version the dependency version - * @param type the dependency packaging type - * @param classifier the dependency classifier - * @param block a callback for performing additional initialization - */ - @PomDsl - fun optional(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - scope: String? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( - groupId = groupId, - artifactId = artifactId, - version = version, - scope = scope, - type = type, - classifier = classifier, - optional = true, - block = block) - } + /** + * Adds an optional dependency identified by the supplied coordinate parameters. + * + * @param groupId the dependency groupId + * @param artifactId the dependency artifactId + * @param version the dependency version + * @param type the dependency packaging type + * @param classifier the dependency classifier + * @param block a callback for performing additional initialization + */ + @PomDsl + fun optional( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + scope: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( + groupId = groupId, + artifactId = artifactId, + version = version, + scope = scope, + type = type, + classifier = classifier, + optional = true, + block = block) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyManagement.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyManagement.kt index aa7a95ed..fd6fd60e 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyManagement.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DependencyManagement.kt @@ -3,14 +3,14 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class DependencyManagement : org.apache.maven.model.DependencyManagement(), Cloneable { - @PomDsl - fun dependencies(block: ManagedDependencyList.(ManagedDependencyList) -> Unit) { - val dependencies = ManagedDependencyList() - block.invoke(dependencies, dependencies) - this.dependencies = dependencies - } + @PomDsl + fun dependencies(block: ManagedDependencyList.(ManagedDependencyList) -> Unit) { + val dependencies = ManagedDependencyList() + block.invoke(dependencies, dependencies) + this.dependencies = dependencies + } - override fun clone(): org.apache.maven.model.DependencyManagement { - return super.clone() - } + override fun clone(): org.apache.maven.model.DependencyManagement { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeploymentRepository.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeploymentRepository.kt index 80611158..baa64d12 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeploymentRepository.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeploymentRepository.kt @@ -3,36 +3,36 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class DeploymentRepository : org.apache.maven.model.DeploymentRepository(), Cloneable { - @PomDsl - fun uniqueVersion(uniqueVersion: Boolean = true) { - this.isUniqueVersion = uniqueVersion - } + @PomDsl + fun uniqueVersion(uniqueVersion: Boolean = true) { + this.isUniqueVersion = uniqueVersion + } - @PomDsl - fun id(id: String): DeploymentRepository { - this.id = id - return this - } + @PomDsl + fun id(id: String): DeploymentRepository { + this.id = id + return this + } - @PomDsl - fun name(name: String): DeploymentRepository { - this.name = name - return this - } + @PomDsl + fun name(name: String): DeploymentRepository { + this.name = name + return this + } - @PomDsl - fun url(url: String): DeploymentRepository { - this.url = url - return this - } + @PomDsl + fun url(url: String): DeploymentRepository { + this.url = url + return this + } - @PomDsl - fun layout(layout: String): DeploymentRepository { - this.layout = layout - return this - } + @PomDsl + fun layout(layout: String): DeploymentRepository { + this.layout = layout + return this + } - override fun clone(): org.apache.maven.model.DeploymentRepository { - return super.clone() - } + override fun clone(): org.apache.maven.model.DeploymentRepository { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Developer.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Developer.kt index fe6dfcf2..dc77a64c 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Developer.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Developer.kt @@ -3,67 +3,63 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Developer : org.apache.maven.model.Developer(), Cloneable { - @PomDsl - fun id(id: String): Developer { - this.id = id - return this - } + @PomDsl + fun id(id: String): Developer { + this.id = id + return this + } - @PomDsl - fun name(name: String): Developer { - this.name = name - return this - } + @PomDsl + fun name(name: String): Developer { + this.name = name + return this + } - @PomDsl - fun email(email: String): Developer { - this.email = email - return this - } + @PomDsl + fun email(email: String): Developer { + this.email = email + return this + } - @PomDsl - fun url(url: String): Developer { - this.url = url - return this - } + @PomDsl + fun url(url: String): Developer { + this.url = url + return this + } - @PomDsl - fun organization(organization: String): Developer { - this.organization = organization - return this - } + @PomDsl + fun organization(organization: String): Developer { + this.organization = organization + return this + } - @PomDsl - fun organizationUrl(organizationUrl: String): Developer { - this.organizationUrl = organizationUrl - return this - } + @PomDsl + fun organizationUrl(organizationUrl: String): Developer { + this.organizationUrl = organizationUrl + return this + } - @PomDsl - fun roles(vararg roles: String): Developer { - this.roles = roles.asList() - return this - } + @PomDsl + fun roles(vararg roles: String): Developer { + this.roles = roles.asList() + return this + } - @PomDsl - fun timezone(timezone: String): Developer { - this.timezone = timezone - return this - } + @PomDsl + fun timezone(timezone: String): Developer { + this.timezone = timezone + return this + } - /** - * Provides a callback for defining additional developer properties. - */ - @PomDsl - fun properties(block: Properties.(Properties) -> Unit) { - val properties = Properties() - block.invoke(properties, properties) - this.properties = propertiesFactory().apply { - putAll(properties.entries()) - } - } + /** Provides a callback for defining additional developer properties. */ + @PomDsl + fun properties(block: Properties.(Properties) -> Unit) { + val properties = Properties() + block.invoke(properties, properties) + this.properties = propertiesFactory().apply { putAll(properties.entries()) } + } - override fun clone(): org.apache.maven.model.Developer { - return super.clone() - } + override fun clone(): org.apache.maven.model.Developer { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeveloperList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeveloperList.kt index ad3eca18..171ad846 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeveloperList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DeveloperList.kt @@ -3,43 +3,44 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class DeveloperList : ArrayList(), Cloneable { - private val nameAndEmailRegex: Regex = Regex("""([^<]+?)\s*<\s*(([^>@]+)@[^>]+)\s*>""") - private val emailRegex: Regex = Regex("""([^@]+)@.+""") + private val nameAndEmailRegex: Regex = Regex("""([^<]+?)\s*<\s*(([^>@]+)@[^>]+)\s*>""") + private val emailRegex: Regex = Regex("""([^@]+)@.+""") - /** - * Provides a callback for defining a new developer entry. If formatted as `name `, the name will be - * extracted from the first part of the string, and the email from the second. The ID will be extracted from the - * email. - * - * @param nameOrId the name or id of the developer entry - */ - @PomDsl - fun developer(nameOrId: String? = null, block: (Developer.(Developer) -> Unit)? = null) { - val developer = Developer().apply { - if (nameOrId != null) { - val nameAndEmailMatch = this@DeveloperList.nameAndEmailRegex.matchEntire(nameOrId) - if (nameAndEmailMatch != null) { - this.id = nameAndEmailMatch.groupValues[3] - this.name = nameAndEmailMatch.groupValues[1] - this.email = nameAndEmailMatch.groupValues[2] - } else { - val emailMatch = this@DeveloperList.emailRegex.matchEntire(nameOrId) - if (emailMatch != null) { - this.id = emailMatch.groupValues[1] - this.name = emailMatch.groupValues[1] - this.email = emailMatch.groupValues[0] - } else { - this.id = nameOrId - this.name = nameOrId - } - } + /** + * Provides a callback for defining a new developer entry. If formatted as `name `, the + * name will be extracted from the first part of the string, and the email from the second. The ID + * will be extracted from the email. + * + * @param nameOrId the name or id of the developer entry + */ + @PomDsl + fun developer(nameOrId: String? = null, block: (Developer.(Developer) -> Unit)? = null) { + val developer = + Developer().apply { + if (nameOrId != null) { + val nameAndEmailMatch = this@DeveloperList.nameAndEmailRegex.matchEntire(nameOrId) + if (nameAndEmailMatch != null) { + this.id = nameAndEmailMatch.groupValues[3] + this.name = nameAndEmailMatch.groupValues[1] + this.email = nameAndEmailMatch.groupValues[2] + } else { + val emailMatch = this@DeveloperList.emailRegex.matchEntire(nameOrId) + if (emailMatch != null) { + this.id = emailMatch.groupValues[1] + this.name = emailMatch.groupValues[1] + this.email = emailMatch.groupValues[0] + } else { + this.id = nameOrId + this.name = nameOrId + } } + } } - block?.invoke(developer, developer) - add(developer) - } + block?.invoke(developer, developer) + add(developer) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DistributionManagement.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DistributionManagement.kt index 4d2b232a..89793406 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DistributionManagement.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DistributionManagement.kt @@ -3,59 +3,69 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class DistributionManagement : org.apache.maven.model.DistributionManagement(), Cloneable { - @PomDsl - fun downloadUrl(downloadUrl: String) { - this.downloadUrl = downloadUrl - } - - @PomDsl - fun status(status: String) { - this.status = status - } - - @PomDsl - fun repository(nameOrId: String? = null, block: DeploymentRepository.(DeploymentRepository) -> Unit) { - val repository = DeploymentRepository().apply { - this.id = nameOrId - this.name = nameOrId + @PomDsl + fun downloadUrl(downloadUrl: String) { + this.downloadUrl = downloadUrl + } + + @PomDsl + fun status(status: String) { + this.status = status + } + + @PomDsl + fun repository( + nameOrId: String? = null, + block: DeploymentRepository.(DeploymentRepository) -> Unit + ) { + val repository = + DeploymentRepository().apply { + this.id = nameOrId + this.name = nameOrId } - block.invoke(repository, repository) - this.repository = repository - } - - @PomDsl - fun snapshotRepository(nameOrId: String? = null, block: DeploymentRepository.(DeploymentRepository) -> Unit) { - val snapshotRepository = DeploymentRepository().apply { - this.id = nameOrId - this.name = nameOrId + block.invoke(repository, repository) + this.repository = repository + } + + @PomDsl + fun snapshotRepository( + nameOrId: String? = null, + block: DeploymentRepository.(DeploymentRepository) -> Unit + ) { + val snapshotRepository = + DeploymentRepository().apply { + this.id = nameOrId + this.name = nameOrId } - block.invoke(snapshotRepository, snapshotRepository) - this.snapshotRepository = snapshotRepository - } - - @PomDsl - fun site(nameOrId: String? = null, block: Site.(Site) -> Unit) { - val site = Site().apply { - this.id = nameOrId - this.name = nameOrId + block.invoke(snapshotRepository, snapshotRepository) + this.snapshotRepository = snapshotRepository + } + + @PomDsl + fun site(nameOrId: String? = null, block: Site.(Site) -> Unit) { + val site = + Site().apply { + this.id = nameOrId + this.name = nameOrId } - block.invoke(site, site) - this.site = site - } - - @PomDsl - fun relocation(gav: String? = null, block: Relocation.(Relocation) -> Unit) { - val (groupId, artifactId, version) = splitCoordinates(gav, 3) - val relocation = Relocation().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + block.invoke(site, site) + this.site = site + } + + @PomDsl + fun relocation(gav: String? = null, block: Relocation.(Relocation) -> Unit) { + val (groupId, artifactId, version) = splitCoordinates(gav, 3) + val relocation = + Relocation().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - block.invoke(relocation, relocation) - this.relocation = relocation - } + block.invoke(relocation, relocation) + this.relocation = relocation + } - override fun clone(): org.apache.maven.model.DistributionManagement { - return super.clone() - } + override fun clone(): org.apache.maven.model.DistributionManagement { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Exclusion.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Exclusion.kt index d1cbaa71..a7b7524c 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Exclusion.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Exclusion.kt @@ -3,19 +3,19 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Exclusion : org.apache.maven.model.Exclusion(), Cloneable { - @PomDsl - fun groupId(groupId: String): Exclusion { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): Exclusion { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): Exclusion { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): Exclusion { + this.artifactId = artifactId + return this + } - override fun clone(): org.apache.maven.model.Exclusion { - return super.clone() - } + override fun clone(): org.apache.maven.model.Exclusion { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExclusionList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExclusionList.kt index fa0d5b1a..9b8ac973 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExclusionList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExclusionList.kt @@ -3,17 +3,15 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ExclusionList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new dependency exclusion. - */ - @PomDsl - fun exclusion(block: Exclusion.(Exclusion) -> Unit) { - val exclusion = Exclusion() - block(exclusion, exclusion) - add(exclusion) - } + /** Provides a callback for defining a new dependency exclusion. */ + @PomDsl + fun exclusion(block: Exclusion.(Exclusion) -> Unit) { + val exclusion = Exclusion() + block(exclusion, exclusion) + add(exclusion) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Extension.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Extension.kt index c7f8d9e7..7f611dbf 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Extension.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Extension.kt @@ -1,27 +1,27 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl -class Extension : org.apache.maven.model.Extension(), Cloneable { +class Extension : org.apache.maven.model.Extension(), Cloneable { - @PomDsl - fun groupId(groupId: String): Extension { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): Extension { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): Extension { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): Extension { + this.artifactId = artifactId + return this + } - @PomDsl - fun version(version: String): Extension { - this.version = version - return this - } + @PomDsl + fun version(version: String): Extension { + this.version = version + return this + } - override fun clone(): org.apache.maven.model.Extension { - return super.clone() - } + override fun clone(): org.apache.maven.model.Extension { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExtensionList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExtensionList.kt index b0eb1ff6..e3ed3a92 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExtensionList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ExtensionList.kt @@ -3,22 +3,20 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ExtensionList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new build extension. - */ - @PomDsl - fun extension(gav: String? = null, block: (Extension.(Extension) -> Unit)? = null): Extension { - val (groupId, artifactId, version) = splitCoordinates(gav, 3) - return Extension().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - this@ExtensionList.add(this) - block?.invoke(this, this) - } + /** Provides a callback for defining a new build extension. */ + @PomDsl + fun extension(gav: String? = null, block: (Extension.(Extension) -> Unit)? = null): Extension { + val (groupId, artifactId, version) = splitCoordinates(gav, 3) + return Extension().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + this@ExtensionList.add(this) + block?.invoke(this, this) } + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/IssueManagement.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/IssueManagement.kt index d9f81d9d..971309df 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/IssueManagement.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/IssueManagement.kt @@ -3,19 +3,19 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class IssueManagement : org.apache.maven.model.IssueManagement(), Cloneable { - @PomDsl - fun system(system: String): IssueManagement { - this.system = system - return this - } + @PomDsl + fun system(system: String): IssueManagement { + this.system = system + return this + } - @PomDsl - fun url(url: String): IssueManagement { - this.url = url - return this - } + @PomDsl + fun url(url: String): IssueManagement { + this.url = url + return this + } - override fun clone(): org.apache.maven.model.IssueManagement { - return super.clone() - } + override fun clone(): org.apache.maven.model.IssueManagement { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/License.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/License.kt index 0aa29f0e..af49ba48 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/License.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/License.kt @@ -3,31 +3,31 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class License : org.apache.maven.model.License(), Cloneable { - @PomDsl - fun name(name: String): License { - this.name = name - return this - } + @PomDsl + fun name(name: String): License { + this.name = name + return this + } - @PomDsl - fun url(url: String): License { - this.url = url - return this - } + @PomDsl + fun url(url: String): License { + this.url = url + return this + } - @PomDsl - fun distribution(distribution: String): License { - this.distribution = distribution - return this - } + @PomDsl + fun distribution(distribution: String): License { + this.distribution = distribution + return this + } - @PomDsl - fun comments(comments: String): License { - this.comments = comments - return this - } + @PomDsl + fun comments(comments: String): License { + this.comments = comments + return this + } - override fun clone(): org.apache.maven.model.License { - return super.clone() - } + override fun clone(): org.apache.maven.model.License { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/LicenseList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/LicenseList.kt index fab627a7..191d0e0d 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/LicenseList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/LicenseList.kt @@ -3,16 +3,14 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class LicenseList : ArrayList(), Cloneable { - @PomDsl - fun license(name: String? = null, block: License.(License) -> Unit) { - val license = License().apply { - this.name = name - } - block.invoke(license, license) - add(license) - } + @PomDsl + fun license(name: String? = null, block: License.(License) -> Unit) { + val license = License().apply { this.name = name } + block.invoke(license, license) + add(license) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingList.kt index f0d54ab6..022baaa8 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingList.kt @@ -3,43 +3,43 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class MailingList : org.apache.maven.model.MailingList(), Cloneable { - @PomDsl - fun name(name: String): MailingList { - this.name = name - return this - } - - @PomDsl - fun subscribe(subscribe: String): MailingList { - this.subscribe = subscribe - return this - } - - @PomDsl - fun unsubscribe(unsubscribe: String): MailingList { - this.unsubscribe = unsubscribe - return this - } - - @PomDsl - fun post(post: String): MailingList { - this.post = post - return this - } - - @PomDsl - fun archive(name: String): MailingList { - this.archive = name - return this - } - - @PomDsl - fun otherArchives(vararg otherArchives: String): MailingList { - this.otherArchives = otherArchives.asList() - return this - } - - override fun clone(): org.apache.maven.model.MailingList { - return super.clone() - } + @PomDsl + fun name(name: String): MailingList { + this.name = name + return this + } + + @PomDsl + fun subscribe(subscribe: String): MailingList { + this.subscribe = subscribe + return this + } + + @PomDsl + fun unsubscribe(unsubscribe: String): MailingList { + this.unsubscribe = unsubscribe + return this + } + + @PomDsl + fun post(post: String): MailingList { + this.post = post + return this + } + + @PomDsl + fun archive(name: String): MailingList { + this.archive = name + return this + } + + @PomDsl + fun otherArchives(vararg otherArchives: String): MailingList { + this.otherArchives = otherArchives.asList() + return this + } + + override fun clone(): org.apache.maven.model.MailingList { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingListList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingListList.kt index 2cd74207..cfbbd710 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingListList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/MailingListList.kt @@ -3,19 +3,15 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class MailingListList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new mailing list. - */ - @PomDsl - fun mailingList(name: String? = null, block: MailingList.(MailingList) -> Unit) { - val mailingList = MailingList().apply { - this.name = name - } - block(mailingList, mailingList) - add(mailingList) - } + /** Provides a callback for defining a new mailing list. */ + @PomDsl + fun mailingList(name: String? = null, block: MailingList.(MailingList) -> Unit) { + val mailingList = MailingList().apply { this.name = name } + block(mailingList, mailingList) + add(mailingList) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ManagedDependencyList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ManagedDependencyList.kt index 8b95f17c..aef00d74 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ManagedDependencyList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ManagedDependencyList.kt @@ -3,32 +3,35 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ManagedDependencyList : DependencyList(), Cloneable { - @PomDsl - fun import(gav: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency(gav, block).apply { - scope = "import" - type = "pom" - } + @PomDsl + fun import(gav: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { + return dependency(gav, block).apply { + scope = "import" + type = "pom" } + } - @PomDsl - fun import(groupId: String, - artifactId: String, - version: String? = null, - classifier: String? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return dependency( + @PomDsl + fun import( + groupId: String, + artifactId: String, + version: String? = null, + classifier: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return dependency( groupId = groupId, artifactId = artifactId, version = version, classifier = classifier, - block = block).apply { - this.scope = "import" - this.type = "pom" + block = block) + .apply { + this.scope = "import" + this.type = "pom" } - } + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Notifier.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Notifier.kt index 9f5fcc3c..c3c5a5c4 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Notifier.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Notifier.kt @@ -3,52 +3,50 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Notifier : org.apache.maven.model.Notifier(), Cloneable { - @PomDsl - fun type(type: String): Notifier { - this.type = type - return this - } - - @PomDsl - fun address(address: String): Notifier { - this.address = address - return this - } - - @PomDsl - fun sendOnError(sendOnError: Boolean = true): Notifier { - this.isSendOnError = sendOnError - return this - } - - @PomDsl - fun sendOnFailure(sendOnFailure: Boolean = true): Notifier { - this.isSendOnFailure = sendOnFailure - return this - } - - @PomDsl - fun sendOnSuccess(sendOnSuccess: Boolean = true): Notifier { - this.isSendOnSuccess = sendOnSuccess - return this - } - - @PomDsl - fun sendOnWarning(sendOnWarning: Boolean = true): Notifier { - this.isSendOnWarning = sendOnWarning - return this - } - - @PomDsl - fun configuration(block: Properties.(Properties) -> Unit) { - val properties = Properties() - block.invoke(properties, properties) - this.configuration = propertiesFactory().apply { - putAll(properties.entries()) - } - } - - override fun clone(): org.apache.maven.model.Notifier { - return super.clone() - } + @PomDsl + fun type(type: String): Notifier { + this.type = type + return this + } + + @PomDsl + fun address(address: String): Notifier { + this.address = address + return this + } + + @PomDsl + fun sendOnError(sendOnError: Boolean = true): Notifier { + this.isSendOnError = sendOnError + return this + } + + @PomDsl + fun sendOnFailure(sendOnFailure: Boolean = true): Notifier { + this.isSendOnFailure = sendOnFailure + return this + } + + @PomDsl + fun sendOnSuccess(sendOnSuccess: Boolean = true): Notifier { + this.isSendOnSuccess = sendOnSuccess + return this + } + + @PomDsl + fun sendOnWarning(sendOnWarning: Boolean = true): Notifier { + this.isSendOnWarning = sendOnWarning + return this + } + + @PomDsl + fun configuration(block: Properties.(Properties) -> Unit) { + val properties = Properties() + block.invoke(properties, properties) + this.configuration = propertiesFactory().apply { putAll(properties.entries()) } + } + + override fun clone(): org.apache.maven.model.Notifier { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/NotifierList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/NotifierList.kt index cfedb898..aa1518b0 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/NotifierList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/NotifierList.kt @@ -3,17 +3,15 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class NotifierList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new notifier entry. - */ - @PomDsl - fun notifier(block: Notifier.(Notifier) -> Unit) { - val notifier = Notifier() - block(notifier, notifier) - add(notifier) - } + /** Provides a callback for defining a new notifier entry. */ + @PomDsl + fun notifier(block: Notifier.(Notifier) -> Unit) { + val notifier = Notifier() + block(notifier, notifier) + add(notifier) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Organization.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Organization.kt index 58b82b1d..9641f395 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Organization.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Organization.kt @@ -3,19 +3,19 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Organization : org.apache.maven.model.Organization(), Cloneable { - @PomDsl - fun name(name: String): Organization { - this.name = name - return this - } + @PomDsl + fun name(name: String): Organization { + this.name = name + return this + } - @PomDsl - fun url(url: String): Organization { - this.url = url - return this - } + @PomDsl + fun url(url: String): Organization { + this.url = url + return this + } - override fun clone(): org.apache.maven.model.Organization { - return super.clone() - } + override fun clone(): org.apache.maven.model.Organization { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Parent.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Parent.kt index b62fa071..482f1d23 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Parent.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Parent.kt @@ -3,35 +3,35 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Parent : org.apache.maven.model.Parent(), Cloneable { - init { - relativePath = "../pom.kts" - } + init { + relativePath = "../pom.kts" + } - @PomDsl - fun groupId(groupId: String): Parent { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): Parent { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): Parent { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): Parent { + this.artifactId = artifactId + return this + } - @PomDsl - fun version(version: String): Parent { - this.version = version - return this - } + @PomDsl + fun version(version: String): Parent { + this.version = version + return this + } - @PomDsl - infix fun relativePath(relativePath: String): Parent { - this.relativePath = relativePath - return this - } + @PomDsl + infix fun relativePath(relativePath: String): Parent { + this.relativePath = relativePath + return this + } - override fun clone(): org.apache.maven.model.Parent { - return super.clone() - } + override fun clone(): org.apache.maven.model.Parent { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Plugin.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Plugin.kt index 76a0ae2b..36473334 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Plugin.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Plugin.kt @@ -6,139 +6,150 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder @PomDsl class Plugin : org.apache.maven.model.Plugin(), Cloneable { - //-- Initialization ----------------------------------------------------------------------------------------------// + // -- Initialization + // ----------------------------------------------------------------------------------------------// - private val _executions: PluginExecutionList - get() { - return executions as PluginExecutionList - } - - private val _dependencies: DependencyList - get() { - return dependencies as DependencyList - } - - init { - this.executions = PluginExecutionList() - this.dependencies = DependencyList() - } - - @PomDsl - fun groupId(groupId: String): Plugin { - this.groupId = groupId - return this - } - - @PomDsl - fun artifactId(artifactId: String): Plugin { - this.artifactId = artifactId - return this + private val _executions: PluginExecutionList + get() { + return executions as PluginExecutionList } - @PomDsl - fun version(version: String): Plugin { - this.version = version - return this - } - - @PomDsl - fun extensions(extensions: Boolean = true): Plugin { - this.extensions = extensions.toString() - return this - } - - @PomDsl - fun inherited(inherited: Boolean = true): Plugin { - this.isInherited = inherited - return this - } - - //-- Block Functions ---------------------------------------------------------------------------------------------// - - @PomDsl - fun executions(block: PluginExecutionList.(PluginExecutionList) -> Unit) { - block.invoke(_executions, _executions) + private val _dependencies: DependencyList + get() { + return dependencies as DependencyList } - @PomDsl - fun dependencies(block: DependencyList.(DependencyList) -> Unit) { - block(_dependencies, _dependencies) - } - - //-- Plugin Dependency Helpers -----------------------------------------------------------------------------------// - - @PomDsl - fun dependency(gavtc: String? = null, block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return _dependencies.dependency(gavtc, block) - } - - @PomDsl - fun dependency(groupId: String, - artifactId: String, - version: String? = null, - type: String = "jar", - classifier: String? = null, - optional: Boolean? = null, - scope: String? = null, - systemPath: String? = null, - block: (Dependency.(Dependency) -> Unit)? = null): Dependency { - return _dependencies.dependency(groupId, artifactId, version, type, classifier, optional, scope, systemPath, block) - } - - //-- Plugin Execution Helpers ------------------------------------------------------------------------------------// - - @PomDsl - fun execution(id: String? = "default", - phase: String? = null, - goals: List? = null, - priority: Int = 0, - inherited: Boolean? = null, - configuration: Xpp3Dom? = null, - block: (PluginExecution.(PluginExecution) -> Unit)? = null): PluginExecution { - return _executions.execution(id, phase, goals, priority, inherited, configuration, block) - } - - //-- Configuration Helpers ---------------------------------------------------------------------------------------// - - /** - * Sets the plugin configuration. - * - * @param source the configuration source as a [String] of XML - */ - @PomDsl - fun configuration(source: String): Xpp3Dom { - this.configuration = source - return this.configuration as Xpp3Dom - } - - @PomDsl - fun configuration(block: XmlNode.(XmlNode) -> Unit) { - val configuration = XmlNode("configuration") - block(configuration, configuration) - this.configuration = configuration.xpp3Dom - } - - /** - * Sets the configuration. - */ - override fun setConfiguration(source: Any?) { - val name = "configuration" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setConfiguration(configuration) - } else { - super.setConfiguration(xpp3Dom) + init { + this.executions = PluginExecutionList() + this.dependencies = DependencyList() + } + + @PomDsl + fun groupId(groupId: String): Plugin { + this.groupId = groupId + return this + } + + @PomDsl + fun artifactId(artifactId: String): Plugin { + this.artifactId = artifactId + return this + } + + @PomDsl + fun version(version: String): Plugin { + this.version = version + return this + } + + @PomDsl + fun extensions(extensions: Boolean = true): Plugin { + this.extensions = extensions.toString() + return this + } + + @PomDsl + fun inherited(inherited: Boolean = true): Plugin { + this.isInherited = inherited + return this + } + + // -- Block Functions + // ---------------------------------------------------------------------------------------------// + + @PomDsl + fun executions(block: PluginExecutionList.(PluginExecutionList) -> Unit) { + block.invoke(_executions, _executions) + } + + @PomDsl + fun dependencies(block: DependencyList.(DependencyList) -> Unit) { + block(_dependencies, _dependencies) + } + + // -- Plugin Dependency Helpers + // -----------------------------------------------------------------------------------// + + @PomDsl + fun dependency( + gavtc: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return _dependencies.dependency(gavtc, block) + } + + @PomDsl + fun dependency( + groupId: String, + artifactId: String, + version: String? = null, + type: String = "jar", + classifier: String? = null, + optional: Boolean? = null, + scope: String? = null, + systemPath: String? = null, + block: (Dependency.(Dependency) -> Unit)? = null + ): Dependency { + return _dependencies.dependency( + groupId, artifactId, version, type, classifier, optional, scope, systemPath, block) + } + + // -- Plugin Execution Helpers + // ------------------------------------------------------------------------------------// + + @PomDsl + fun execution( + id: String? = "default", + phase: String? = null, + goals: List? = null, + priority: Int = 0, + inherited: Boolean? = null, + configuration: Xpp3Dom? = null, + block: (PluginExecution.(PluginExecution) -> Unit)? = null + ): PluginExecution { + return _executions.execution(id, phase, goals, priority, inherited, configuration, block) + } + + // -- Configuration Helpers + // ---------------------------------------------------------------------------------------// + + /** + * Sets the plugin configuration. + * + * @param source the configuration source as a [String] of XML + */ + @PomDsl + fun configuration(source: String): Xpp3Dom { + this.configuration = source + return this.configuration as Xpp3Dom + } + + @PomDsl + fun configuration(block: XmlNode.(XmlNode) -> Unit) { + val configuration = XmlNode("configuration") + block(configuration, configuration) + this.configuration = configuration.xpp3Dom + } + + /** Sets the configuration. */ + override fun setConfiguration(source: Any?) { + val name = "configuration" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setConfiguration(configuration) + } else { + super.setConfiguration(xpp3Dom) } + } - override fun clone(): org.apache.maven.model.Plugin { - return super.clone() - } + override fun clone(): org.apache.maven.model.Plugin { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecution.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecution.kt index 4ef1cbb3..f640ed20 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecution.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecution.kt @@ -6,71 +6,70 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder @PomDsl class PluginExecution : org.apache.maven.model.PluginExecution(), Cloneable { - @PomDsl - fun id(id: String): PluginExecution { - this.id = id - return this - } + @PomDsl + fun id(id: String): PluginExecution { + this.id = id + return this + } - @PomDsl - fun phase(phase: String): PluginExecution { - this.phase = phase - return this - } + @PomDsl + fun phase(phase: String): PluginExecution { + this.phase = phase + return this + } - @PomDsl - fun goals(vararg goals: String): PluginExecution { - this.goals = goals.asList() - return this - } + @PomDsl + fun goals(vararg goals: String): PluginExecution { + this.goals = goals.asList() + return this + } - @PomDsl - fun inherited(inherited: Boolean = true): PluginExecution { - this.isInherited = inherited - return this - } + @PomDsl + fun inherited(inherited: Boolean = true): PluginExecution { + this.isInherited = inherited + return this + } - //-- Configuration Helpers ---------------------------------------------------------------------------------------// + // -- Configuration Helpers + // ---------------------------------------------------------------------------------------// - /** - * Sets the plugin configuration. - * - * @param source the configuration source as a [String] of XML - */ - @PomDsl - fun configuration(source: String): Xpp3Dom { - this.configuration = source - return this.configuration as Xpp3Dom - } + /** + * Sets the plugin configuration. + * + * @param source the configuration source as a [String] of XML + */ + @PomDsl + fun configuration(source: String): Xpp3Dom { + this.configuration = source + return this.configuration as Xpp3Dom + } - @PomDsl - fun configuration(block: XmlNode.(XmlNode) -> Unit) { - val configuration = XmlNode("configuration") - block(configuration, configuration) - this.configuration = configuration.xpp3Dom - } + @PomDsl + fun configuration(block: XmlNode.(XmlNode) -> Unit) { + val configuration = XmlNode("configuration") + block(configuration, configuration) + this.configuration = configuration.xpp3Dom + } - /** - * Sets the configuration. - */ - override fun setConfiguration(source: Any?) { - val name = "configuration" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setConfiguration(configuration) - } else { - super.setConfiguration(xpp3Dom) + /** Sets the configuration. */ + override fun setConfiguration(source: Any?) { + val name = "configuration" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setConfiguration(configuration) + } else { + super.setConfiguration(xpp3Dom) } + } - override fun clone(): org.apache.maven.model.PluginExecution { - return super.clone() - } + override fun clone(): org.apache.maven.model.PluginExecution { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecutionList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecutionList.kt index db7447d1..49e63676 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecutionList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginExecutionList.kt @@ -5,30 +5,30 @@ import org.codehaus.plexus.util.xml.Xpp3Dom @PomDsl class PluginExecutionList : ArrayList(), Cloneable { - /** - * Defines a new plugin execution. - */ - @PomDsl - fun execution(id: String? = "default", - phase: String? = null, - goals: List? = null, - priority: Int = 0, - inherited: Boolean? = null, - configuration: Xpp3Dom? = null, - block: (PluginExecution.(PluginExecution) -> Unit)? = null): PluginExecution { - return PluginExecution().apply { - this.id = id - this.phase = phase - this.priority = priority - if (inherited != null) this.isInherited = inherited - this.goals = goals - this.configuration = configuration - this@PluginExecutionList.add(this) - block?.invoke(this, this) - } + /** Defines a new plugin execution. */ + @PomDsl + fun execution( + id: String? = "default", + phase: String? = null, + goals: List? = null, + priority: Int = 0, + inherited: Boolean? = null, + configuration: Xpp3Dom? = null, + block: (PluginExecution.(PluginExecution) -> Unit)? = null + ): PluginExecution { + return PluginExecution().apply { + this.id = id + this.phase = phase + this.priority = priority + if (inherited != null) this.isInherited = inherited + this.goals = goals + this.configuration = configuration + this@PluginExecutionList.add(this) + block?.invoke(this, this) } + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginList.kt index 3d9674e8..66f80982 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginList.kt @@ -3,22 +3,20 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class PluginList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new build plugin. - */ - @PomDsl - fun plugin(gav: String? = null, block: (Plugin.(Plugin) -> Unit)? = null): Plugin { - val (groupId, artifactId, version) = splitCoordinates(gav, 3) - return Plugin().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - this@PluginList.add(this) - block?.invoke(this, this) - } + /** Provides a callback for defining a new build plugin. */ + @PomDsl + fun plugin(gav: String? = null, block: (Plugin.(Plugin) -> Unit)? = null): Plugin { + val (groupId, artifactId, version) = splitCoordinates(gav, 3) + return Plugin().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + this@PluginList.add(this) + block?.invoke(this, this) } + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginManagement.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginManagement.kt index 82d00ae1..c431211a 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginManagement.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginManagement.kt @@ -3,14 +3,14 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class PluginManagement : org.apache.maven.model.PluginManagement(), Cloneable { - @PomDsl - fun plugins(block: PluginList.(PluginList) -> Unit) { - val plugins = PluginList() - block.invoke(plugins, plugins) - this.plugins = plugins - } + @PomDsl + fun plugins(block: PluginList.(PluginList) -> Unit) { + val plugins = PluginList() + block.invoke(plugins, plugins) + this.plugins = plugins + } - override fun clone(): org.apache.maven.model.PluginManagement { - return super.clone() - } + override fun clone(): org.apache.maven.model.PluginManagement { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginRepositoryList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginRepositoryList.kt index 4a5634ab..eaf2618a 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginRepositoryList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PluginRepositoryList.kt @@ -3,17 +3,18 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class PluginRepositoryList : ArrayList(), Cloneable { - @PomDsl - fun pluginRepository(nameOrId: String? = null, block: Repository.(Repository) -> Unit) { - val repository = Repository().apply { - this.id = nameOrId - this.name = nameOrId + @PomDsl + fun pluginRepository(nameOrId: String? = null, block: Repository.(Repository) -> Unit) { + val repository = + Repository().apply { + this.id = nameOrId + this.name = nameOrId } - block.invoke(repository, repository) - add(repository) - } + block.invoke(repository, repository) + add(repository) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PomDsl.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PomDsl.kt index 1414c3fb..563c3b1c 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PomDsl.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/PomDsl.kt @@ -1,5 +1,3 @@ package org.sonatype.maven.polyglot.kotlin.dsl -@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) -@DslMarker -annotation class PomDsl +@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) @DslMarker annotation class PomDsl diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Prerequisites.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Prerequisites.kt index 29e05eff..b23f36ba 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Prerequisites.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Prerequisites.kt @@ -3,12 +3,12 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Prerequisites : org.apache.maven.model.Prerequisites(), Cloneable { - @PomDsl - fun maven(mavenVersion: String) { - this.maven = mavenVersion - } + @PomDsl + fun maven(mavenVersion: String) { + this.maven = mavenVersion + } - override fun clone(): org.apache.maven.model.Prerequisites { - return super.clone() - } + override fun clone(): org.apache.maven.model.Prerequisites { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Profile.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Profile.kt index 14ddfd04..2cb21edf 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Profile.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Profile.kt @@ -6,123 +6,120 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder @PomDsl class Profile : org.apache.maven.model.Profile(), Cloneable { - @PomDsl - fun id(id: String): Profile { - this.id = id - return this - } - - @PomDsl - fun activation(block: Activation.(Activation) -> Unit) { - val activation = Activation() - block(activation, activation) - this.activation = activation - } - - @PomDsl - fun build(block: Build.(Build) -> Unit) { - val build = Build() - block(build, build) - this.build = build - } - - @PomDsl - fun dependencies(block: DependencyList.(DependencyList) -> Unit) { - val dependencies = DependencyList() - block(dependencies, dependencies) - this.dependencies = dependencies - } - - @PomDsl - fun dependencyManagement(block: DependencyManagement.(DependencyManagement) -> Unit) { - val dependencyManagement = DependencyManagement() - block(dependencyManagement, dependencyManagement) - this.dependencyManagement = dependencyManagement - } - - @PomDsl - fun distributionManagement(block: DistributionManagement.(DistributionManagement) -> Unit) { - val distributionManagement = DistributionManagement() - block.invoke(distributionManagement, distributionManagement) - this.distributionManagement = distributionManagement - } - - @PomDsl - fun modules(vararg modules: String) { - this.modules = modules.asList() - } - - @PomDsl - fun pluginRepositories(block: PluginRepositoryList.(PluginRepositoryList) -> Unit) { - val pluginRepositories = PluginRepositoryList() - block.invoke(pluginRepositories, pluginRepositories) - this.pluginRepositories = pluginRepositories - } - - @PomDsl - fun properties(block: Properties.(Properties) -> Unit) { - val properties = Properties() - block.invoke(properties, properties) - this.properties = propertiesFactory().apply { - putAll(properties.entries()) - } - } - - @PomDsl - fun repositories(block: RepositoryList.(RepositoryList) -> Unit) { - val repositories = RepositoryList() - block.invoke(repositories, repositories) - this.repositories = repositories - } - - @PomDsl - fun reporting(block: Reporting.(Reporting) -> Unit) { - val reporting = Reporting() - block(reporting, reporting) - this.reporting = reporting - } - - //-- Configuration Helpers ---------------------------------------------------------------------------------------// - - /** - * Sets the reports content. - * - * @param source the reports source as a [String] of XML - */ - @PomDsl - fun reports(source: String): Xpp3Dom { - this.reports = source - return this.reports as Xpp3Dom - } - - @PomDsl - fun reports(block: XmlNode.(XmlNode) -> Unit) { - val reports = XmlNode("reports") - block(reports, reports) - this.reports = reports.xpp3Dom - } - - /** - * Sets the reports. - */ - override fun setReports(source: Any?) { - val name = "reports" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setReports(configuration) - } else { - super.setReports(xpp3Dom) + @PomDsl + fun id(id: String): Profile { + this.id = id + return this + } + + @PomDsl + fun activation(block: Activation.(Activation) -> Unit) { + val activation = Activation() + block(activation, activation) + this.activation = activation + } + + @PomDsl + fun build(block: Build.(Build) -> Unit) { + val build = Build() + block(build, build) + this.build = build + } + + @PomDsl + fun dependencies(block: DependencyList.(DependencyList) -> Unit) { + val dependencies = DependencyList() + block(dependencies, dependencies) + this.dependencies = dependencies + } + + @PomDsl + fun dependencyManagement(block: DependencyManagement.(DependencyManagement) -> Unit) { + val dependencyManagement = DependencyManagement() + block(dependencyManagement, dependencyManagement) + this.dependencyManagement = dependencyManagement + } + + @PomDsl + fun distributionManagement(block: DistributionManagement.(DistributionManagement) -> Unit) { + val distributionManagement = DistributionManagement() + block.invoke(distributionManagement, distributionManagement) + this.distributionManagement = distributionManagement + } + + @PomDsl + fun modules(vararg modules: String) { + this.modules = modules.asList() + } + + @PomDsl + fun pluginRepositories(block: PluginRepositoryList.(PluginRepositoryList) -> Unit) { + val pluginRepositories = PluginRepositoryList() + block.invoke(pluginRepositories, pluginRepositories) + this.pluginRepositories = pluginRepositories + } + + @PomDsl + fun properties(block: Properties.(Properties) -> Unit) { + val properties = Properties() + block.invoke(properties, properties) + this.properties = propertiesFactory().apply { putAll(properties.entries()) } + } + + @PomDsl + fun repositories(block: RepositoryList.(RepositoryList) -> Unit) { + val repositories = RepositoryList() + block.invoke(repositories, repositories) + this.repositories = repositories + } + + @PomDsl + fun reporting(block: Reporting.(Reporting) -> Unit) { + val reporting = Reporting() + block(reporting, reporting) + this.reporting = reporting + } + + // -- Configuration Helpers + // ---------------------------------------------------------------------------------------// + + /** + * Sets the reports content. + * + * @param source the reports source as a [String] of XML + */ + @PomDsl + fun reports(source: String): Xpp3Dom { + this.reports = source + return this.reports as Xpp3Dom + } + + @PomDsl + fun reports(block: XmlNode.(XmlNode) -> Unit) { + val reports = XmlNode("reports") + block(reports, reports) + this.reports = reports.xpp3Dom + } + + /** Sets the reports. */ + override fun setReports(source: Any?) { + val name = "reports" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setReports(configuration) + } else { + super.setReports(xpp3Dom) } + } - override fun clone(): org.apache.maven.model.Profile { - return super.clone() - } + override fun clone(): org.apache.maven.model.Profile { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProfileList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProfileList.kt index a27f0c35..3483f32a 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProfileList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProfileList.kt @@ -3,19 +3,15 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ProfileList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new dependency exclusion. - */ - @PomDsl - fun profile(id: String? = null, block: Profile.(Profile) -> Unit) { - val profile = Profile().apply { - this.id = id - } - block.invoke(profile, profile) - add(profile) - } + /** Provides a callback for defining a new dependency exclusion. */ + @PomDsl + fun profile(id: String? = null, block: Profile.(Profile) -> Unit) { + val profile = Profile().apply { this.id = id } + block.invoke(profile, profile) + add(profile) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Project.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Project.kt index a68c975a..56162867 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Project.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Project.kt @@ -1,400 +1,431 @@ package org.sonatype.maven.polyglot.kotlin.dsl +import java.io.File import org.codehaus.plexus.util.xml.Xpp3Dom import org.codehaus.plexus.util.xml.Xpp3DomBuilder import org.sonatype.maven.polyglot.execute.ExecuteTask -import java.io.File @PomDsl class Project(pom: File) : org.apache.maven.model.Model(), Cloneable { - init { - this.pomFile = pom - this.modelVersion = "4.0.0" - this.modelEncoding = "UTF-8" - } - - val tasks: MutableList - get() { - val bld = build - if (bld != null && bld is ProjectBuild) { - return bld.tasks - } - return mutableListOf() - } - - //-- Project Model Version ---------------------------------------------------------------------------------------// - - @PomDsl - fun modelVersion(modelVersion: String) { - this.modelVersion = modelVersion - } - - //-- Project Directory -------------------------------------------------------------------------------------------// - - @PomDsl - override fun getProjectDirectory(): File? { - return super.getProjectDirectory() - } - - //-- Project ID --------------------------------------------------------------------------------------------------// - - /** - * @param gavp a string in the form groupId:artifactId:version[:packaging] - */ - @PomDsl - fun id(gavp: String) { - val (groupId, artifactId, version, packaging) = splitCoordinates(gavp, 4) - this.id(groupId, artifactId, version, packaging) - } - - @PomDsl - fun id(groupId: String? = null, - artifactId: String? = null, - version: String? = null, - packaging: String? = null) { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - if (packaging != null) this.packaging = packaging - } - - fun setId(gavp: String) { - id(gavp) - } - - //-- Parent POM --------------------------------------------------------------------------------------------------// - - @PomDsl - fun parent(block: Parent.(Parent) -> Unit) { - val parent = Parent() - block.invoke(parent, parent) - this.parent = parent - } - - @PomDsl - fun parent(gav: String, - relativePath: String? = null): Parent { - val (groupId, artifactId, version) = splitCoordinates(gav, 3) - return Parent().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - if (relativePath !== null) this.relativePath = relativePath - this@Project.parent = this - } - } - - @PomDsl - fun parent(groupId: String, - artifactId: String, - version: String, - relativePath: String? = null): Parent { - return Parent().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - if (relativePath !== null) this.relativePath = relativePath - this@Project.parent = this - } - } - - //-- Project Artifact ID -----------------------------------------------------------------------------------------// - - @PomDsl - fun artifactId(artifactId: String) { - this.artifactId = artifactId - } - - //-- Project Group ID --------------------------------------------------------------------------------------------// - - @PomDsl - fun groupId(groupId: String) { - this.groupId = groupId - } - - //-- Project Version ---------------------------------------------------------------------------------------------// - - @PomDsl - fun version(version: String) { - this.version = version - } - - //-- Project Packaging -------------------------------------------------------------------------------------------// - - @PomDsl - fun packaging(packaging: String) { - this.packaging = packaging - } - - //-- Project Name ------------------------------------------------------------------------------------------------// - - @PomDsl - fun name(name: String) { - this.name = name - } - - //-- Project Description -----------------------------------------------------------------------------------------// - - @PomDsl - fun description(description: String) { - this.description = description - } - - //-- Project URL -------------------------------------------------------------------------------------------------// - - @PomDsl - fun url(url: String) { - this.url = url - } - - //-- Project Inception Year --------------------------------------------------------------------------------------// - - @PomDsl - fun inceptionYear(inceptionYear: String) { - this.inceptionYear = inceptionYear - } - - @PomDsl - fun inceptionYear(inceptionYear: Int) { - this.inceptionYear = inceptionYear.toString() - } - - //-- Organization ------------------------------------------------------------------------------------------------// - - @PomDsl - fun organization(block: Organization.(Organization) -> Unit) { - val organization = Organization() - block.invoke(organization, organization) - this.organization = organization - } - - @PomDsl - fun organization(name: String?, url: String?): Organization { - return Organization().apply { - this.name = name - this.url = url - this@Project.organization = this - } - } - - //-- Licenses ----------------------------------------------------------------------------------------------------// - - @PomDsl - fun licenses(block: LicenseList.(LicenseList) -> Unit) { - val licenses = LicenseList() - block.invoke(licenses, licenses) - this.licenses = licenses - } - - @PomDsl - fun license(name: String, - url: String, - distribution: String = "repo", - comments: String? = null): License { - return License().apply { - this.name = name - this.url = url - this.distribution = distribution - this.comments = comments - this@Project.addLicense(this) + init { + this.pomFile = pom + this.modelVersion = "4.0.0" + this.modelEncoding = "UTF-8" + } + + val tasks: MutableList + get() { + val bld = build + if (bld != null && bld is ProjectBuild) { + return bld.tasks + } + return mutableListOf() + } + + // -- Project Model Version + // ---------------------------------------------------------------------------------------// + + @PomDsl + fun modelVersion(modelVersion: String) { + this.modelVersion = modelVersion + } + + // -- Project Directory + // -------------------------------------------------------------------------------------------// + + @PomDsl + override fun getProjectDirectory(): File? { + return super.getProjectDirectory() + } + + // -- Project ID + // --------------------------------------------------------------------------------------------------// + + /** @param gavp a string in the form groupId:artifactId:version[:packaging] */ + @PomDsl + fun id(gavp: String) { + val (groupId, artifactId, version, packaging) = splitCoordinates(gavp, 4) + this.id(groupId, artifactId, version, packaging) + } + + @PomDsl + fun id( + groupId: String? = null, + artifactId: String? = null, + version: String? = null, + packaging: String? = null + ) { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + if (packaging != null) this.packaging = packaging + } + + fun setId(gavp: String) { + id(gavp) + } + + // -- Parent POM + // --------------------------------------------------------------------------------------------------// + + @PomDsl + fun parent(block: Parent.(Parent) -> Unit) { + val parent = Parent() + block.invoke(parent, parent) + this.parent = parent + } + + @PomDsl + fun parent(gav: String, relativePath: String? = null): Parent { + val (groupId, artifactId, version) = splitCoordinates(gav, 3) + return Parent().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + if (relativePath !== null) this.relativePath = relativePath + this@Project.parent = this + } + } + + @PomDsl + fun parent( + groupId: String, + artifactId: String, + version: String, + relativePath: String? = null + ): Parent { + return Parent().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + if (relativePath !== null) this.relativePath = relativePath + this@Project.parent = this + } + } + + // -- Project Artifact ID + // -----------------------------------------------------------------------------------------// + + @PomDsl + fun artifactId(artifactId: String) { + this.artifactId = artifactId + } + + // -- Project Group ID + // --------------------------------------------------------------------------------------------// + + @PomDsl + fun groupId(groupId: String) { + this.groupId = groupId + } + + // -- Project Version + // ---------------------------------------------------------------------------------------------// + + @PomDsl + fun version(version: String) { + this.version = version + } + + // -- Project Packaging + // -------------------------------------------------------------------------------------------// + + @PomDsl + fun packaging(packaging: String) { + this.packaging = packaging + } + + // -- Project Name + // ------------------------------------------------------------------------------------------------// + + @PomDsl + fun name(name: String) { + this.name = name + } + + // -- Project Description + // -----------------------------------------------------------------------------------------// + + @PomDsl + fun description(description: String) { + this.description = description + } + + // -- Project URL + // -------------------------------------------------------------------------------------------------// + + @PomDsl + fun url(url: String) { + this.url = url + } + + // -- Project Inception Year + // --------------------------------------------------------------------------------------// + + @PomDsl + fun inceptionYear(inceptionYear: String) { + this.inceptionYear = inceptionYear + } + + @PomDsl + fun inceptionYear(inceptionYear: Int) { + this.inceptionYear = inceptionYear.toString() + } + + // -- Organization + // ------------------------------------------------------------------------------------------------// + + @PomDsl + fun organization(block: Organization.(Organization) -> Unit) { + val organization = Organization() + block.invoke(organization, organization) + this.organization = organization + } + + @PomDsl + fun organization(name: String?, url: String?): Organization { + return Organization().apply { + this.name = name + this.url = url + this@Project.organization = this + } + } + + // -- Licenses + // ----------------------------------------------------------------------------------------------------// + + @PomDsl + fun licenses(block: LicenseList.(LicenseList) -> Unit) { + val licenses = LicenseList() + block.invoke(licenses, licenses) + this.licenses = licenses + } + + @PomDsl + fun license( + name: String, + url: String, + distribution: String = "repo", + comments: String? = null + ): License { + return License().apply { + this.name = name + this.url = url + this.distribution = distribution + this.comments = comments + this@Project.addLicense(this) + } + } + + // -- Developers + // --------------------------------------------------------------------------------------------------// + + @PomDsl + fun developers(block: DeveloperList.(DeveloperList) -> Unit) { + val developers = DeveloperList() + block.invoke(developers, developers) + this.developers = developers + } + + // -- Contributors + // ------------------------------------------------------------------------------------------------// + + @PomDsl + fun contributors(block: ContributorList.(ContributorList) -> Unit) { + val contributors = ContributorList() + block.invoke(contributors, contributors) + this.contributors = contributors + } + + // -- Mailing Lists + // -----------------------------------------------------------------------------------------------// + + @PomDsl + fun mailingLists(block: MailingListList.(MailingListList) -> Unit) { + val mailingLists = MailingListList() + block.invoke(mailingLists, mailingLists) + this.mailingLists = mailingLists + } + + // -- Prerequisites + // -----------------------------------------------------------------------------------------------// + + @PomDsl + fun prerequisites(block: Prerequisites.(Prerequisites) -> Unit) { + val prerequisites = Prerequisites() + block.invoke(prerequisites, prerequisites) + this.prerequisites = prerequisites + } + + // -- Modules + // -----------------------------------------------------------------------------------------------------// + + @PomDsl + fun modules(vararg modules: String) { + this.modules = modules.asList() + } + + // -- SCM + // ---------------------------------------------------------------------------------------------------------// + + @PomDsl + fun scm(block: Scm.(Scm) -> Unit) { + val scm = Scm() + block.invoke(scm, scm) + this.scm = scm + } + + // -- Issue Management + // --------------------------------------------------------------------------------------------// + + @PomDsl + fun issueManagement(block: IssueManagement.(IssueManagement) -> Unit) { + val issueManagement = IssueManagement() + block.invoke(issueManagement, issueManagement) + this.issueManagement = issueManagement + } + + // -- CI Management + // -----------------------------------------------------------------------------------------------// + + @PomDsl + fun ciManagement(block: CiManagement.(CiManagement) -> Unit) { + val ciManagement = CiManagement() + block.invoke(ciManagement, ciManagement) + this.ciManagement = ciManagement + } + + // -- Distribution Management + // -------------------------------------------------------------------------------------// + + @PomDsl + fun distributionManagement(block: DistributionManagement.(DistributionManagement) -> Unit) { + val distributionManagement = DistributionManagement() + block.invoke(distributionManagement, distributionManagement) + this.distributionManagement = distributionManagement + } + + // -- Properties + // --------------------------------------------------------------------------------------------------// + + @PomDsl + fun properties(block: Properties.(Properties) -> Unit) { + val properties = Properties() + block.invoke(properties, properties) + this.properties = propertiesFactory().apply { putAll(properties.entries()) } + } + + // -- Dependency Management + // ---------------------------------------------------------------------------------------// + + @PomDsl + fun dependencyManagement(block: DependencyManagement.(DependencyManagement) -> Unit) { + val dependencyManagement = DependencyManagement() + block(dependencyManagement, dependencyManagement) + this.dependencyManagement = dependencyManagement + } + + // -- Dependencies + // ------------------------------------------------------------------------------------------------// + + @PomDsl + fun dependencies(block: DependencyList.(DependencyList) -> Unit) { + val dependencies = DependencyList() + block(dependencies, dependencies) + this.dependencies = dependencies + } + + // -- Repositories + // ------------------------------------------------------------------------------------------------// + + @PomDsl + fun repositories(block: RepositoryList.(RepositoryList) -> Unit) { + val repositories = RepositoryList() + block.invoke(repositories, repositories) + this.repositories = repositories + } + + // -- Plugin Repositories + // -----------------------------------------------------------------------------------------// + + @PomDsl + fun pluginRepositories(block: PluginRepositoryList.(PluginRepositoryList) -> Unit) { + val pluginRepositories = PluginRepositoryList() + block.invoke(pluginRepositories, pluginRepositories) + this.pluginRepositories = pluginRepositories + } + + // -- Build + // -------------------------------------------------------------------------------------------------------// + + @PomDsl + fun build(block: ProjectBuild.(ProjectBuild) -> Unit) { + val build = ProjectBuild() + block(build, build) + setBuild(build) + } + + // -- Reports + // -----------------------------------------------------------------------------------------------------// + + /** + * Sets the reports content. + * + * @param source the reports source as a [String] of XML + */ + @PomDsl + fun reports(source: String): Xpp3Dom { + this.reports = source + return this.reports as Xpp3Dom + } + + @PomDsl + fun reports(block: XmlNode.(XmlNode) -> Unit) { + val reports = XmlNode("reports") + block(reports, reports) + this.reports = reports.xpp3Dom + } + + /** Sets the reports. */ + override fun setReports(source: Any?) { + val name = "reports" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } - } - - //-- Developers --------------------------------------------------------------------------------------------------// - - @PomDsl - fun developers(block: DeveloperList.(DeveloperList) -> Unit) { - val developers = DeveloperList() - block.invoke(developers, developers) - this.developers = developers - } - - //-- Contributors ------------------------------------------------------------------------------------------------// - - @PomDsl - fun contributors(block: ContributorList.(ContributorList) -> Unit) { - val contributors = ContributorList() - block.invoke(contributors, contributors) - this.contributors = contributors - } - - //-- Mailing Lists -----------------------------------------------------------------------------------------------// - - @PomDsl - fun mailingLists(block: MailingListList.(MailingListList) -> Unit) { - val mailingLists = MailingListList() - block.invoke(mailingLists, mailingLists) - this.mailingLists = mailingLists - } - - //-- Prerequisites -----------------------------------------------------------------------------------------------// - - @PomDsl - fun prerequisites(block: Prerequisites.(Prerequisites) -> Unit) { - val prerequisites = Prerequisites() - block.invoke(prerequisites, prerequisites) - this.prerequisites = prerequisites - } - - //-- Modules -----------------------------------------------------------------------------------------------------// - - @PomDsl - fun modules(vararg modules: String) { - this.modules = modules.asList() - } - - //-- SCM ---------------------------------------------------------------------------------------------------------// - - @PomDsl - fun scm(block: Scm.(Scm) -> Unit) { - val scm = Scm() - block.invoke(scm, scm) - this.scm = scm - } - - //-- Issue Management --------------------------------------------------------------------------------------------// - - @PomDsl - fun issueManagement(block: IssueManagement.(IssueManagement) -> Unit) { - val issueManagement = IssueManagement() - block.invoke(issueManagement, issueManagement) - this.issueManagement = issueManagement - } - - //-- CI Management -----------------------------------------------------------------------------------------------// - - @PomDsl - fun ciManagement(block: CiManagement.(CiManagement) -> Unit) { - val ciManagement = CiManagement() - block.invoke(ciManagement, ciManagement) - this.ciManagement = ciManagement - } - - //-- Distribution Management -------------------------------------------------------------------------------------// - - @PomDsl - fun distributionManagement(block: DistributionManagement.(DistributionManagement) -> Unit) { - val distributionManagement = DistributionManagement() - block.invoke(distributionManagement, distributionManagement) - this.distributionManagement = distributionManagement - } - - //-- Properties --------------------------------------------------------------------------------------------------// - - @PomDsl - fun properties(block: Properties.(Properties) -> Unit) { - val properties = Properties() - block.invoke(properties, properties) - this.properties = propertiesFactory().apply { - putAll(properties.entries()) - } - } - - //-- Dependency Management ---------------------------------------------------------------------------------------// - - @PomDsl - fun dependencyManagement(block: DependencyManagement.(DependencyManagement) -> Unit) { - val dependencyManagement = DependencyManagement() - block(dependencyManagement, dependencyManagement) - this.dependencyManagement = dependencyManagement - } - - //-- Dependencies ------------------------------------------------------------------------------------------------// - - @PomDsl - fun dependencies(block: DependencyList.(DependencyList) -> Unit) { - val dependencies = DependencyList() - block(dependencies, dependencies) - this.dependencies = dependencies - } - - //-- Repositories ------------------------------------------------------------------------------------------------// - - @PomDsl - fun repositories(block: RepositoryList.(RepositoryList) -> Unit) { - val repositories = RepositoryList() - block.invoke(repositories, repositories) - this.repositories = repositories - } - - //-- Plugin Repositories -----------------------------------------------------------------------------------------// - - @PomDsl - fun pluginRepositories(block: PluginRepositoryList.(PluginRepositoryList) -> Unit) { - val pluginRepositories = PluginRepositoryList() - block.invoke(pluginRepositories, pluginRepositories) - this.pluginRepositories = pluginRepositories - } - - //-- Build -------------------------------------------------------------------------------------------------------// - - @PomDsl - fun build(block: ProjectBuild.(ProjectBuild) -> Unit) { - val build = ProjectBuild() - block(build, build) - setBuild(build) - } - - //-- Reports -----------------------------------------------------------------------------------------------------// - - /** - * Sets the reports content. - * - * @param source the reports source as a [String] of XML - */ - @PomDsl - fun reports(source: String): Xpp3Dom { - this.reports = source - return this.reports as Xpp3Dom - } - - @PomDsl - fun reports(block: XmlNode.(XmlNode) -> Unit) { - val reports = XmlNode("reports") - block(reports, reports) - this.reports = reports.xpp3Dom - } - - /** - * Sets the reports. - */ - override fun setReports(source: Any?) { - val name = "reports" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setReports(configuration) - } else { - super.setReports(xpp3Dom) - } - } - - //-- Reporting ---------------------------------------------------------------------------------------------------// - - @PomDsl - fun reporting(block: Reporting.(Reporting) -> Unit) { - val reporting = Reporting() - block(reporting, reporting) - this.reporting = reporting - } - - //-- Profiles ----------------------------------------------------------------------------------------------------// - - @PomDsl - fun profiles(block: ProfileList.(ProfileList) -> Unit) { - val profiles = ProfileList() - block(profiles, profiles) - this.profiles = profiles - } - - override fun clone(): org.apache.maven.model.Model { - return super.clone() - } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setReports(configuration) + } else { + super.setReports(xpp3Dom) + } + } + + // -- Reporting + // ---------------------------------------------------------------------------------------------------// + + @PomDsl + fun reporting(block: Reporting.(Reporting) -> Unit) { + val reporting = Reporting() + block(reporting, reporting) + this.reporting = reporting + } + + // -- Profiles + // ----------------------------------------------------------------------------------------------------// + + @PomDsl + fun profiles(block: ProfileList.(ProfileList) -> Unit) { + val profiles = ProfileList() + block(profiles, profiles) + this.profiles = profiles + } + + override fun clone(): org.apache.maven.model.Model { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProjectBuild.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProjectBuild.kt index c18dc658..34ce9e6f 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProjectBuild.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ProjectBuild.kt @@ -1,34 +1,42 @@ package org.sonatype.maven.polyglot.kotlin.dsl +import java.io.File import org.sonatype.maven.polyglot.execute.ExecuteContext import org.sonatype.maven.polyglot.execute.ExecuteTask import org.sonatype.maven.polyglot.kotlin.engine.ScriptHost import org.sonatype.maven.polyglot.kotlin.execute.KotlinExecuteTask -import java.io.File @PomDsl class ProjectBuild : Build() { - val tasks: MutableList = mutableListOf() + val tasks: MutableList = mutableListOf() - @PomDsl - fun execute(id: String, phase: String, profile: String? = null, block: ExecuteContext.() -> Unit) { - tasks.add(KotlinExecuteTask(block).apply { - this.id = id - this.phase = phase - this.profileId = profile + @PomDsl + fun execute( + id: String, + phase: String, + profile: String? = null, + block: ExecuteContext.() -> Unit + ) { + tasks.add( + KotlinExecuteTask(block).apply { + this.id = id + this.phase = phase + this.profileId = profile }) - } + } - @PomDsl - fun execute(id: String, phase: String, profile: String? = null, script: String) { - tasks.add(KotlinExecuteTask { - val file = File("$basedir/$script") - ScriptHost.eval(file, this) - }.apply { - this.id = id - this.phase = phase - this.profileId = profile - }) - } + @PomDsl + fun execute(id: String, phase: String, profile: String? = null, script: String) { + tasks.add( + KotlinExecuteTask { + val file = File("$basedir/$script") + ScriptHost.eval(file, this) + } + .apply { + this.id = id + this.phase = phase + this.profileId = profile + }) + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Properties.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Properties.kt index f93562e3..d7d62227 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Properties.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Properties.kt @@ -5,50 +5,50 @@ import java.util.* @PomDsl open class Properties { - private val properties: MutableMap = LinkedHashMap() - private val groups: MutableList = ArrayList() + private val properties: MutableMap = LinkedHashMap() + private val groups: MutableList = ArrayList() - internal fun entries(): Map { - return this@Properties.properties - } + internal fun entries(): Map { + return this@Properties.properties + } - @Suppress("unused") - internal fun groups(): List { - return this@Properties.groups - } + @Suppress("unused") + internal fun groups(): List { + return this@Properties.groups + } - @PomDsl - fun group(comment: String? = null, block: Properties.Group.(Properties.Group) -> Unit) { - val group = Group(comment) - block(group, group) - groups.add(group) - } + @PomDsl + fun group(comment: String? = null, block: Properties.Group.(Properties.Group) -> Unit) { + val group = Group(comment) + block(group, group) + groups.add(group) + } - infix fun String.to(value: Any) = addEntry(this, value) + infix fun String.to(value: Any) = addEntry(this, value) - private fun addEntry(key: String, value: Any) { - properties[key] = value.toString() - } + private fun addEntry(key: String, value: Any) { + properties[key] = value.toString() + } - @PomDsl - inner class Group(@Suppress("unused") val comment: String? = null) { + @PomDsl + inner class Group(@Suppress("unused") val comment: String? = null) { - private val keys: MutableSet = LinkedHashSet() + private val keys: MutableSet = LinkedHashSet() - @Suppress("unused") - fun entries(): Map { - return this@Properties.properties.filterKeys { keys.contains(it) } - } + @Suppress("unused") + fun entries(): Map { + return this@Properties.properties.filterKeys { keys.contains(it) } + } - infix fun String.to(value: String) = addEntry(this, value) + infix fun String.to(value: String) = addEntry(this, value) - infix fun String.to(value: Number) = addEntry(this, value) + infix fun String.to(value: Number) = addEntry(this, value) - infix fun String.to(value: Boolean) = addEntry(this, value) + infix fun String.to(value: Boolean) = addEntry(this, value) - private fun addEntry(key: String, value: Any) { - keys.add(key) - this@Properties.addEntry(key, value) - } + private fun addEntry(key: String, value: Any) { + keys.add(key) + this@Properties.addEntry(key, value) } + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Relocation.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Relocation.kt index 00684692..742a6bde 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Relocation.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Relocation.kt @@ -3,31 +3,31 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Relocation : org.apache.maven.model.Relocation(), Cloneable { - @PomDsl - fun groupId(groupId: String): Relocation { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): Relocation { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): Relocation { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): Relocation { + this.artifactId = artifactId + return this + } - @PomDsl - fun version(version: String): Relocation { - this.version = version - return this - } + @PomDsl + fun version(version: String): Relocation { + this.version = version + return this + } - @PomDsl - fun message(message: String): Relocation { - this.message = message - return this - } + @PomDsl + fun message(message: String): Relocation { + this.message = message + return this + } - override fun clone(): org.apache.maven.model.Relocation { - return super.clone() - } + override fun clone(): org.apache.maven.model.Relocation { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPlugin.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPlugin.kt index 77e63f8b..4ac74aa5 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPlugin.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPlugin.kt @@ -6,81 +6,78 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder @PomDsl class ReportPlugin : org.apache.maven.model.ReportPlugin(), Cloneable { - @PomDsl - fun groupId(groupId: String): ReportPlugin { - this.groupId = groupId - return this - } + @PomDsl + fun groupId(groupId: String): ReportPlugin { + this.groupId = groupId + return this + } - @PomDsl - fun artifactId(artifactId: String): ReportPlugin { - this.artifactId = artifactId - return this - } + @PomDsl + fun artifactId(artifactId: String): ReportPlugin { + this.artifactId = artifactId + return this + } - @PomDsl - fun version(version: String): ReportPlugin { - this.version = version - return this - } + @PomDsl + fun version(version: String): ReportPlugin { + this.version = version + return this + } - @PomDsl - fun inherited(inherited: Boolean = true): ReportPlugin { - this.isInherited = inherited - return this - } + @PomDsl + fun inherited(inherited: Boolean = true): ReportPlugin { + this.isInherited = inherited + return this + } - /** - * Provides a callback for defining a list of report sets. - */ - @PomDsl - fun reportSets(block: ReportSetList.(ReportSetList) -> Unit) { - val reportSets = ReportSetList() - block(reportSets, reportSets) - this.reportSets = reportSets - } + /** Provides a callback for defining a list of report sets. */ + @PomDsl + fun reportSets(block: ReportSetList.(ReportSetList) -> Unit) { + val reportSets = ReportSetList() + block(reportSets, reportSets) + this.reportSets = reportSets + } - //-- Configuration Helpers ---------------------------------------------------------------------------------------// + // -- Configuration Helpers + // ---------------------------------------------------------------------------------------// - /** - * Sets the plugin configuration. - * - * @param source the configuration source as a [String] of XML - */ - @PomDsl - fun configuration(source: String): Xpp3Dom { - this.configuration = source - return this.configuration as Xpp3Dom - } + /** + * Sets the plugin configuration. + * + * @param source the configuration source as a [String] of XML + */ + @PomDsl + fun configuration(source: String): Xpp3Dom { + this.configuration = source + return this.configuration as Xpp3Dom + } - @PomDsl - fun configuration(block: XmlNode.(XmlNode) -> Unit) { - val configuration = XmlNode("configuration") - block(configuration, configuration) - this.configuration = configuration.xpp3Dom - } + @PomDsl + fun configuration(block: XmlNode.(XmlNode) -> Unit) { + val configuration = XmlNode("configuration") + block(configuration, configuration) + this.configuration = configuration.xpp3Dom + } - /** - * Sets the configuration. - */ - override fun setConfiguration(source: Any?) { - val name = "configuration" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setConfiguration(configuration) - } else { - super.setConfiguration(xpp3Dom) + /** Sets the configuration. */ + override fun setConfiguration(source: Any?) { + val name = "configuration" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setConfiguration(configuration) + } else { + super.setConfiguration(xpp3Dom) } + } - override fun clone(): org.apache.maven.model.ReportPlugin { - return super.clone() - } + override fun clone(): org.apache.maven.model.ReportPlugin { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPluginList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPluginList.kt index 9631c6c9..4ad0d124 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPluginList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportPluginList.kt @@ -3,22 +3,23 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ReportPluginList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new report plugin. - */ - @PomDsl - fun plugin(gav: String? = null, block: (ReportPlugin.(ReportPlugin) -> Unit)? = null): ReportPlugin { - val (groupId, artifactId, version) = splitCoordinates(gav, 3) - return ReportPlugin().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version - this@ReportPluginList.add(this) - block?.invoke(this, this) - } + /** Provides a callback for defining a new report plugin. */ + @PomDsl + fun plugin( + gav: String? = null, + block: (ReportPlugin.(ReportPlugin) -> Unit)? = null + ): ReportPlugin { + val (groupId, artifactId, version) = splitCoordinates(gav, 3) + return ReportPlugin().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version + this@ReportPluginList.add(this) + block?.invoke(this, this) } + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSet.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSet.kt index 944e096b..e68f4917 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSet.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSet.kt @@ -6,65 +6,64 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder @PomDsl class ReportSet : org.apache.maven.model.ReportSet(), Cloneable { - @PomDsl - fun id(id: String): ReportSet { - this.id = id - return this - } + @PomDsl + fun id(id: String): ReportSet { + this.id = id + return this + } - @PomDsl - fun reports(vararg reports: String): ReportSet { - this.reports = reports.asList() - return this - } + @PomDsl + fun reports(vararg reports: String): ReportSet { + this.reports = reports.asList() + return this + } - @PomDsl - fun inherited(inherited: Boolean = true): ReportSet { - this.isInherited = inherited - return this - } + @PomDsl + fun inherited(inherited: Boolean = true): ReportSet { + this.isInherited = inherited + return this + } - //-- Configuration Helpers ---------------------------------------------------------------------------------------// + // -- Configuration Helpers + // ---------------------------------------------------------------------------------------// - /** - * Sets the plugin configuration. - * - * @param source the configuration source as a [String] of XML - */ - @PomDsl - fun configuration(source: String): Xpp3Dom { - this.configuration = source - return this.configuration as Xpp3Dom - } + /** + * Sets the plugin configuration. + * + * @param source the configuration source as a [String] of XML + */ + @PomDsl + fun configuration(source: String): Xpp3Dom { + this.configuration = source + return this.configuration as Xpp3Dom + } - @PomDsl - fun configuration(block: XmlNode.(XmlNode) -> Unit) { - val configuration = XmlNode("configuration") - block(configuration, configuration) - this.configuration = configuration.xpp3Dom - } + @PomDsl + fun configuration(block: XmlNode.(XmlNode) -> Unit) { + val configuration = XmlNode("configuration") + block(configuration, configuration) + this.configuration = configuration.xpp3Dom + } - /** - * Sets the configuration. - */ - override fun setConfiguration(source: Any?) { - val name = "configuration" - val xpp3Dom = - when (source) { - null -> null - is Xpp3Dom -> source - else -> Xpp3DomBuilder.build(source.toString().reader()) - } - if (xpp3Dom != null && xpp3Dom.name != name) { - val configuration = Xpp3Dom(name) - configuration.addChild(xpp3Dom) - super.setConfiguration(configuration) - } else { - super.setConfiguration(xpp3Dom) + /** Sets the configuration. */ + override fun setConfiguration(source: Any?) { + val name = "configuration" + val xpp3Dom = + when (source) { + null -> null + is Xpp3Dom -> source + else -> Xpp3DomBuilder.build(source.toString().reader()) } + if (xpp3Dom != null && xpp3Dom.name != name) { + val configuration = Xpp3Dom(name) + configuration.addChild(xpp3Dom) + super.setConfiguration(configuration) + } else { + super.setConfiguration(xpp3Dom) } + } - override fun clone(): org.apache.maven.model.ReportSet { - return super.clone() - } + override fun clone(): org.apache.maven.model.ReportSet { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSetList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSetList.kt index 188711b1..1716bacc 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSetList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ReportSetList.kt @@ -3,19 +3,15 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ReportSetList : ArrayList(), Cloneable { - /** - * Provides a callback for defining a new report set. - */ - @PomDsl - fun reportSet(id: String? = null, block: ReportSet.(ReportSet) -> Unit) { - val reportSet = ReportSet().apply { - this.id = id - } - block(reportSet, reportSet) - add(reportSet) - } + /** Provides a callback for defining a new report set. */ + @PomDsl + fun reportSet(id: String? = null, block: ReportSet.(ReportSet) -> Unit) { + val reportSet = ReportSet().apply { this.id = id } + block(reportSet, reportSet) + add(reportSet) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Reporting.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Reporting.kt index 0205b85e..bf820b30 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Reporting.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Reporting.kt @@ -3,26 +3,26 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Reporting : org.apache.maven.model.Reporting(), Cloneable { - @PomDsl - fun excludeDefaults(excludeDefaults: Boolean = true): Reporting { - this.isExcludeDefaults = excludeDefaults - return this - } + @PomDsl + fun excludeDefaults(excludeDefaults: Boolean = true): Reporting { + this.isExcludeDefaults = excludeDefaults + return this + } - @PomDsl - fun outputDirectory(outputDirectory: String): Reporting { - this.outputDirectory = outputDirectory - return this - } + @PomDsl + fun outputDirectory(outputDirectory: String): Reporting { + this.outputDirectory = outputDirectory + return this + } - @PomDsl - fun plugins(block: ReportPluginList.(ReportPluginList) -> Unit) { - val plugins = ReportPluginList() - block.invoke(plugins, plugins) - this.plugins = plugins - } + @PomDsl + fun plugins(block: ReportPluginList.(ReportPluginList) -> Unit) { + val plugins = ReportPluginList() + block.invoke(plugins, plugins) + this.plugins = plugins + } - override fun clone(): org.apache.maven.model.Reporting { - return super.clone() - } + override fun clone(): org.apache.maven.model.Reporting { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Repository.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Repository.kt index fef2285a..4aaf2571 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Repository.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Repository.kt @@ -3,45 +3,45 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Repository : org.apache.maven.model.Repository(), Cloneable { - @PomDsl - fun id(id: String): Repository { - this.id = id - return this - } - - @PomDsl - fun name(name: String): Repository { - this.name = name - return this - } - - @PomDsl - fun url(url: String): Repository { - this.url = url - return this - } - - @PomDsl - fun layout(layout: String): Repository { - this.layout = layout - return this - } - - @PomDsl - fun releases(block: RepositoryPolicy.(RepositoryPolicy) -> Unit) { - val releases = RepositoryPolicy() - block.invoke(releases, releases) - this.releases = releases - } - - @PomDsl - fun snapshots(block: RepositoryPolicy.(RepositoryPolicy) -> Unit) { - val snapshots = RepositoryPolicy() - block.invoke(snapshots, snapshots) - this.snapshots = snapshots - } - - override fun clone(): org.apache.maven.model.Repository { - return super.clone() - } + @PomDsl + fun id(id: String): Repository { + this.id = id + return this + } + + @PomDsl + fun name(name: String): Repository { + this.name = name + return this + } + + @PomDsl + fun url(url: String): Repository { + this.url = url + return this + } + + @PomDsl + fun layout(layout: String): Repository { + this.layout = layout + return this + } + + @PomDsl + fun releases(block: RepositoryPolicy.(RepositoryPolicy) -> Unit) { + val releases = RepositoryPolicy() + block.invoke(releases, releases) + this.releases = releases + } + + @PomDsl + fun snapshots(block: RepositoryPolicy.(RepositoryPolicy) -> Unit) { + val snapshots = RepositoryPolicy() + block.invoke(snapshots, snapshots) + this.snapshots = snapshots + } + + override fun clone(): org.apache.maven.model.Repository { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryList.kt index 90300060..9b3c1928 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryList.kt @@ -3,17 +3,18 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class RepositoryList : ArrayList(), Cloneable { - @PomDsl - fun repository(nameOrId: String? = null, block: Repository.(Repository) -> Unit) { - val repository = Repository().apply { - this.id = nameOrId - this.name = nameOrId + @PomDsl + fun repository(nameOrId: String? = null, block: Repository.(Repository) -> Unit) { + val repository = + Repository().apply { + this.id = nameOrId + this.name = nameOrId } - block.invoke(repository, repository) - add(repository) - } + block.invoke(repository, repository) + add(repository) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryPolicy.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryPolicy.kt index f6fca7d4..2a249401 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryPolicy.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/RepositoryPolicy.kt @@ -3,25 +3,25 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class RepositoryPolicy : org.apache.maven.model.RepositoryPolicy(), Cloneable { - @PomDsl - fun enabled(enabled: Boolean = true): RepositoryPolicy { - this.isEnabled = enabled - return this - } + @PomDsl + fun enabled(enabled: Boolean = true): RepositoryPolicy { + this.isEnabled = enabled + return this + } - @PomDsl - fun updatePolicy(updatePolicy: String): RepositoryPolicy { - this.updatePolicy = updatePolicy - return this - } + @PomDsl + fun updatePolicy(updatePolicy: String): RepositoryPolicy { + this.updatePolicy = updatePolicy + return this + } - @PomDsl - fun checksumPolicy(checksumPolicy: String): RepositoryPolicy { - this.checksumPolicy = checksumPolicy - return this - } + @PomDsl + fun checksumPolicy(checksumPolicy: String): RepositoryPolicy { + this.checksumPolicy = checksumPolicy + return this + } - override fun clone(): org.apache.maven.model.RepositoryPolicy { - return super.clone() - } + override fun clone(): org.apache.maven.model.RepositoryPolicy { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Resource.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Resource.kt index a17510f9..dc8ea28c 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Resource.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Resource.kt @@ -3,37 +3,37 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Resource : org.apache.maven.model.Resource(), Cloneable { - @PomDsl - fun targetPath(targetPath: String): Resource { - this.targetPath = targetPath - return this - } + @PomDsl + fun targetPath(targetPath: String): Resource { + this.targetPath = targetPath + return this + } - @PomDsl - fun filtering(filtering: Boolean = true): Resource { - this.isFiltering = filtering - return this - } + @PomDsl + fun filtering(filtering: Boolean = true): Resource { + this.isFiltering = filtering + return this + } - @PomDsl - fun directory(directory: String): Resource { - this.directory = directory - return this - } + @PomDsl + fun directory(directory: String): Resource { + this.directory = directory + return this + } - @PomDsl - fun includes(vararg includes: String): Resource { - this.includes = includes.asList() - return this - } + @PomDsl + fun includes(vararg includes: String): Resource { + this.includes = includes.asList() + return this + } - @PomDsl - fun excludes(vararg excludes: String): Resource { - this.excludes = excludes.asList() - return this - } + @PomDsl + fun excludes(vararg excludes: String): Resource { + this.excludes = excludes.asList() + return this + } - override fun clone(): org.apache.maven.model.Resource { - return super.clone() - } + override fun clone(): org.apache.maven.model.Resource { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ResourceList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ResourceList.kt index 486b6427..7ef8fd7b 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ResourceList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/ResourceList.kt @@ -3,14 +3,14 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class ResourceList : ArrayList(), Cloneable { - @PomDsl - fun resource(block: Resource.(Resource) -> Unit) { - val resource = Resource() - block.invoke(resource, resource) - add(resource) - } + @PomDsl + fun resource(block: Resource.(Resource) -> Unit) { + val resource = Resource() + block.invoke(resource, resource) + add(resource) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Scm.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Scm.kt index dcf97f2e..71d73b0b 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Scm.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Scm.kt @@ -3,27 +3,27 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Scm : org.apache.maven.model.Scm(), Cloneable { - @PomDsl - fun url(url: String) { - this.url = url - } + @PomDsl + fun url(url: String) { + this.url = url + } - @PomDsl - fun connection(connection: String) { - this.connection = connection - } + @PomDsl + fun connection(connection: String) { + this.connection = connection + } - @PomDsl - fun developerConnection(developerConnection: String) { - this.developerConnection = developerConnection - } + @PomDsl + fun developerConnection(developerConnection: String) { + this.developerConnection = developerConnection + } - @PomDsl - fun tag(tag: String) { - this.tag = tag - } + @PomDsl + fun tag(tag: String) { + this.tag = tag + } - override fun clone(): org.apache.maven.model.Scm { - return super.clone() - } + override fun clone(): org.apache.maven.model.Scm { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Site.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Site.kt index f8a96e4a..0f1a85c6 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Site.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/Site.kt @@ -3,25 +3,25 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class Site : org.apache.maven.model.Site(), Cloneable { - @PomDsl - fun id(id: String): Site { - this.id = id - return this - } + @PomDsl + fun id(id: String): Site { + this.id = id + return this + } - @PomDsl - fun name(name: String): Site { - this.name = name - return this - } + @PomDsl + fun name(name: String): Site { + this.name = name + return this + } - @PomDsl - fun url(url: String): Site { - this.url = url - return this - } + @PomDsl + fun url(url: String): Site { + this.url = url + return this + } - override fun clone(): org.apache.maven.model.Site { - return super.clone() - } + override fun clone(): org.apache.maven.model.Site { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/TestResourceList.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/TestResourceList.kt index 35db6b62..8a44d535 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/TestResourceList.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/TestResourceList.kt @@ -3,14 +3,14 @@ package org.sonatype.maven.polyglot.kotlin.dsl @PomDsl class TestResourceList : ArrayList(), Cloneable { - @PomDsl - fun testResource(block: Resource.(Resource) -> Unit) { - val resource = Resource() - block.invoke(resource, resource) - add(resource) - } + @PomDsl + fun testResource(block: Resource.(Resource) -> Unit) { + val resource = Resource() + block.invoke(resource, resource) + add(resource) + } - override fun clone(): Any { - return super.clone() - } + override fun clone(): Any { + return super.clone() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/XmlNode.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/XmlNode.kt index 6c51e40e..7fc15995 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/XmlNode.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/XmlNode.kt @@ -5,43 +5,43 @@ import org.codehaus.plexus.util.xml.Xpp3Dom @PomDsl open class XmlNode(val name: String, val parent: XmlNode? = null) { - var xpp3Dom: Xpp3Dom = Xpp3Dom(name) + var xpp3Dom: Xpp3Dom = Xpp3Dom(name) - init { - if (parent != null) { - parent.xpp3Dom.addChild(xpp3Dom) - } - } - - infix fun String.to(value: Any) { - val node = XmlNode(this, this@XmlNode) - node.xpp3Dom.value = value.toString() - } - - infix fun String.to(value: Int) { - val node = XmlNode(this, this@XmlNode) - node.xpp3Dom.value = value.toString() - } - - infix fun String.to(value: Long) { - val node = XmlNode(this, this@XmlNode) - node.xpp3Dom.value = value.toString() - } - - infix fun String.to(value: Double) { - val node = XmlNode(this, this@XmlNode) - node.xpp3Dom.value = value.toString() - } - - infix fun String.to(value: Boolean) { - val node = XmlNode(this, this@XmlNode) - node.xpp3Dom.value = value.toString() - } - - @PomDsl - operator fun String.invoke(block: XmlNode.(XmlNode) -> Unit): XmlNode { - val node = XmlNode(this, this@XmlNode) - block.invoke(node, node) - return node + init { + if (parent != null) { + parent.xpp3Dom.addChild(xpp3Dom) } + } + + infix fun String.to(value: Any) { + val node = XmlNode(this, this@XmlNode) + node.xpp3Dom.value = value.toString() + } + + infix fun String.to(value: Int) { + val node = XmlNode(this, this@XmlNode) + node.xpp3Dom.value = value.toString() + } + + infix fun String.to(value: Long) { + val node = XmlNode(this, this@XmlNode) + node.xpp3Dom.value = value.toString() + } + + infix fun String.to(value: Double) { + val node = XmlNode(this, this@XmlNode) + node.xpp3Dom.value = value.toString() + } + + infix fun String.to(value: Boolean) { + val node = XmlNode(this, this@XmlNode) + node.xpp3Dom.value = value.toString() + } + + @PomDsl + operator fun String.invoke(block: XmlNode.(XmlNode) -> Unit): XmlNode { + val node = XmlNode(this, this@XmlNode) + block.invoke(node, node) + return node + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/PomKtsScript.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/PomKtsScript.kt index 04636508..cbec6c3d 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/PomKtsScript.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/PomKtsScript.kt @@ -1,45 +1,38 @@ package org.sonatype.maven.polyglot.kotlin.engine -import org.sonatype.maven.polyglot.execute.ExecuteContext -import org.sonatype.maven.polyglot.kotlin.dsl.PomDsl -import org.sonatype.maven.polyglot.kotlin.dsl.Project import java.io.File import kotlin.script.experimental.annotations.KotlinScript import kotlin.script.templates.ScriptTemplateDefinition +import org.sonatype.maven.polyglot.execute.ExecuteContext +import org.sonatype.maven.polyglot.kotlin.dsl.PomDsl +import org.sonatype.maven.polyglot.kotlin.dsl.Project @KotlinScript( - displayName = "Maven kotlin POM script", - fileExtension = "pom.kts", - compilationConfiguration = ScriptDefinition::class -) + displayName = "Maven kotlin POM script", + fileExtension = "pom.kts", + compilationConfiguration = ScriptDefinition::class) @ScriptTemplateDefinition(scriptFilePattern = "pom\\.kts") abstract class PomKtsScript(val script: File, val basedir: File, val model: Project) { - /** - * Configures a Maven project model. - */ - @PomDsl - fun project(nameOrId: String? = null, block: Project.() -> Unit): Project { - if (nameOrId != null) { - model.name = nameOrId - model.id = nameOrId - } - return model.apply(block) + /** Configures a Maven project model. */ + @PomDsl + fun project(nameOrId: String? = null, block: Project.() -> Unit): Project { + if (nameOrId != null) { + model.name = nameOrId + model.id = nameOrId } + return model.apply(block) + } - /** - * Invokes the script at the supplied location - */ - @Suppress("unused") - fun eval(script: File) { - ScriptHost.eval(script, basedir, model) - } + /** Invokes the script at the supplied location */ + @Suppress("unused") + fun eval(script: File) { + ScriptHost.eval(script, basedir, model) + } - /** - * Invokes the script at the supplied location - */ - @Suppress("unused") - fun ExecuteContext.eval(taskScript: File) { - ScriptHost.eval(taskScript, this) - } + /** Invokes the script at the supplied location */ + @Suppress("unused") + fun ExecuteContext.eval(taskScript: File) { + ScriptHost.eval(taskScript, this) + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptDefinition.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptDefinition.kt index 30bb942b..d503a559 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptDefinition.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptDefinition.kt @@ -1,5 +1,11 @@ package org.sonatype.maven.polyglot.kotlin.engine +import kotlin.script.experimental.api.ScriptAcceptedLocation +import kotlin.script.experimental.api.ScriptCompilationConfiguration +import kotlin.script.experimental.api.acceptedLocations +import kotlin.script.experimental.api.ide +import kotlin.script.experimental.jvm.dependenciesFromClassContext +import kotlin.script.experimental.jvm.jvm import org.apache.maven.artifact.Artifact import org.apache.maven.model.Model import org.apache.maven.plugin.logging.Log @@ -7,27 +13,24 @@ import org.apache.maven.project.MavenProject import org.apache.maven.settings.Settings import org.codehaus.plexus.util.xml.Xpp3DomBuilder import org.sonatype.maven.polyglot.execute.ExecuteContext -import kotlin.script.experimental.api.ScriptAcceptedLocation -import kotlin.script.experimental.api.ScriptCompilationConfiguration -import kotlin.script.experimental.api.acceptedLocations -import kotlin.script.experimental.api.ide -import kotlin.script.experimental.jvm.dependenciesFromClassContext -import kotlin.script.experimental.jvm.jvm -object ScriptDefinition : ScriptCompilationConfiguration( - { - jvm { - dependenciesFromClassContext(PomKtsScript::class, "polyglot-kotlin") // needed for DSL - dependenciesFromClassContext(ExecuteContext::class, "polyglot-common") // needed for executing tasks - dependenciesFromClassContext(Model::class, "maven-model") // needed for maven model - dependenciesFromClassContext(MavenProject::class, "maven-core") // needed for maven project/session - dependenciesFromClassContext(Artifact::class, "maven-artifact") // needed for maven artifacts - dependenciesFromClassContext(Settings::class, "maven-settings") // needed for accessing settings - dependenciesFromClassContext(Xpp3DomBuilder::class, "plexus-utils") // needed for Xpp3DomBuilder - dependenciesFromClassContext(Log::class, "maven-plugin-api") // Needed for writing to the Maven build log - } - ide { - acceptedLocations(ScriptAcceptedLocation.Everywhere) - } - } -) +object ScriptDefinition : + ScriptCompilationConfiguration({ + jvm { + dependenciesFromClassContext(PomKtsScript::class, "polyglot-kotlin") // needed for DSL + dependenciesFromClassContext( + ExecuteContext::class, "polyglot-common") // needed for executing tasks + dependenciesFromClassContext(Model::class, "maven-model") // needed for maven model + dependenciesFromClassContext( + MavenProject::class, "maven-core") // needed for maven project/session + dependenciesFromClassContext( + Artifact::class, "maven-artifact") // needed for maven artifacts + dependenciesFromClassContext( + Settings::class, "maven-settings") // needed for accessing settings + dependenciesFromClassContext( + Xpp3DomBuilder::class, "plexus-utils") // needed for Xpp3DomBuilder + dependenciesFromClassContext( + Log::class, "maven-plugin-api") // Needed for writing to the Maven build log + } + ide { acceptedLocations(ScriptAcceptedLocation.Everywhere) } + }) diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptHost.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptHost.kt index 4ac5a7b4..c0d18851 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptHost.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/ScriptHost.kt @@ -1,8 +1,5 @@ package org.sonatype.maven.polyglot.kotlin.engine -import org.apache.maven.MavenExecutionException -import org.sonatype.maven.polyglot.execute.ExecuteContext -import org.sonatype.maven.polyglot.kotlin.dsl.Project import java.io.File import kotlin.script.experimental.api.ResultWithDiagnostics import kotlin.script.experimental.api.ScriptCompilationConfiguration @@ -14,47 +11,50 @@ import kotlin.script.experimental.jvm.baseClassLoader import kotlin.script.experimental.jvm.jvm import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate +import org.apache.maven.MavenExecutionException +import org.sonatype.maven.polyglot.execute.ExecuteContext +import org.sonatype.maven.polyglot.kotlin.dsl.Project object ScriptHost { - private val host = BasicJvmScriptingHost() - private val pomCompilationConfig = createJvmCompilationConfigurationFromTemplate() - private val taskCompilationConfig = createJvmCompilationConfigurationFromTemplate() + private val host = BasicJvmScriptingHost() + private val pomCompilationConfig = createJvmCompilationConfigurationFromTemplate() + private val taskCompilationConfig = createJvmCompilationConfigurationFromTemplate() - fun eval(script: File, basedir: File, model: Project) { - eval(script, pomCompilationConfig) { - constructorArgs(script, basedir, model) - jvm { - baseClassLoader(PomKtsScript::class.java.classLoader) - } - } + fun eval(script: File, basedir: File, model: Project) { + eval(script, pomCompilationConfig) { + constructorArgs(script, basedir, model) + jvm { baseClassLoader(PomKtsScript::class.java.classLoader) } } + } - fun eval(script: File, executeContext: ExecuteContext) { - eval(script, taskCompilationConfig) { - constructorArgs(script, executeContext) - jvm { - baseClassLoader(TaskKtsScript::class.java.classLoader) - } - } + fun eval(script: File, executeContext: ExecuteContext) { + eval(script, taskCompilationConfig) { + constructorArgs(script, executeContext) + jvm { baseClassLoader(TaskKtsScript::class.java.classLoader) } } + } - private fun eval(script: File, - compilationConfig: ScriptCompilationConfiguration, - evaluationConfigBuilder: ScriptEvaluationConfiguration.Builder.() -> Unit) { - val sourceCode = script.readText().toScriptSource() - val evaluationConfig = ScriptEvaluationConfiguration(evaluationConfigBuilder) - val result = host.eval(sourceCode, compilationConfig, evaluationConfig) - result.reports.filter { it.exception != null }.forEach { - System.err.println(it) - it.exception?.printStackTrace() - } - if (result is ResultWithDiagnostics.Failure) { - throw MavenExecutionException( - "Failed to evaluate script\n" + - result.reports - .filterNot { it.severity == ScriptDiagnostic.Severity.DEBUG } - .joinToString("\n"), script - ) + private fun eval( + script: File, + compilationConfig: ScriptCompilationConfiguration, + evaluationConfigBuilder: ScriptEvaluationConfiguration.Builder.() -> Unit + ) { + val sourceCode = script.readText().toScriptSource() + val evaluationConfig = ScriptEvaluationConfiguration(evaluationConfigBuilder) + val result = host.eval(sourceCode, compilationConfig, evaluationConfig) + result.reports + .filter { it.exception != null } + .forEach { + System.err.println(it) + it.exception?.printStackTrace() } + if (result is ResultWithDiagnostics.Failure) { + throw MavenExecutionException( + "Failed to evaluate script\n" + + result.reports + .filterNot { it.severity == ScriptDiagnostic.Severity.DEBUG } + .joinToString("\n"), + script) } + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/TaskKtsScript.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/TaskKtsScript.kt index c28315e5..14149497 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/TaskKtsScript.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/engine/TaskKtsScript.kt @@ -1,14 +1,14 @@ package org.sonatype.maven.polyglot.kotlin.engine -import org.sonatype.maven.polyglot.execute.ExecuteContext import java.io.File import kotlin.script.experimental.annotations.KotlinScript import kotlin.script.templates.ScriptTemplateDefinition +import org.sonatype.maven.polyglot.execute.ExecuteContext @KotlinScript( displayName = "External kotlin task script", fileExtension = "task.kts", - compilationConfiguration = ScriptDefinition::class -) + compilationConfiguration = ScriptDefinition::class) @ScriptTemplateDefinition(scriptFilePattern = ".*\\.task\\.kts") -abstract class TaskKtsScript(val script: File, private val delegate: ExecuteContext) : ExecuteContext by delegate +abstract class TaskKtsScript(val script: File, private val delegate: ExecuteContext) : + ExecuteContext by delegate diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/execute/KotlinExecuteTask.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/execute/KotlinExecuteTask.kt index 1c649b4f..864a77f4 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/execute/KotlinExecuteTask.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/execute/KotlinExecuteTask.kt @@ -5,7 +5,7 @@ import org.sonatype.maven.polyglot.execute.ExecuteTaskSupport class KotlinExecuteTask(private val script: ExecuteContext.() -> Unit) : ExecuteTaskSupport() { - override fun execute(context: ExecuteContext) { - context.script() - } + override fun execute(context: ExecuteContext) { + context.script() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/KotlinScriptWriter.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/KotlinScriptWriter.kt index 532dde06..ab8dd163 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/KotlinScriptWriter.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/KotlinScriptWriter.kt @@ -1,307 +1,318 @@ package org.sonatype.maven.polyglot.kotlin.serialization -import org.sonatype.maven.polyglot.kotlin.dsl.escape -import org.sonatype.maven.polyglot.kotlin.dsl.escapeRaw import java.io.Writer import java.util.* import kotlin.collections.ArrayList +import org.sonatype.maven.polyglot.kotlin.dsl.escape +import org.sonatype.maven.polyglot.kotlin.dsl.escapeRaw internal open class KotlinScriptWriter(writer: Writer) { - private enum class SerializerState { - BLOCK, FUNCTION, FIELD, RAW_STRING - } - - private val state: Deque = LinkedList() - private val indentation = " " - protected var indentLevel = 0 - private var lineStart = true - private val argumentWrapThreshold = 50 - private val out = OUT(writer) - private val expressionText = Regex("""[$][{][^}]+[}]""") - private val booleanLiteral = Regex("true|false") - - class OUT(private val out: Writer) : Writer() { - - private var position: Long = 0 - - override fun write(cbuf: CharArray, off: Int, len: Int) { - out.write(cbuf, off, len) - position += len - } - - override fun flush() { - out.flush() - } - - override fun close() { - out.close() - } - } - - protected fun write(str: String): KotlinScriptWriter { - if (lineStart) { - for (i in 1..indentLevel) { - out.write(indentation) - } - lineStart = false - } - out.write(str) - return this + private enum class SerializerState { + BLOCK, + FUNCTION, + FIELD, + RAW_STRING + } + + private val state: Deque = LinkedList() + private val indentation = " " + protected var indentLevel = 0 + private var lineStart = true + private val argumentWrapThreshold = 50 + private val out = OUT(writer) + private val expressionText = Regex("""[$][{][^}]+[}]""") + private val booleanLiteral = Regex("true|false") + + class OUT(private val out: Writer) : Writer() { + + private var position: Long = 0 + + override fun write(cbuf: CharArray, off: Int, len: Int) { + out.write(cbuf, off, len) + position += len } - private fun writeString(value: String): KotlinScriptWriter { - val escapedValue = escape(value) - when { - expressionText.find(value) != null -> { - write("\"${escapedValue}\"") - } - value != escapedValue -> { - val escapedRawValue = escapeRaw(value) - tripleQuotedString(escapedRawValue) - } - else -> write("\"${value}\"") - } - return this + override fun flush() { + out.flush() } - protected fun writePair(pair: Pair): KotlinScriptWriter { - writeString(pair.first) - write(" to ") - val value = pair.second - when { - value == null -> write("null") - value.toLongOrNull().toString() == value -> write(value) - value.toDoubleOrNull().toString() == value -> write(value) - value.matches(booleanLiteral) -> write(value) - else -> writeString(value) - } - return this + override fun close() { + out.close() } - - protected fun endLine(): KotlinScriptWriter { - out.write("\n") - lineStart = true - return this + } + + protected fun write(str: String): KotlinScriptWriter { + if (lineStart) { + for (i in 1..indentLevel) { + out.write(indentation) + } + lineStart = false } - - protected fun blockComment(comment: String): KotlinScriptWriter { - write("/*").endLine() - comment.prependIndent(" * ").lines().forEach { write(it).endLine() } - write(" */").endLine() - return this + out.write(str) + return this + } + + private fun writeString(value: String): KotlinScriptWriter { + val escapedValue = escape(value) + when { + expressionText.find(value) != null -> { + write("\"${escapedValue}\"") + } + value != escapedValue -> { + val escapedRawValue = escapeRaw(value) + tripleQuotedString(escapedRawValue) + } + else -> write("\"${value}\"") } - - protected fun lineComment(comment: String): KotlinScriptWriter { - comment.prependIndent("// ").lines().forEach { write(it).endLine() } - return this + return this + } + + protected fun writePair(pair: Pair): KotlinScriptWriter { + writeString(pair.first) + write(" to ") + val value = pair.second + when { + value == null -> write("null") + value.toLongOrNull().toString() == value -> write(value) + value.toDoubleOrNull().toString() == value -> write(value) + value.matches(booleanLiteral) -> write(value) + else -> writeString(value) } - - protected fun block(name: String, - modelObject: T?, - args: (T.(MutableList) -> Unit)? = null, - contents: (T.() -> Unit)? = null) { - block(name, modelObject, "it", args, contents) + return this + } + + protected fun endLine(): KotlinScriptWriter { + out.write("\n") + lineStart = true + return this + } + + protected fun blockComment(comment: String): KotlinScriptWriter { + write("/*").endLine() + comment.prependIndent(" * ").lines().forEach { write(it).endLine() } + write(" */").endLine() + return this + } + + protected fun lineComment(comment: String): KotlinScriptWriter { + comment.prependIndent("// ").lines().forEach { write(it).endLine() } + return this + } + + protected fun block( + name: String, + modelObject: T?, + args: (T.(MutableList) -> Unit)? = null, + contents: (T.() -> Unit)? = null + ) { + block(name, modelObject, "it", args, contents) + } + + protected fun block( + name: String, + modelObject: T?, + paramName: String, + args: (T.(MutableList) -> Unit)? = null, + contents: (T.() -> Unit)? = null + ) { + if (modelObject == null) { + return + } else if (modelObject is Collection<*> && modelObject.isEmpty()) { + return + } else if (modelObject is Map<*, *> && modelObject.isEmpty()) { + return + } else if (indentLevel == 1) { + // Add an extra space before project-level blocks + endLine() } - - protected fun block(name: String, - modelObject: T?, - paramName: String, - args: (T.(MutableList) -> Unit)? = null, - contents: (T.() -> Unit)? = null) { - if (modelObject == null) { - return - } else if (modelObject is Collection<*> && modelObject.isEmpty()) { - return - } else if (modelObject is Map<*, *> && modelObject.isEmpty()) { - return - } else if (indentLevel == 1) { - // Add an extra space before project-level blocks - endLine() + if (args != null) { + val params: MutableList = ArrayList() + args(modelObject, params) + if (params.isEmpty()) { + if (contents != null) { + startBlock(name, paramName) } - if (args != null) { - val params: MutableList = ArrayList() - args(modelObject, params) - if (params.isEmpty()) { - if (contents != null) { - startBlock(name, paramName) - } - } else { - function(name) { - if (params.size == 1 || params.joinToString().length < argumentWrapThreshold) { - @Suppress("UNCHECKED_CAST") - when (params[0]) { - is Pair<*, *> -> namedArguments(params as List>) - is String -> arguments(params as List) - else -> throw IllegalArgumentException("The argument type \"${params[0]::class}\" is unsupported. Must be Pair or String") - } - } else { - @Suppress("UNCHECKED_CAST") - when (params[0]) { - is Pair<*, *> -> namedMultiLineArguments(params as List>) - is String -> multiLineArguments(params as List) - else -> throw IllegalArgumentException("The argument type \"${params[0]::class}\" is unsupported. Must be Pair or String") - } - } - } - if (contents != null) { - write(" ") - startBlock(null, paramName) - } + } else { + function(name) { + if (params.size == 1 || params.joinToString().length < argumentWrapThreshold) { + @Suppress("UNCHECKED_CAST") + when (params[0]) { + is Pair<*, *> -> namedArguments(params as List>) + is String -> arguments(params as List) + else -> + throw IllegalArgumentException( + "The argument type \"${params[0]::class}\" is unsupported. Must be Pair or String") + } + } else { + @Suppress("UNCHECKED_CAST") + when (params[0]) { + is Pair<*, *> -> namedMultiLineArguments(params as List>) + is String -> multiLineArguments(params as List) + else -> + throw IllegalArgumentException( + "The argument type \"${params[0]::class}\" is unsupported. Must be Pair or String") } - } else if (contents != null) { - startBlock(name, paramName) + } } if (contents != null) { - contents(modelObject) - endBlock() - } - endLine() - } - - protected fun singleQuotedString(text: String?) { - if (text == null) { - write("null") - } else { - write("\"").write(escape(text)).write("\"") - } - } - - private fun tripleQuotedString(text: String?) { - if (text == null) { - write("null") - } else { - write("\"\"\"") - state.push(SerializerState.RAW_STRING) - incrementIndent() - text.lines().forEach { write(it) } - decrementIndent() - state.pop() - write("\"\"\"") + write(" ") + startBlock(null, paramName) } + } + } else if (contents != null) { + startBlock(name, paramName) } - - private fun incrementIndent(): KotlinScriptWriter { - indentLevel++ - return this - } - - private fun decrementIndent(): KotlinScriptWriter { - indentLevel-- - return this - } - - private fun startBlock(name: String? = null, paramName: String? = "it"): KotlinScriptWriter { - write(if (name == null) "{" else "${name} {") - if (paramName != "it") { - write(" ${paramName} ->") - } - state.push(SerializerState.BLOCK) - indentLevel++ - endLine() - return this - } - - private fun endBlock(): KotlinScriptWriter { - indentLevel-- - write("}") - state.pop() - return this + if (contents != null) { + contents(modelObject) + endBlock() } - - private fun startFunction(name: String): KotlinScriptWriter { - write("${name}(") - state.push(SerializerState.FUNCTION) - return this - } - - private fun endFunction(): KotlinScriptWriter { - write(")") - state.pop() - return this - } - - private fun startField(name: String) { - write("${name} = ") - state.push(SerializerState.FIELD) + endLine() + } + + protected fun singleQuotedString(text: String?) { + if (text == null) { + write("null") + } else { + write("\"").write(escape(text)).write("\"") } - - private fun endField() { - state.pop() - } - - private fun startMultiLineString() { - write("\"\"\"") - state.push(SerializerState.RAW_STRING) - incrementIndent() - endLine() + } + + private fun tripleQuotedString(text: String?) { + if (text == null) { + write("null") + } else { + write("\"\"\"") + state.push(SerializerState.RAW_STRING) + incrementIndent() + text.lines().forEach { write(it) } + decrementIndent() + state.pop() + write("\"\"\"") } - - private fun endMultiLineString() { - write("\"\"\"") - state.pop() - decrementIndent() + } + + private fun incrementIndent(): KotlinScriptWriter { + indentLevel++ + return this + } + + private fun decrementIndent(): KotlinScriptWriter { + indentLevel-- + return this + } + + private fun startBlock(name: String? = null, paramName: String? = "it"): KotlinScriptWriter { + write(if (name == null) "{" else "${name} {") + if (paramName != "it") { + write(" ${paramName} ->") } - - protected fun arguments(values: List) { - values.forEachIndexed { index, value -> - if (index > 0) write(", ") - singleQuotedString(value) - } + state.push(SerializerState.BLOCK) + indentLevel++ + endLine() + return this + } + + private fun endBlock(): KotlinScriptWriter { + indentLevel-- + write("}") + state.pop() + return this + } + + private fun startFunction(name: String): KotlinScriptWriter { + write("${name}(") + state.push(SerializerState.FUNCTION) + return this + } + + private fun endFunction(): KotlinScriptWriter { + write(")") + state.pop() + return this + } + + private fun startField(name: String) { + write("${name} = ") + state.push(SerializerState.FIELD) + } + + private fun endField() { + state.pop() + } + + private fun startMultiLineString() { + write("\"\"\"") + state.push(SerializerState.RAW_STRING) + incrementIndent() + endLine() + } + + private fun endMultiLineString() { + write("\"\"\"") + state.pop() + decrementIndent() + } + + protected fun arguments(values: List) { + values.forEachIndexed { index, value -> + if (index > 0) write(", ") + singleQuotedString(value) } + } - private fun namedArguments(pairs: List>) { - pairs.forEachIndexed { index, pair -> - if (index > 0) write(", ") - write("${pair.first} = ") - singleQuotedString(pair.second) - } + private fun namedArguments(pairs: List>) { + pairs.forEachIndexed { index, pair -> + if (index > 0) write(", ") + write("${pair.first} = ") + singleQuotedString(pair.second) } - - private fun multiLineArguments(values: List) { - incrementIndent() + } + + private fun multiLineArguments(values: List) { + incrementIndent() + endLine() + values.forEachIndexed { index, value -> + if (index > 0) { + write(",") endLine() - values.forEachIndexed { index, value -> - if (index > 0) { - write(",") - endLine() - } - singleQuotedString(value) - } - endLine() - decrementIndent() + } + singleQuotedString(value) } - - private fun namedMultiLineArguments(pairs: List>) { - incrementIndent() + endLine() + decrementIndent() + } + + private fun namedMultiLineArguments(pairs: List>) { + incrementIndent() + endLine() + pairs.forEachIndexed { index, pair -> + if (index > 0) { + write(",") endLine() - pairs.forEachIndexed { index, pair -> - if (index > 0) { - write(",") - endLine() - } - write("${pair.first} = ") - singleQuotedString(pair.second) - } - endLine() - decrementIndent() - } - - protected fun field(fieldName: String, contents: () -> Unit) { - startField(fieldName) - contents() - endField() - } - - protected fun function(functionName: String, contents: () -> Unit) { - startFunction(functionName) - contents() - endFunction() - } - - protected fun multiLineString(contents: () -> Unit) { - startMultiLineString() - contents() - endMultiLineString() + } + write("${pair.first} = ") + singleQuotedString(pair.second) } + endLine() + decrementIndent() + } + + protected fun field(fieldName: String, contents: () -> Unit) { + startField(fieldName) + contents() + endField() + } + + protected fun function(functionName: String, contents: () -> Unit) { + startFunction(functionName) + contents() + endFunction() + } + + protected fun multiLineString(contents: () -> Unit) { + startMultiLineString() + contents() + endMultiLineString() + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/ModelScriptWriter.kt b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/ModelScriptWriter.kt index 63d9d7dc..e5891b8d 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/ModelScriptWriter.kt +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/serialization/ModelScriptWriter.kt @@ -1,5 +1,9 @@ package org.sonatype.maven.polyglot.kotlin.serialization +import java.io.Writer +import java.time.LocalDate +import java.time.LocalTime +import java.util.* import org.apache.maven.execution.MavenSession import org.apache.maven.model.* import org.apache.maven.plugin.logging.Log @@ -10,17 +14,14 @@ import org.sonatype.maven.polyglot.kotlin.dsl.addAll import org.sonatype.maven.polyglot.kotlin.dsl.addAllNonNull import org.sonatype.maven.polyglot.kotlin.dsl.addFirstNonNull import org.sonatype.maven.polyglot.kotlin.dsl.cast -import java.io.Writer -import java.time.LocalDate -import java.time.LocalTime -import java.util.* /** - * A `ModelScriptWriter` converts a Maven project model into a Kotlin script capable of producing an identical model. - * Instances of this class may be configured with one of two flavors of the Kotlin Model DSL. The most basic flavor, - * "block", consists of simply writing callbacks on each model element and using property setters to initialize its - * fields. All complex model elements can be configured using this "block" flavor of the DSL. The "block" flavor, - * however, does little on its own to reduce the code verbosity of the original XML. + * A `ModelScriptWriter` converts a Maven project model into a Kotlin script capable of producing an + * identical model. Instances of this class may be configured with one of two flavors of the Kotlin + * Model DSL. The most basic flavor, "block", consists of simply writing callbacks on each model + * element and using property setters to initialize its fields. All complex model elements can be + * configured using this "block" flavor of the DSL. The "block" flavor, however, does little on its + * own to reduce the code verbosity of the original XML. * * ``` * project { @@ -77,8 +78,8 @@ import java.util.* * } * ``` * - * The "mixed" flavor leverages optional parameters on block functions as well as additional extension functions and in - * order to minimize the verbosity of specific model elements. + * The "mixed" flavor leverages optional parameters on block functions as well as additional + * extension functions and in order to minimize the verbosity of specific model elements. * * ``` * project("Sample Application") { @@ -106,775 +107,789 @@ import java.util.* * } * } * ``` - * Fields that require values of type [Xpp3Dom] can receive their values as strings or by using the XML builder DSL - * shown in the sample plugin configuration above. + * + * Fields that require values of type [Xpp3Dom] can receive their values as strings or by using the + * XML builder DSL shown in the sample plugin configuration above. */ -internal class ModelScriptWriter( - writer: Writer, - private val options: Map -) : KotlinScriptWriter(writer) { - - private val fileComment: String = (options["file.comment"] as String?) - ?: "Generated from pom.kts on ${LocalDate.now()} at ${LocalTime.now()}" - - // By default, Xpp3Dom values are scripted as a function that accepts a raw (triple-quoted) string. - // When using the XML builder DSL, we script the Xpp3Dom as hierarchy of gets on tag names using an operator - private val useXmlBuilder: Boolean = option("xml.dsl.enabled", false) { it == "true" } - - // The default flavor is to use consistent block semantics all the way down the model. - // When the flavor is "mixed", we'll write the script using additional extensions that - // have been designed to minimize verbosity. - private val flavor: String = option("flavor", "block") { +internal class ModelScriptWriter(writer: Writer, private val options: Map) : + KotlinScriptWriter(writer) { + + private val fileComment: String = + (options["file.comment"] as String?) + ?: "Generated from pom.kts on ${LocalDate.now()} at ${LocalTime.now()}" + + // By default, Xpp3Dom values are scripted as a function that accepts a raw (triple-quoted) + // string. + // When using the XML builder DSL, we script the Xpp3Dom as hierarchy of gets on tag names using + // an operator + private val useXmlBuilder: Boolean = option("xml.dsl.enabled", false) { it == "true" } + + // The default flavor is to use consistent block semantics all the way down the model. + // When the flavor is "mixed", we'll write the script using additional extensions that + // have been designed to minimize verbosity. + private val flavor: String = + option("flavor", "block") { when (it) { - "mixed" -> "mixed" - else -> "block" + "mixed" -> "mixed" + else -> "block" } - } - - private val mixedFlavor: Boolean = flavor == "mixed" - - private val blockFlavor: Boolean = flavor == "block" - - // For convenience in referencing methods inside certain lambdas - private val out: ModelScriptWriter = this - - //-- Public API --------------------------------------------------------------------------------------------------// - - fun write(model: Model) { - - blockComment(fileComment) - - val gavp = with(model) { - "${groupId ?: ""}:${artifactId ?: ""}:${version ?: ""}:${packaging ?: "jar"}" - } - block("project", model, { if (mixedFlavor) it.addFirstNonNull(name, gavp) }) { - - set("modelVersion", modelVersion) { modelVersion != "4.0.0" } - set("modelEncoding", modelEncoding) { modelEncoding != "UTF-8" } - - writeParent(parent) - - if (blockFlavor || name != null) { - endLine() - if (mixedFlavor) { - set("id", gavp) - } else { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - set("packaging", packaging) { packaging != "jar" } - } - } - - if (mixedFlavor && name != null) { - if (listOfNotNull(description, url, inceptionYear).isNotEmpty()) { - endLine() - } - } else { - if (listOfNotNull(name, description, url, inceptionYear).isNotEmpty()) { - endLine() - } - } - - set("name", name) { blockFlavor } - set("description", description) - set("url", url) - set("inceptionYear", inceptionYear) - - writeOrganization(organization) - - block("licenses", licenses) { forEach(out::writeLicense) } - block("developers", developers) { forEach(out::writeDeveloper) } - block("contributors", contributors) { forEach(out::writeContributor) } - block("mailingLists", mailingLists) { forEach(out::writeMailingList) } + } - writePrerequisites(prerequisites) + private val mixedFlavor: Boolean = flavor == "mixed" - block("modules", modules, { it.addAll(modules) }) + private val blockFlavor: Boolean = flavor == "block" - writeScm(scm) - writeIssueManagement(issueManagement) - writeCiManagement(ciManagement) - writeDistributionManagement(distributionManagement) - writeProperties(properties) - writeDependencyManagement(dependencyManagement) + // For convenience in referencing methods inside certain lambdas + private val out: ModelScriptWriter = this - block("dependencies", dependencies) { forEach(out::writeDependency) } - block("repositories", repositories) { forEach(out::writeRepository) } - block("pluginRepositories", pluginRepositories) { forEach(::writePluginRepository) } + // -- Public API + // --------------------------------------------------------------------------------------------------// - writeBuild(build) + fun write(model: Model) { - set("reports", reports as Xpp3Dom?) + blockComment(fileComment) - writeReporting(reporting) - - block("profiles", profiles) { forEach(out::writeProfile) } + val gavp = + with(model) { + "${groupId ?: ""}:${artifactId ?: ""}:${version ?: ""}:${packaging ?: "jar"}" } - } + block("project", model, { if (mixedFlavor) it.addFirstNonNull(name, gavp) }) { + set("modelVersion", modelVersion) { modelVersion != "4.0.0" } + set("modelEncoding", modelEncoding) { modelEncoding != "UTF-8" } - //-- Protected API -----------------------------------------------------------------------------------------------// + writeParent(parent) - private fun writeActivation(activation: Activation?) { - block("activation", activation) { - set("isActiveByDefault", "activeByDefault", isActiveByDefault) { isActiveByDefault } - set("jdk", jdk) - writeActivationOS(os) - writeActivationProperty(property) - writeActivationFile(file) - } - } - - private fun writeActivationFile(activationFile: ActivationFile?) { - block("file", activationFile) { - set("missing", missing) - set("exists", exists) - } - } - - private fun writeActivationOS(activationOS: ActivationOS?) { - block("os", activationOS, { if (mixedFlavor) it.add(name) }) { - set("name", name) { blockFlavor } - set("family", family) - set("arch", arch) - set("version", version) - } - } - - private fun writeActivationProperty(activationProperty: ActivationProperty?) { - block("property", activationProperty, { if (mixedFlavor) it.add(name) }) { - set("name", name) { blockFlavor } - set("value", value) - } - } - - private fun writeBuild(build: Build?) { - block("build", build) { - set("finalName", finalName) - set("defaultGoal", defaultGoal) - set("sourceDirectory", sourceDirectory) - set("testSourceDirectory", testSourceDirectory) - set("scriptSourceDirectory", scriptSourceDirectory) - set("directory", directory) - set("outputDirectory", outputDirectory) - set("testOutputDirectory", testOutputDirectory) - set("filters", filters) - block("resources", resources) { forEach(out::writeResource) } - block("testResources", testResources) { forEach(out::writeTestResource) } - block("extensions", extensions) { forEach(out::writeExtension) } - writePluginManagement(pluginManagement) - block("plugins", plugins) { forEach(out::writePlugin) } + if (blockFlavor || name != null) { + endLine() + if (mixedFlavor) { + set("id", gavp) + } else { + set("groupId", groupId) + set("artifactId", artifactId) + set("version", version) + set("packaging", packaging) { packaging != "jar" } } - } + } - private fun writeBuildBase(buildBase: BuildBase?) { - block("build", buildBase) { - set("defaultGoal", defaultGoal) - set("resources", cast>(resources)) - set("testResources", cast>(testResources)) - set("directory", directory) - set("finalName", finalName) - set("filters", filters) - writePluginManagement(pluginManagement) - block("plugins", plugins) { forEach(out::writePlugin) } + if (mixedFlavor && name != null) { + if (listOfNotNull(description, url, inceptionYear).isNotEmpty()) { + endLine() } - } - - private fun writeCiManagement(ciManagement: CiManagement?) { - block("ciManagement", ciManagement) { - set("system", system) - set("url", url) - block("notifiers", notifiers) { forEach(out::writeNotifier) } + } else { + if (listOfNotNull(name, description, url, inceptionYear).isNotEmpty()) { + endLine() } - } + } + + set("name", name) { blockFlavor } + set("description", description) + set("url", url) + set("inceptionYear", inceptionYear) - private fun writeContributor(contributor: Contributor) { - block("contributor", contributor, { if (mixedFlavor) it.add(name) }) { - set("name", name) { blockFlavor } - set("email", email) - set("url", url) - set("organization", organization) - set("organizationUrl", organizationUrl) - set("roles", roles) - set("timezone", timezone) - writeProperties(properties) - } - } + writeOrganization(organization) + + block("licenses", licenses) { forEach(out::writeLicense) } + block("developers", developers) { forEach(out::writeDeveloper) } + block("contributors", contributors) { forEach(out::writeContributor) } + block("mailingLists", mailingLists) { forEach(out::writeMailingList) } + + writePrerequisites(prerequisites) - private fun writeDependency(dependency: Dependency) { - val gav = with(dependency) { - if (version == null) { - "${groupId ?: ""}:${artifactId ?: ""}" - } else { - "${groupId ?: ""}:${artifactId ?: ""}:${version}" - } - } + block("modules", modules, { it.addAll(modules) }) + + writeScm(scm) + writeIssueManagement(issueManagement) + writeCiManagement(ciManagement) + writeDistributionManagement(distributionManagement) + writeProperties(properties) + writeDependencyManagement(dependencyManagement) + + block("dependencies", dependencies) { forEach(out::writeDependency) } + block("repositories", repositories) { forEach(out::writeRepository) } + block("pluginRepositories", pluginRepositories) { forEach(::writePluginRepository) } + + writeBuild(build) + + set("reports", reports as Xpp3Dom?) + + writeReporting(reporting) + + block("profiles", profiles) { forEach(out::writeProfile) } + } + } + + // -- Protected API + // -----------------------------------------------------------------------------------------------// + + private fun writeActivation(activation: Activation?) { + block("activation", activation) { + set("isActiveByDefault", "activeByDefault", isActiveByDefault) { isActiveByDefault } + set("jdk", jdk) + writeActivationOS(os) + writeActivationProperty(property) + writeActivationFile(file) + } + } + + private fun writeActivationFile(activationFile: ActivationFile?) { + block("file", activationFile) { + set("missing", missing) + set("exists", exists) + } + } + + private fun writeActivationOS(activationOS: ActivationOS?) { + block("os", activationOS, { if (mixedFlavor) it.add(name) }) { + set("name", name) { blockFlavor } + set("family", family) + set("arch", arch) + set("version", version) + } + } + + private fun writeActivationProperty(activationProperty: ActivationProperty?) { + block("property", activationProperty, { if (mixedFlavor) it.add(name) }) { + set("name", name) { blockFlavor } + set("value", value) + } + } + + private fun writeBuild(build: Build?) { + block("build", build) { + set("finalName", finalName) + set("defaultGoal", defaultGoal) + set("sourceDirectory", sourceDirectory) + set("testSourceDirectory", testSourceDirectory) + set("scriptSourceDirectory", scriptSourceDirectory) + set("directory", directory) + set("outputDirectory", outputDirectory) + set("testOutputDirectory", testOutputDirectory) + set("filters", filters) + block("resources", resources) { forEach(out::writeResource) } + block("testResources", testResources) { forEach(out::writeTestResource) } + block("extensions", extensions) { forEach(out::writeExtension) } + writePluginManagement(pluginManagement) + block("plugins", plugins) { forEach(out::writePlugin) } + } + } + + private fun writeBuildBase(buildBase: BuildBase?) { + block("build", buildBase) { + set("defaultGoal", defaultGoal) + set("resources", cast>(resources)) + set("testResources", cast>(testResources)) + set("directory", directory) + set("finalName", finalName) + set("filters", filters) + writePluginManagement(pluginManagement) + block("plugins", plugins) { forEach(out::writePlugin) } + } + } + + private fun writeCiManagement(ciManagement: CiManagement?) { + block("ciManagement", ciManagement) { + set("system", system) + set("url", url) + block("notifiers", notifiers) { forEach(out::writeNotifier) } + } + } + + private fun writeContributor(contributor: Contributor) { + block("contributor", contributor, { if (mixedFlavor) it.add(name) }) { + set("name", name) { blockFlavor } + set("email", email) + set("url", url) + set("organization", organization) + set("organizationUrl", organizationUrl) + set("roles", roles) + set("timezone", timezone) + writeProperties(properties) + } + } + + private fun writeDependency(dependency: Dependency) { + val gav = with(dependency) { - val fields = HashSet() - if (type != null && type != "jar") fields.add("type") - if (classifier != null) fields.add("classifier") - if (scope != null) fields.add("scope") - if (systemPath != null) fields.add("systemPath") - if (!exclusions.isNullOrEmpty()) fields.add("exclusions") - if (isOptional) fields.add("isOptional") - - if (mixedFlavor) { - if (fields.isEmpty()) { - block("dependency", dependency, { it.add(gav) }) - } else if (fields.contains("scope")) { - if (scope == "import" && type == "pom") { - if (fields.size == 2) { - block(scope, dependency, { it.add(gav) }) - } else { - block(scope, dependency, { it.add(gav) }) { - set("classifier", classifier) - writeExclusions(exclusions) - set("isOptional", "optional", isOptional) { isOptional } - } - } - } else if (scope == "system" && systemPath != null) { - if (fields.size == 2) { - block(scope, dependency, { it.addAll(gav, systemPath) }) - } else { - block(scope, dependency, { it.addAll(gav, systemPath) }) { - set("type", type) { type != "jar" } - set("classifier", classifier) - writeExclusions(exclusions) - set("isOptional", "optional", isOptional) { isOptional } - } - } - } else { - if (fields.size == 1) { - block(scope, dependency, { it.add(gav) }) - } else { - block(scope, dependency, { it.add(gav) }) { - set("type", type) { type != "jar" } - set("classifier", classifier) - writeExclusions(exclusions) - set("isOptional", "optional", isOptional) { isOptional } - } - } - } - } else if (fields.contains("isOptional")) { - if (fields.size == 1) { - block("optional", dependency, { it.add(gav) }) - } else { - block("optional", dependency, { it.add(gav) }) { - set("type", type) { type != "jar" } - set("classifier", classifier) - writeExclusions(exclusions) - } - } - } else { - block("dependency", dependency, { it.add(gav) }) { - set("type", type) { type != "jar" } - set("classifier", classifier) - writeExclusions(exclusions) - } - } + if (version == null) { + "${groupId ?: ""}:${artifactId ?: ""}" + } else { + "${groupId ?: ""}:${artifactId ?: ""}:${version}" + } + } + with(dependency) { + val fields = HashSet() + if (type != null && type != "jar") fields.add("type") + if (classifier != null) fields.add("classifier") + if (scope != null) fields.add("scope") + if (systemPath != null) fields.add("systemPath") + if (!exclusions.isNullOrEmpty()) fields.add("exclusions") + if (isOptional) fields.add("isOptional") + + if (mixedFlavor) { + if (fields.isEmpty()) { + block("dependency", dependency, { it.add(gav) }) + } else if (fields.contains("scope")) { + if (scope == "import" && type == "pom") { + if (fields.size == 2) { + block(scope, dependency, { it.add(gav) }) } else { - block("dependency", dependency, { if (mixedFlavor) it.add(gav) }) { - if (blockFlavor) { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - } - set("type", type) { type != "jar" } - set("classifier", classifier) - set("scope", scope) - set("systemPath", systemPath) - writeExclusions(exclusions) - set("isOptional", "optional", isOptional) { isOptional } - } + block(scope, dependency, { it.add(gav) }) { + set("classifier", classifier) + writeExclusions(exclusions) + set("isOptional", "optional", isOptional) { isOptional } + } } - } - } - - private fun writeDependencyManagement(dependencyManagement: DependencyManagement?) { - block("dependencyManagement", dependencyManagement) { - block("dependencies", dependencies) { - forEach(out::writeDependency) - } - } - } - - private fun writeDeploymentRepository(deploymentRepository: DeploymentRepository?, blockName: String) { - block(blockName, deploymentRepository, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { - set("id", id) { blockFlavor || (name != null && name != id) } - set("name", name) { blockFlavor } - set("url", url) - set("layout", layout) { layout != "default" } - set("isUniqueVersion", "uniqueVersion", isUniqueVersion) { !isUniqueVersion } - } - } - - private fun writeDeveloper(developer: Developer) { - if (mixedFlavor && developer.email != null) { - val address = if (developer.name != null) { - "${developer.name} <${developer.email}>" + } else if (scope == "system" && systemPath != null) { + if (fields.size == 2) { + block(scope, dependency, { it.addAll(gav, systemPath) }) } else { - developer.email + block(scope, dependency, { it.addAll(gav, systemPath) }) { + set("type", type) { type != "jar" } + set("classifier", classifier) + writeExclusions(exclusions) + set("isOptional", "optional", isOptional) { isOptional } + } } - val id = if (developer.id != developer.email.split('@')[0]) developer.id else null - if (id != null || developer.url != null || developer.organization != null || developer.organizationUrl != null || !developer.roles.isNullOrEmpty() || developer.timezone != null || !developer.properties.isNullOrEmpty()) { - block("developer", developer, { it.add(address) }) { - set("id", id) { id != developer.email.split('@')[0] } - set("url", url) - set("organization", organization) - set("organizationUrl", organizationUrl) - set("roles", roles) - set("timezone", timezone) - writeProperties(properties) - } + } else { + if (fields.size == 1) { + block(scope, dependency, { it.add(gav) }) } else { - block("developer", developer, { it.add(address) }) + block(scope, dependency, { it.add(gav) }) { + set("type", type) { type != "jar" } + set("classifier", classifier) + writeExclusions(exclusions) + set("isOptional", "optional", isOptional) { isOptional } + } } - } else { - block("developer", developer, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { - set("id", id) { blockFlavor || (name != null && name != id) } - set("name", name) { blockFlavor } - set("email", email) - set("url", url) - set("organization", organization) - set("organizationUrl", organizationUrl) - set("roles", roles) - set("timezone", timezone) - writeProperties(properties) + } + } else if (fields.contains("isOptional")) { + if (fields.size == 1) { + block("optional", dependency, { it.add(gav) }) + } else { + block("optional", dependency, { it.add(gav) }) { + set("type", type) { type != "jar" } + set("classifier", classifier) + writeExclusions(exclusions) } - } - } - - private fun writeDistributionManagement(distributionManagement: DistributionManagement?) { - block("distributionManagement", distributionManagement) { - writeDeploymentRepository(repository) - writeDeploymentSnapshotRepository(snapshotRepository) - writeSite(site) - set("downloadUrl", downloadUrl) - writeRelocation(relocation) - set("status", status) - } - } - - private fun writeExclusion(exclusion: Exclusion) { - block("exclusion", exclusion) { + } + } else { + block("dependency", dependency, { it.add(gav) }) { + set("type", type) { type != "jar" } + set("classifier", classifier) + writeExclusions(exclusions) + } + } + } else { + block("dependency", dependency, { if (mixedFlavor) it.add(gav) }) { + if (blockFlavor) { set("groupId", groupId) set("artifactId", artifactId) - } - } - - private fun writeExclusions(exclusions: List?) { - if (mixedFlavor) { - block("exclusions", exclusions, { args -> - args.addAll(map { - "${it.groupId ?: ""}:${it.artifactId ?: ""}" - }) - }) - } else { - block("exclusions", exclusions) { forEach(out::writeExclusion) } - } - } - - private fun writeExtension(extension: Extension) { - if (mixedFlavor) { - val gav = with(extension) { - if (version == null) { - "${groupId ?: ""}:${artifactId ?: ""}" - } else { - "${groupId ?: ""}:${artifactId ?: ""}:${version}" - } - } - block("extension", extension, { it.add(gav) }) - } else { - block("extension", extension) { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - } - } - } - - private fun writeIssueManagement(issueManagement: IssueManagement?) { - block("issueManagement", issueManagement) { - set("system", system) - set("url", url) - } - } - - private fun writeLicense(license: License) { - block("license", license, { if (mixedFlavor) it.add(name) }) { - set("name", name) { blockFlavor } - set("url", url) - set("distribution", distribution) - set("comments", comments) - } - } - - private fun writeMailingList(mailingList: MailingList) { - block("mailingList", mailingList, { if (mixedFlavor) it.add(name) }) { - set("name", name) { blockFlavor } - set("subscribe", subscribe) - set("unsubscribe", unsubscribe) - set("post", post) - set("archive", archive) - set("otherArchives", otherArchives) - } - } - - private fun writeNotifier(notifier: Notifier) { - block("notifier", notifier) { - set("type", type) { type != "mail" } - set("address", address) - set("isSendOnError", "sendOnError", isSendOnError) { !isSendOnError } - set("isSendOnFailure", "sendOnFailure", isSendOnFailure) { !isSendOnFailure } - set("isSendOnSuccess", "sendOnSuccess", isSendOnSuccess) { !isSendOnFailure } - set("isSendOnWarning", "sendOnWarning", isSendOnWarning) { !isSendOnFailure } - writeProperties(configuration, "configuration") - } - } - - private fun writeOrganization(organization: Organization?) { - if (mixedFlavor) { - block("organization", organization, { it.addAllNonNull(name, url) }) - } else { - block("organization", organization) { - set("name", name) - set("url", url) - } - } - } - - private fun writeParent(parent: Parent?) { - if (mixedFlavor) { - block("parent", parent, { it.addAll(groupId, artifactId, version, relativePath) }) - } else { - block("parent", parent) { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - set("relativePath", relativePath) { relativePath != "../pom.kts" } - } - } - } - - private fun writePlugin(plugin: Plugin) { - val gav = with(plugin) { - val groupId = if (groupId == null) "" else groupId + set("version", version) + } + set("type", type) { type != "jar" } + set("classifier", classifier) + set("scope", scope) + set("systemPath", systemPath) + writeExclusions(exclusions) + set("isOptional", "optional", isOptional) { isOptional } + } + } + } + } + + private fun writeDependencyManagement(dependencyManagement: DependencyManagement?) { + block("dependencyManagement", dependencyManagement) { + block("dependencies", dependencies) { forEach(out::writeDependency) } + } + } + + private fun writeDeploymentRepository( + deploymentRepository: DeploymentRepository?, + blockName: String + ) { + block(blockName, deploymentRepository, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { + set("id", id) { blockFlavor || (name != null && name != id) } + set("name", name) { blockFlavor } + set("url", url) + set("layout", layout) { layout != "default" } + set("isUniqueVersion", "uniqueVersion", isUniqueVersion) { !isUniqueVersion } + } + } + + private fun writeDeveloper(developer: Developer) { + if (mixedFlavor && developer.email != null) { + val address = + if (developer.name != null) { + "${developer.name} <${developer.email}>" + } else { + developer.email + } + val id = if (developer.id != developer.email.split('@')[0]) developer.id else null + if (id != null || + developer.url != null || + developer.organization != null || + developer.organizationUrl != null || + !developer.roles.isNullOrEmpty() || + developer.timezone != null || + !developer.properties.isNullOrEmpty()) { + block("developer", developer, { it.add(address) }) { + set("id", id) { id != developer.email.split('@')[0] } + set("url", url) + set("organization", organization) + set("organizationUrl", organizationUrl) + set("roles", roles) + set("timezone", timezone) + writeProperties(properties) + } + } else { + block("developer", developer, { it.add(address) }) + } + } else { + block("developer", developer, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { + set("id", id) { blockFlavor || (name != null && name != id) } + set("name", name) { blockFlavor } + set("email", email) + set("url", url) + set("organization", organization) + set("organizationUrl", organizationUrl) + set("roles", roles) + set("timezone", timezone) + writeProperties(properties) + } + } + } + + private fun writeDistributionManagement(distributionManagement: DistributionManagement?) { + block("distributionManagement", distributionManagement) { + writeDeploymentRepository(repository) + writeDeploymentSnapshotRepository(snapshotRepository) + writeSite(site) + set("downloadUrl", downloadUrl) + writeRelocation(relocation) + set("status", status) + } + } + + private fun writeExclusion(exclusion: Exclusion) { + block("exclusion", exclusion) { + set("groupId", groupId) + set("artifactId", artifactId) + } + } + + private fun writeExclusions(exclusions: List?) { + if (mixedFlavor) { + block( + "exclusions", + exclusions, + { args -> args.addAll(map { "${it.groupId ?: ""}:${it.artifactId ?: ""}" }) }) + } else { + block("exclusions", exclusions) { forEach(out::writeExclusion) } + } + } + + private fun writeExtension(extension: Extension) { + if (mixedFlavor) { + val gav = + with(extension) { if (version == null) { - "${groupId}:${artifactId ?: ""}" + "${groupId ?: ""}:${artifactId ?: ""}" } else { - "${groupId}:${artifactId ?: ""}:${version}" + "${groupId ?: ""}:${artifactId ?: ""}:${version}" } - } + } + block("extension", extension, { it.add(gav) }) + } else { + block("extension", extension) { + set("groupId", groupId) + set("artifactId", artifactId) + set("version", version) + } + } + } + + private fun writeIssueManagement(issueManagement: IssueManagement?) { + block("issueManagement", issueManagement) { + set("system", system) + set("url", url) + } + } + + private fun writeLicense(license: License) { + block("license", license, { if (mixedFlavor) it.add(name) }) { + set("name", name) { blockFlavor } + set("url", url) + set("distribution", distribution) + set("comments", comments) + } + } + + private fun writeMailingList(mailingList: MailingList) { + block("mailingList", mailingList, { if (mixedFlavor) it.add(name) }) { + set("name", name) { blockFlavor } + set("subscribe", subscribe) + set("unsubscribe", unsubscribe) + set("post", post) + set("archive", archive) + set("otherArchives", otherArchives) + } + } + + private fun writeNotifier(notifier: Notifier) { + block("notifier", notifier) { + set("type", type) { type != "mail" } + set("address", address) + set("isSendOnError", "sendOnError", isSendOnError) { !isSendOnError } + set("isSendOnFailure", "sendOnFailure", isSendOnFailure) { !isSendOnFailure } + set("isSendOnSuccess", "sendOnSuccess", isSendOnSuccess) { !isSendOnFailure } + set("isSendOnWarning", "sendOnWarning", isSendOnWarning) { !isSendOnFailure } + writeProperties(configuration, "configuration") + } + } + + private fun writeOrganization(organization: Organization?) { + if (mixedFlavor) { + block("organization", organization, { it.addAllNonNull(name, url) }) + } else { + block("organization", organization) { + set("name", name) + set("url", url) + } + } + } + + private fun writeParent(parent: Parent?) { + if (mixedFlavor) { + block("parent", parent, { it.addAll(groupId, artifactId, version, relativePath) }) + } else { + block("parent", parent) { + set("groupId", groupId) + set("artifactId", artifactId) + set("version", version) + set("relativePath", relativePath) { relativePath != "../pom.kts" } + } + } + } + + private fun writePlugin(plugin: Plugin) { + val gav = with(plugin) { - if (mixedFlavor && extensions.isNullOrEmpty() && executions.isNullOrEmpty() && - dependencies.isNullOrEmpty() && isInherited && configuration == null) { - block("plugin", plugin, { it.add(gav) }) - } else { - block("plugin", plugin, { if (mixedFlavor) it.add(gav) }) { - if (blockFlavor) { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - } - set("extensions", extensions) - block("executions", executions) { forEach(out::writePluginExecution) } - block("dependencies", dependencies) { forEach(out::writeDependency) } - set("isInherited", "inherited", isInherited) { !isInherited } - set("configuration", configuration as Xpp3Dom?) - } - } - } - } - - private fun writePluginExecution(pluginExecution: PluginExecution) { - block("execution", pluginExecution, { if (mixedFlavor && id != "default") it.add(id) }) { - set("id", id) { id != "default" && blockFlavor } - set("phase", phase) - set("goals", goals) - set("isInherited", "inherited", isInherited) { !isInherited } - set("configuration", configuration as Xpp3Dom?) - } - } - - private fun writePluginManagement(pluginManagement: PluginManagement?) { - block("pluginManagement", pluginManagement) { - block("plugins", plugins) { forEach(out::writePlugin) } - } - } - - private fun writePrerequisites(prerequisites: Prerequisites?) { - block("prerequisites", prerequisites) { - set("maven", maven) { maven != "2.0" } - } - } - - private fun writeProfile(profile: Profile) { - block("profile", profile, { if (mixedFlavor) it.add(id) }) { - set("id", id) { id != "default" && blockFlavor } - - writeActivation(activation) - - block("modules", modules, { it.addAll(modules) }) - - writeDistributionManagement(distributionManagement) - writeProperties(properties) - writeDependencyManagement(dependencyManagement) - - block("dependencies", dependencies) { forEach(out::writeDependency) } - block("repositories", repositories) { forEach(out::writeRepository) } - block("pluginRepositories", pluginRepositories) { forEach(out::writePluginRepository) } - - writeBuildBase(build) - - set("reports", reports as Xpp3Dom?) - - writeReporting(reporting) - } - } - - private fun writeProperties(properties: Properties?, blockName: String = "properties") { - @Suppress("UNCHECKED_CAST") - block(blockName, properties as Map) { - entries - .sortedBy { entry -> entry.key } - .forEach { entry -> - writePair(entry.key to entry.value) - endLine() - } - } - } - - private fun writeRelocation(relocation: Relocation?) { - block("relocation", relocation) { + val groupId = if (groupId == null) "" else groupId + if (version == null) { + "${groupId}:${artifactId ?: ""}" + } else { + "${groupId}:${artifactId ?: ""}:${version}" + } + } + with(plugin) { + if (mixedFlavor && + extensions.isNullOrEmpty() && + executions.isNullOrEmpty() && + dependencies.isNullOrEmpty() && + isInherited && + configuration == null) { + block("plugin", plugin, { it.add(gav) }) + } else { + block("plugin", plugin, { if (mixedFlavor) it.add(gav) }) { + if (blockFlavor) { set("groupId", groupId) set("artifactId", artifactId) set("version", version) - set("message", message) + } + set("extensions", extensions) + block("executions", executions) { forEach(out::writePluginExecution) } + block("dependencies", dependencies) { forEach(out::writeDependency) } + set("isInherited", "inherited", isInherited) { !isInherited } + set("configuration", configuration as Xpp3Dom?) } + } } + } - private fun writeReportPlugin(reportPlugin: ReportPlugin) { - val gav = with(reportPlugin) { - val groupId = if (groupId == null) "" else groupId - if (version == null) { - "${groupId}:${artifactId ?: ""}" - } else { - "${groupId}:${artifactId ?: ""}:${version}" - } - } - with(reportPlugin) { - if (mixedFlavor && reportSets.isNullOrEmpty() && isInherited && configuration == null) { - block("plugin", reportPlugin, { it.add(gav) }) - } else { - block("plugin", reportPlugin, { if (mixedFlavor) it.add(gav) }) { - if (blockFlavor) { - set("groupId", groupId) - set("artifactId", artifactId) - set("version", version) - } - block("reportSets", reportSets) { forEach(out::writeReportSet) } - set("isInherited", "inherited", isInherited) { !isInherited } - set("configuration", configuration as Xpp3Dom?) - } - } - } + private fun writePluginExecution(pluginExecution: PluginExecution) { + block("execution", pluginExecution, { if (mixedFlavor && id != "default") it.add(id) }) { + set("id", id) { id != "default" && blockFlavor } + set("phase", phase) + set("goals", goals) + set("isInherited", "inherited", isInherited) { !isInherited } + set("configuration", configuration as Xpp3Dom?) } + } - private fun writeReportSet(reportSet: ReportSet) { - block("reportSet", reportSet, { if (mixedFlavor) it.add(id) }) { - set("id", id) { id != "default" } - set("reports", reports) - set("isInherited", "inherited", isInherited) { !isInherited } - set("configuration", configuration as Xpp3Dom?) - } + private fun writePluginManagement(pluginManagement: PluginManagement?) { + block("pluginManagement", pluginManagement) { + block("plugins", plugins) { forEach(out::writePlugin) } } + } - private fun writeReporting(reporting: Reporting?) { - block("reporting", reporting) { - set("isExcludeDefaults", "excludeDefaults", isExcludeDefaults) { !isExcludeDefaults } - set("outputDirectory", outputDirectory) - block("plugins", plugins) { forEach(out::writeReportPlugin) } - } - } + private fun writePrerequisites(prerequisites: Prerequisites?) { + block("prerequisites", prerequisites) { set("maven", maven) { maven != "2.0" } } + } - private fun writeRepository(repository: Repository, blockName: String) { - block(blockName, repository, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { - set("id", id) { blockFlavor || (name != null && name != id) } - set("name", name) { blockFlavor } - set("url", url) - set("layout", layout) { layout != "default" } - writeReleaseRepositoryPolicy(releases) - writeSnapshotRepositoryPolicy(snapshots) - } - } + private fun writeProfile(profile: Profile) { + block("profile", profile, { if (mixedFlavor) it.add(id) }) { + set("id", id) { id != "default" && blockFlavor } - private fun writeRepositoryPolicy(repositoryPolicy: RepositoryPolicy?, blockName: String) { - block(blockName, repositoryPolicy) { - set("isEnabled", "enabled", isEnabled) { !isEnabled } - set("updatePolicy", updatePolicy) - set("checksumPolicy", checksumPolicy) - } - } + writeActivation(activation) - private fun writeResource(resource: Resource, blockName: String) { - block(blockName, resource) { - set("targetPath", targetPath) - set("isFiltering", "filtering", isFiltering) { !isFiltering } - set("directory", directory) - set("includes", includes) - set("excludes", excludes) - } - } + block("modules", modules, { it.addAll(modules) }) - private fun writeScm(scm: Scm?) { - block("scm", scm) { - set("url", url) - set("connection", connection) - set("developerConnection", developerConnection) - set("tag", tag) { tag != "HEAD" } - } - } + writeDistributionManagement(distributionManagement) + writeProperties(properties) + writeDependencyManagement(dependencyManagement) - private fun writeSite(site: Site?) { - block("site", site, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { - set("id", id) { blockFlavor || (name != null && name != id) } - set("name", name) { blockFlavor } - set("url", url) - } - } + block("dependencies", dependencies) { forEach(out::writeDependency) } + block("repositories", repositories) { forEach(out::writeRepository) } + block("pluginRepositories", pluginRepositories) { forEach(out::writePluginRepository) } - private fun set(fieldName: String, value: String?, test: (() -> Boolean) = { true }) { - if (value != null && test()) { - val content: () -> Unit = { singleQuotedString(value) } - if (mixedFlavor) { - function(fieldName, content) - } else { - field(fieldName, content) - } - endLine() - } + writeBuildBase(build) + + set("reports", reports as Xpp3Dom?) + + writeReporting(reporting) } + } - private fun set(fieldName: String, functionName: String, value: Boolean, test: (() -> Boolean) = { true }) { - if (test()) { - val content: () -> Unit = { write(value.toString()) } - if (mixedFlavor) { - function(functionName, content) - } else { - field(fieldName, content) - } + private fun writeProperties(properties: Properties?, blockName: String = "properties") { + @Suppress("UNCHECKED_CAST") + block(blockName, properties as Map) { + entries + .sortedBy { entry -> entry.key } + .forEach { entry -> + writePair(entry.key to entry.value) endLine() - } + } } + } - private fun set(fieldName: String, values: List?) { - if (!values.isNullOrEmpty()) { - if (mixedFlavor) { - function(fieldName) { - arguments(values) - } - } else { - field(fieldName) { - function("listOf") { - arguments(values) - } - } - } - endLine() - } + private fun writeRelocation(relocation: Relocation?) { + block("relocation", relocation) { + set("groupId", groupId) + set("artifactId", artifactId) + set("version", version) + set("message", message) } + } - private fun set(fieldName: String, xml: Xpp3Dom?) { - when { - xml == null -> return - useXmlBuilder -> { - block(xml.name, xml) { - children.forEach { writeXpp3Dom(it) } - } - } - else -> { - if (indentLevel == 1) { - endLine() - } - field(fieldName) { - multiLineString { - val str = xml.toString() - .replace(Regex("""(?s)\Q\E\s*"""), "") - .replace("$", "\${\"$\"}") - str.lines().forEach { - if (it.isNotEmpty()) { - write(it) - endLine() - } - } - } - } + private fun writeReportPlugin(reportPlugin: ReportPlugin) { + val gav = + with(reportPlugin) { + val groupId = if (groupId == null) "" else groupId + if (version == null) { + "${groupId}:${artifactId ?: ""}" + } else { + "${groupId}:${artifactId ?: ""}:${version}" + } + } + with(reportPlugin) { + if (mixedFlavor && reportSets.isNullOrEmpty() && isInherited && configuration == null) { + block("plugin", reportPlugin, { it.add(gav) }) + } else { + block("plugin", reportPlugin, { if (mixedFlavor) it.add(gav) }) { + if (blockFlavor) { + set("groupId", groupId) + set("artifactId", artifactId) + set("version", version) + } + block("reportSets", reportSets) { forEach(out::writeReportSet) } + set("isInherited", "inherited", isInherited) { !isInherited } + set("configuration", configuration as Xpp3Dom?) + } + } + } + } + + private fun writeReportSet(reportSet: ReportSet) { + block("reportSet", reportSet, { if (mixedFlavor) it.add(id) }) { + set("id", id) { id != "default" } + set("reports", reports) + set("isInherited", "inherited", isInherited) { !isInherited } + set("configuration", configuration as Xpp3Dom?) + } + } + + private fun writeReporting(reporting: Reporting?) { + block("reporting", reporting) { + set("isExcludeDefaults", "excludeDefaults", isExcludeDefaults) { !isExcludeDefaults } + set("outputDirectory", outputDirectory) + block("plugins", plugins) { forEach(out::writeReportPlugin) } + } + } + + private fun writeRepository(repository: Repository, blockName: String) { + block(blockName, repository, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { + set("id", id) { blockFlavor || (name != null && name != id) } + set("name", name) { blockFlavor } + set("url", url) + set("layout", layout) { layout != "default" } + writeReleaseRepositoryPolicy(releases) + writeSnapshotRepositoryPolicy(snapshots) + } + } + + private fun writeRepositoryPolicy(repositoryPolicy: RepositoryPolicy?, blockName: String) { + block(blockName, repositoryPolicy) { + set("isEnabled", "enabled", isEnabled) { !isEnabled } + set("updatePolicy", updatePolicy) + set("checksumPolicy", checksumPolicy) + } + } + + private fun writeResource(resource: Resource, blockName: String) { + block(blockName, resource) { + set("targetPath", targetPath) + set("isFiltering", "filtering", isFiltering) { !isFiltering } + set("directory", directory) + set("includes", includes) + set("excludes", excludes) + } + } + + private fun writeScm(scm: Scm?) { + block("scm", scm) { + set("url", url) + set("connection", connection) + set("developerConnection", developerConnection) + set("tag", tag) { tag != "HEAD" } + } + } + + private fun writeSite(site: Site?) { + block("site", site, { if (mixedFlavor) it.addFirstNonNull(name, id) }) { + set("id", id) { blockFlavor || (name != null && name != id) } + set("name", name) { blockFlavor } + set("url", url) + } + } + + private fun set(fieldName: String, value: String?, test: (() -> Boolean) = { true }) { + if (value != null && test()) { + val content: () -> Unit = { singleQuotedString(value) } + if (mixedFlavor) { + function(fieldName, content) + } else { + field(fieldName, content) + } + endLine() + } + } + + private fun set( + fieldName: String, + functionName: String, + value: Boolean, + test: (() -> Boolean) = { true } + ) { + if (test()) { + val content: () -> Unit = { write(value.toString()) } + if (mixedFlavor) { + function(functionName, content) + } else { + field(fieldName, content) + } + endLine() + } + } + + private fun set(fieldName: String, values: List?) { + if (!values.isNullOrEmpty()) { + if (mixedFlavor) { + function(fieldName) { arguments(values) } + } else { + field(fieldName) { function("listOf") { arguments(values) } } + } + endLine() + } + } + + private fun set(fieldName: String, xml: Xpp3Dom?) { + when { + xml == null -> return + useXmlBuilder -> { + block(xml.name, xml) { children.forEach { writeXpp3Dom(it) } } + } + else -> { + if (indentLevel == 1) { + endLine() + } + field(fieldName) { + multiLineString { + val str = + xml.toString() + .replace(Regex("""(?s)\Q\E\s*"""), "") + .replace("$", "\${\"$\"}") + str.lines().forEach { + if (it.isNotEmpty()) { + write(it) endLine() + } } + } } + endLine() + } } + } - private fun writeXpp3Dom(xml: Xpp3Dom) { - if (xml.value == null) { - block("\"${xml.name}\"", xml) { - children.forEach { writeXpp3Dom(it) } - } - } else { - writePair(Pair(xml.name, xml.value)) - endLine() - } + private fun writeXpp3Dom(xml: Xpp3Dom) { + if (xml.value == null) { + block("\"${xml.name}\"", xml) { children.forEach { writeXpp3Dom(it) } } + } else { + writePair(Pair(xml.name, xml.value)) + endLine() } + } - private val executeContext: ExecuteContext = ExecuteContextStub() - - private class ExecuteContextStub : ExecuteContext { - override fun getProject(): MavenProject { - throw NotImplementedError("not implemented") - } - - override fun getSession(): MavenSession { - throw NotImplementedError("not implemented") - } + private val executeContext: ExecuteContext = ExecuteContextStub() - override fun getLog(): Log { - throw NotImplementedError("not implemented") - } + private class ExecuteContextStub : ExecuteContext { + override fun getProject(): MavenProject { + throw NotImplementedError("not implemented") } - private fun writeDeploymentRepository(deploymentRepository: DeploymentRepository?) { - writeDeploymentRepository(deploymentRepository, "repository") + override fun getSession(): MavenSession { + throw NotImplementedError("not implemented") } - private fun writeDeploymentSnapshotRepository(deploymentRepository: DeploymentRepository?) { - writeDeploymentRepository(deploymentRepository, "snapshotRepository") + override fun getLog(): Log { + throw NotImplementedError("not implemented") } + } - private fun writeRepository(repository: Repository) { - writeRepository(repository, "repository") - } + private fun writeDeploymentRepository(deploymentRepository: DeploymentRepository?) { + writeDeploymentRepository(deploymentRepository, "repository") + } - private fun writePluginRepository(repository: Repository) { - writeRepository(repository, "pluginRepository") - } + private fun writeDeploymentSnapshotRepository(deploymentRepository: DeploymentRepository?) { + writeDeploymentRepository(deploymentRepository, "snapshotRepository") + } - private fun writeReleaseRepositoryPolicy(repositoryPolicy: RepositoryPolicy?) { - writeRepositoryPolicy(repositoryPolicy, "releases") - } + private fun writeRepository(repository: Repository) { + writeRepository(repository, "repository") + } - private fun writeSnapshotRepositoryPolicy(repositoryPolicy: RepositoryPolicy?) { - writeRepositoryPolicy(repositoryPolicy, "snapshots") - } + private fun writePluginRepository(repository: Repository) { + writeRepository(repository, "pluginRepository") + } - private fun writeResource(resource: Resource) { - writeResource(resource, "resource") - } + private fun writeReleaseRepositoryPolicy(repositoryPolicy: RepositoryPolicy?) { + writeRepositoryPolicy(repositoryPolicy, "releases") + } - private fun writeTestResource(resource: Resource) { - writeResource(resource, "testResource") - } + private fun writeSnapshotRepositoryPolicy(repositoryPolicy: RepositoryPolicy?) { + writeRepositoryPolicy(repositoryPolicy, "snapshots") + } - private fun option(key: String, default: T, converter: (String) -> T): T { - val value = options[key] ?: return default - return converter(value.toString()) - } + private fun writeResource(resource: Resource) { + writeResource(resource, "resource") + } + + private fun writeTestResource(resource: Resource) { + writeResource(resource, "testResource") + } + + private fun option(key: String, default: T, converter: (String) -> T): T { + val value = options[key] ?: return default + return converter(value.toString()) + } } diff --git a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/util/Properties.java b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/util/Properties.java index cfe843fa..15083ecb 100644 --- a/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/util/Properties.java +++ b/polyglot-kotlin/src/main/kotlin/org/sonatype/maven/polyglot/kotlin/util/Properties.java @@ -1,27 +1,28 @@ package org.sonatype.maven.polyglot.kotlin.util; -import org.jetbrains.annotations.NotNull; - import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import org.jetbrains.annotations.NotNull; public class Properties extends java.util.Properties { @Override @NotNull public Set keySet() { - return super.keySet().stream().sorted(Comparator.comparing(Object::toString)) + return super.keySet().stream() + .sorted(Comparator.comparing(Object::toString)) .collect(LinkedHashSet::new, Set::add, Set::addAll); } @Override @NotNull public Set> entrySet() { - return super.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey().toString())) + return super.entrySet().stream() + .sorted(Comparator.comparing(e -> e.getKey().toString())) .collect(LinkedHashSet::new, Set::add, Set::addAll); } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMappingTest.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMappingTest.kt index c194b4fd..337f99f3 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMappingTest.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinMappingTest.kt @@ -9,15 +9,16 @@ import org.sonatype.maven.polyglot.mapping.Mapping class KotlinMappingTest : PlexusTestCase() { - override fun customizeContainerConfiguration(configuration: ContainerConfiguration?) { - configuration?.autoWiring = true; - configuration?.classPathScanning = PlexusConstants.SCANNING_CACHE - } + override fun customizeContainerConfiguration(configuration: ContainerConfiguration?) { + configuration?.autoWiring = true + configuration?.classPathScanning = PlexusConstants.SCANNING_CACHE + } - @Test - fun testMapping() { - val mapping = lookup(Mapping::class.java, "kotlin") - val options = mapOf("org.apache.maven.model.building.source" to "/polyglot-maven/polyglot-kotlin/pom.kts") - Assert.assertTrue(mapping.accept(options)) - } + @Test + fun testMapping() { + val mapping = lookup(Mapping::class.java, "kotlin") + val options = + mapOf("org.apache.maven.model.building.source" to "/polyglot-maven/polyglot-kotlin/pom.kts") + Assert.assertTrue(mapping.accept(options)) + } } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReaderTests.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReaderTests.kt index 0104b974..94fbf681 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReaderTests.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelReaderTests.kt @@ -5,20 +5,25 @@ import org.sonatype.maven.polyglot.kotlin.testing.AbstractModelTestCase class KotlinModelReaderTests(testName: String) : AbstractModelTestCase(testName) { - //@formatter:off + // @formatter:off - @Test fun `test#example`() = doTest() + @Test fun `test#example`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-0`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-1`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-2`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-3`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-4`() = doTest() - @Test fun `test#convert#kotlin-to-xml#variation-5`() = doTest() + @Test fun `test#convert#kotlin-to-xml#variation-0`() = doTest() - // @formatter:on + @Test fun `test#convert#kotlin-to-xml#variation-1`() = doTest() - private fun doTest() { - assertEquals(pomXml, pomKts.kts2model().model2xml()) - } + @Test fun `test#convert#kotlin-to-xml#variation-2`() = doTest() + + @Test fun `test#convert#kotlin-to-xml#variation-3`() = doTest() + + @Test fun `test#convert#kotlin-to-xml#variation-4`() = doTest() + + @Test fun `test#convert#kotlin-to-xml#variation-5`() = doTest() + + // @formatter:on + + private fun doTest() { + assertEquals(pomXml, pomKts.kts2model().model2xml()) + } } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriterTests.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriterTests.kt index 42a7c476..17ce46f8 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriterTests.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/KotlinModelWriterTests.kt @@ -5,48 +5,44 @@ import org.junit.Test import org.sonatype.maven.polyglot.kotlin.testing.AbstractModelTestCase // TODO: fix this and re-enable tests -@Ignore( "about to inject MavenProject -> OutOfScopeEx" ) +@Ignore("about to inject MavenProject -> OutOfScopeEx") class KotlinModelWriterTests(testName: String) : AbstractModelTestCase(testName) { - @Test - fun `test#convert#xml-to-kotlin#variation-0`() { - doTest( - "file.comment" to "${this::class.simpleName}\n$testBasePath", - "xml.dsl.enabled" to false, - "flavor" to "block" - ) - } + @Test + fun `test#convert#xml-to-kotlin#variation-0`() { + doTest( + "file.comment" to "${this::class.simpleName}\n$testBasePath", + "xml.dsl.enabled" to false, + "flavor" to "block") + } - @Test - fun `test#convert#xml-to-kotlin#variation-1`() { - doTest( - "file.comment" to "${this::class.simpleName}\n$testBasePath", - "xml.dsl.enabled" to true, - "flavor" to "mixed" - ) - } + @Test + fun `test#convert#xml-to-kotlin#variation-1`() { + doTest( + "file.comment" to "${this::class.simpleName}\n$testBasePath", + "xml.dsl.enabled" to true, + "flavor" to "mixed") + } - @Test - fun `test#convert#xml-to-kotlin#variation-2`() { - doTest( - "file.comment" to "${this::class.simpleName}\n$testBasePath", - "xml.dsl.enabled" to false, - "flavor" to "block" - ) - } + @Test + fun `test#convert#xml-to-kotlin#variation-2`() { + doTest( + "file.comment" to "${this::class.simpleName}\n$testBasePath", + "xml.dsl.enabled" to false, + "flavor" to "block") + } - @Test - fun `test#convert#xml-to-kotlin#variation-3`() { - doTest( - "file.comment" to "${this::class.simpleName}\n$testBasePath", - "xml.dsl.enabled" to true, - "flavor" to "mixed" - ) - } + @Test + fun `test#convert#xml-to-kotlin#variation-3`() { + doTest( + "file.comment" to "${this::class.simpleName}\n$testBasePath", + "xml.dsl.enabled" to true, + "flavor" to "mixed") + } - private fun doTest(vararg options: Pair) { - val kts = pomXml.xml2model(*options).model2kts(*options) - assertEquals(pomKts, kts) - assertEquals(pomXml, kts.kts2model().model2xml()) - } + private fun doTest(vararg options: Pair) { + val kts = pomXml.xml2model(*options).model2kts(*options) + assertEquals(pomKts, kts) + assertEquals(pomXml, kts.kts2model().model2xml()) + } } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/UnitTests.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/UnitTests.kt index 5fc8e336..d346e7cd 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/UnitTests.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/UnitTests.kt @@ -1,162 +1,243 @@ package org.sonatype.maven.polyglot.kotlin -import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.sonatype.maven.polyglot.kotlin.testing.AbstractModelTestCase class UnitTests(testName: String) : AbstractModelTestCase(testName) { - //@formatter:off - - @Test fun `test#unit-tests#artifactId#variation-1`() = doTest() - @Test fun `test#unit-tests#artifactId#variation-2`() = doTest() - @Test fun `test#unit-tests#artifactId#variation-3`() = doTest() - @Test fun `test#unit-tests#artifactId#variation-4`() = doTest() - @Test fun `test#unit-tests#artifactId#variation-5`() = doTest() - @Test fun `test#unit-tests#artifactId#variation-6`() = doTest() - - @Test fun `test#unit-tests#build#variation-1`() = doTest() - @Test fun `test#unit-tests#build#variation-2`() = doTest() - @Test fun `test#unit-tests#build#variation-3`() = doTest() - @Test fun `test#unit-tests#build#variation-4`() = doTest() - @Test fun `test#unit-tests#build#variation-5`() = doTest() - @Test fun `test#unit-tests#build#variation-6`() = doTest() - - @Test fun `test#unit-tests#ciManagement#variation-1`() = doTest() - @Test fun `test#unit-tests#ciManagement#variation-2`() = doTest() - - @Test fun `test#unit-tests#contributors#variation-1`() = doTest() - @Test fun `test#unit-tests#contributors#variation-2`() = doTest() - - @Test fun `test#unit-tests#dependencies#variation-1`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-2`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-3`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-4`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-5`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-6`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-7`() = doTest() - @Test fun `test#unit-tests#dependencies#variation-8`() = doTest() - - @Test fun `test#unit-tests#dependencyManagement#variation-1`() = doTest() - @Test fun `test#unit-tests#dependencyManagement#variation-2`() = doTest() - @Test fun `test#unit-tests#dependencyManagement#variation-3`() = doTest() - - @Test fun `test#unit-tests#description#variation-1`() = doTest() - @Test fun `test#unit-tests#description#variation-2`() = doTest() - @Test fun `test#unit-tests#description#variation-3`() = doTest() - - @Test fun `test#unit-tests#developers#variation-1`() = doTest() - @Test fun `test#unit-tests#developers#variation-2`() = doTest() - - @Test fun `test#unit-tests#distributionManagement#variation-1`() = doTest() - @Test fun `test#unit-tests#distributionManagement#variation-2`() = doTest() - @Test fun `test#unit-tests#distributionManagement#variation-3`() = doTest() - @Test fun `test#unit-tests#distributionManagement#variation-4`() = doTest() - - @Test fun `test#unit-tests#execute#variation-1`() = doTest() - @Test fun `test#unit-tests#execute#variation-2`() = doTest() - - @Test fun `test#unit-tests#groupId#variation-1`() = doTest() - @Test fun `test#unit-tests#groupId#variation-2`() = doTest() - @Test fun `test#unit-tests#groupId#variation-3`() = doTest() - @Test fun `test#unit-tests#groupId#variation-4`() = doTest() - @Test fun `test#unit-tests#groupId#variation-5`() = doTest() - @Test fun `test#unit-tests#groupId#variation-6`() = doTest() - - @Test fun `test#unit-tests#id#variation-1`() = doTest() - @Test fun `test#unit-tests#id#variation-2`() = doTest() - @Test fun `test#unit-tests#id#variation-3`() = doTest() - @Test fun `test#unit-tests#id#variation-4`() = doTest() - - @Test fun `test#unit-tests#inceptionYear#variation-1`() = doTest() - @Test fun `test#unit-tests#inceptionYear#variation-2`() = doTest() - @Test fun `test#unit-tests#inceptionYear#variation-3`() = doTest() - - @Test fun `test#unit-tests#issueManagement#variation-1`() = doTest() - @Test fun `test#unit-tests#issueManagement#variation-2`() = doTest() - - @Test fun `test#unit-tests#licenses#variation-1`() = doTest() - @Test fun `test#unit-tests#licenses#variation-2`() = doTest() - @Test fun `test#unit-tests#licenses#variation-3`() = doTest() - - @Test fun `test#unit-tests#mailingLists#variation-1`() = doTest() - @Test fun `test#unit-tests#mailingLists#variation-2`() = doTest() - @Test fun `test#unit-tests#mailingLists#variation-3`() = doTest() - - @Test fun `test#unit-tests#modelVersion#variation-1`() = doTest() - @Test fun `test#unit-tests#modelVersion#variation-2`() = doTest() - - @Test fun `test#unit-tests#modules#variation-1`() = doTest() - @Test fun `test#unit-tests#modules#variation-2`() = doTest() - - @Test fun `test#unit-tests#name#variation-1`() = doTest() - @Test fun `test#unit-tests#name#variation-2`() = doTest() - @Test fun `test#unit-tests#name#variation-3`() = doTest() - - @Test fun `test#unit-tests#organization#variation-1`() = doTest() - @Test fun `test#unit-tests#organization#variation-2`() = doTest() - @Test fun `test#unit-tests#organization#variation-3`() = doTest() - - @Test fun `test#unit-tests#packaging#variation-1`() = doTest() - @Test fun `test#unit-tests#packaging#variation-2`() = doTest() - @Test fun `test#unit-tests#packaging#variation-3`() = doTest() - @Test fun `test#unit-tests#packaging#variation-4`() = doTest() - @Test fun `test#unit-tests#packaging#variation-5`() = doTest() - @Test fun `test#unit-tests#packaging#variation-6`() = doTest() - - @Test fun `test#unit-tests#parent#variation-1`() = doTest() - @Test fun `test#unit-tests#parent#variation-2`() = doTest() - @Test fun `test#unit-tests#parent#variation-3`() = doTest() - @Test fun `test#unit-tests#parent#variation-4`() = doTest() - @Test fun `test#unit-tests#parent#variation-5`() = doTest() - @Test fun `test#unit-tests#parent#variation-6`() = doTest() - - @Test fun `test#unit-tests#pluginRepositories#variation-1`() = doTest() - @Test fun `test#unit-tests#pluginRepositories#variation-2`() = doTest() - @Test fun `test#unit-tests#pluginRepositories#variation-3`() = doTest() - @Test fun `test#unit-tests#pluginRepositories#variation-4`() = doTest() - - @Test fun `test#unit-tests#prerequisites#variation-1`() = doTest() - @Test fun `test#unit-tests#prerequisites#variation-2`() = doTest() - - @Test fun `test#unit-tests#profiles#variation-1`() = doTest() - @Test fun `test#unit-tests#profiles#variation-2`() = doTest() - - @Test fun `test#unit-tests#properties#variation-1`() = doTest() - @Test fun `test#unit-tests#properties#variation-2`() = doTest() - - @Test fun `test#unit-tests#reporting#variation-1`() = doTest() - @Test fun `test#unit-tests#reporting#variation-2`() = doTest() - @Test fun `test#unit-tests#reporting#variation-3`() = doTest() - @Test fun `test#unit-tests#reporting#variation-4`() = doTest() - - @Test fun `test#unit-tests#reports#variation-1`() = doTest() - @Test fun `test#unit-tests#reports#variation-2`() = doTest() - @Test fun `test#unit-tests#reports#variation-3`() = doTest() - @Test fun `test#unit-tests#reports#variation-4`() = doTest() - @Test fun `test#unit-tests#reports#variation-5`() = doTest() - - @Test fun `test#unit-tests#repositories#variation-1`() = doTest() - @Test fun `test#unit-tests#repositories#variation-2`() = doTest() - @Test fun `test#unit-tests#repositories#variation-3`() = doTest() - @Test fun `test#unit-tests#repositories#variation-4`() = doTest() - - @Test fun `test#unit-tests#scm#variation-1`() = doTest() - @Test fun `test#unit-tests#scm#variation-2`() = doTest() - - @Test fun `test#unit-tests#url#variation-1`() = doTest() - @Test fun `test#unit-tests#url#variation-2`() = doTest() - - @Test fun `test#unit-tests#version#variation-1`() = doTest() - @Test fun `test#unit-tests#version#variation-2`() = doTest() - @Test fun `test#unit-tests#version#variation-3`() = doTest() - @Test fun `test#unit-tests#version#variation-4`() = doTest() - @Test fun `test#unit-tests#version#variation-5`() = doTest() - @Test fun `test#unit-tests#version#variation-6`() = doTest() - - // @formatter:on - - private fun doTest() { - assertEquals(pomXml, pomKts.kts2model().model2xml()) - } + // @formatter:off + + @Test fun `test#unit-tests#artifactId#variation-1`() = doTest() + + @Test fun `test#unit-tests#artifactId#variation-2`() = doTest() + + @Test fun `test#unit-tests#artifactId#variation-3`() = doTest() + + @Test fun `test#unit-tests#artifactId#variation-4`() = doTest() + + @Test fun `test#unit-tests#artifactId#variation-5`() = doTest() + + @Test fun `test#unit-tests#artifactId#variation-6`() = doTest() + + @Test fun `test#unit-tests#build#variation-1`() = doTest() + + @Test fun `test#unit-tests#build#variation-2`() = doTest() + + @Test fun `test#unit-tests#build#variation-3`() = doTest() + + @Test fun `test#unit-tests#build#variation-4`() = doTest() + + @Test fun `test#unit-tests#build#variation-5`() = doTest() + + @Test fun `test#unit-tests#build#variation-6`() = doTest() + + @Test fun `test#unit-tests#ciManagement#variation-1`() = doTest() + + @Test fun `test#unit-tests#ciManagement#variation-2`() = doTest() + + @Test fun `test#unit-tests#contributors#variation-1`() = doTest() + + @Test fun `test#unit-tests#contributors#variation-2`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-1`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-2`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-3`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-4`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-5`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-6`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-7`() = doTest() + + @Test fun `test#unit-tests#dependencies#variation-8`() = doTest() + + @Test fun `test#unit-tests#dependencyManagement#variation-1`() = doTest() + + @Test fun `test#unit-tests#dependencyManagement#variation-2`() = doTest() + + @Test fun `test#unit-tests#dependencyManagement#variation-3`() = doTest() + + @Test fun `test#unit-tests#description#variation-1`() = doTest() + + @Test fun `test#unit-tests#description#variation-2`() = doTest() + + @Test fun `test#unit-tests#description#variation-3`() = doTest() + + @Test fun `test#unit-tests#developers#variation-1`() = doTest() + + @Test fun `test#unit-tests#developers#variation-2`() = doTest() + + @Test fun `test#unit-tests#distributionManagement#variation-1`() = doTest() + + @Test fun `test#unit-tests#distributionManagement#variation-2`() = doTest() + + @Test fun `test#unit-tests#distributionManagement#variation-3`() = doTest() + + @Test fun `test#unit-tests#distributionManagement#variation-4`() = doTest() + + @Test fun `test#unit-tests#execute#variation-1`() = doTest() + + @Test fun `test#unit-tests#execute#variation-2`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-1`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-2`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-3`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-4`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-5`() = doTest() + + @Test fun `test#unit-tests#groupId#variation-6`() = doTest() + + @Test fun `test#unit-tests#id#variation-1`() = doTest() + + @Test fun `test#unit-tests#id#variation-2`() = doTest() + + @Test fun `test#unit-tests#id#variation-3`() = doTest() + + @Test fun `test#unit-tests#id#variation-4`() = doTest() + + @Test fun `test#unit-tests#inceptionYear#variation-1`() = doTest() + + @Test fun `test#unit-tests#inceptionYear#variation-2`() = doTest() + + @Test fun `test#unit-tests#inceptionYear#variation-3`() = doTest() + + @Test fun `test#unit-tests#issueManagement#variation-1`() = doTest() + + @Test fun `test#unit-tests#issueManagement#variation-2`() = doTest() + + @Test fun `test#unit-tests#licenses#variation-1`() = doTest() + + @Test fun `test#unit-tests#licenses#variation-2`() = doTest() + + @Test fun `test#unit-tests#licenses#variation-3`() = doTest() + + @Test fun `test#unit-tests#mailingLists#variation-1`() = doTest() + + @Test fun `test#unit-tests#mailingLists#variation-2`() = doTest() + + @Test fun `test#unit-tests#mailingLists#variation-3`() = doTest() + + @Test fun `test#unit-tests#modelVersion#variation-1`() = doTest() + + @Test fun `test#unit-tests#modelVersion#variation-2`() = doTest() + + @Test fun `test#unit-tests#modules#variation-1`() = doTest() + + @Test fun `test#unit-tests#modules#variation-2`() = doTest() + + @Test fun `test#unit-tests#name#variation-1`() = doTest() + + @Test fun `test#unit-tests#name#variation-2`() = doTest() + + @Test fun `test#unit-tests#name#variation-3`() = doTest() + + @Test fun `test#unit-tests#organization#variation-1`() = doTest() + + @Test fun `test#unit-tests#organization#variation-2`() = doTest() + + @Test fun `test#unit-tests#organization#variation-3`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-1`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-2`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-3`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-4`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-5`() = doTest() + + @Test fun `test#unit-tests#packaging#variation-6`() = doTest() + + @Test fun `test#unit-tests#parent#variation-1`() = doTest() + + @Test fun `test#unit-tests#parent#variation-2`() = doTest() + + @Test fun `test#unit-tests#parent#variation-3`() = doTest() + + @Test fun `test#unit-tests#parent#variation-4`() = doTest() + + @Test fun `test#unit-tests#parent#variation-5`() = doTest() + + @Test fun `test#unit-tests#parent#variation-6`() = doTest() + + @Test fun `test#unit-tests#pluginRepositories#variation-1`() = doTest() + + @Test fun `test#unit-tests#pluginRepositories#variation-2`() = doTest() + + @Test fun `test#unit-tests#pluginRepositories#variation-3`() = doTest() + + @Test fun `test#unit-tests#pluginRepositories#variation-4`() = doTest() + + @Test fun `test#unit-tests#prerequisites#variation-1`() = doTest() + + @Test fun `test#unit-tests#prerequisites#variation-2`() = doTest() + + @Test fun `test#unit-tests#profiles#variation-1`() = doTest() + + @Test fun `test#unit-tests#profiles#variation-2`() = doTest() + + @Test fun `test#unit-tests#properties#variation-1`() = doTest() + + @Test fun `test#unit-tests#properties#variation-2`() = doTest() + + @Test fun `test#unit-tests#reporting#variation-1`() = doTest() + + @Test fun `test#unit-tests#reporting#variation-2`() = doTest() + + @Test fun `test#unit-tests#reporting#variation-3`() = doTest() + + @Test fun `test#unit-tests#reporting#variation-4`() = doTest() + + @Test fun `test#unit-tests#reports#variation-1`() = doTest() + + @Test fun `test#unit-tests#reports#variation-2`() = doTest() + + @Test fun `test#unit-tests#reports#variation-3`() = doTest() + + @Test fun `test#unit-tests#reports#variation-4`() = doTest() + + @Test fun `test#unit-tests#reports#variation-5`() = doTest() + + @Test fun `test#unit-tests#repositories#variation-1`() = doTest() + + @Test fun `test#unit-tests#repositories#variation-2`() = doTest() + + @Test fun `test#unit-tests#repositories#variation-3`() = doTest() + + @Test fun `test#unit-tests#repositories#variation-4`() = doTest() + + @Test fun `test#unit-tests#scm#variation-1`() = doTest() + + @Test fun `test#unit-tests#scm#variation-2`() = doTest() + + @Test fun `test#unit-tests#url#variation-1`() = doTest() + + @Test fun `test#unit-tests#url#variation-2`() = doTest() + + @Test fun `test#unit-tests#version#variation-1`() = doTest() + + @Test fun `test#unit-tests#version#variation-2`() = doTest() + + @Test fun `test#unit-tests#version#variation-3`() = doTest() + + @Test fun `test#unit-tests#version#variation-4`() = doTest() + + @Test fun `test#unit-tests#version#variation-5`() = doTest() + + @Test fun `test#unit-tests#version#variation-6`() = doTest() + + // @formatter:on + + private fun doTest() { + assertEquals(pomXml, pomKts.kts2model().model2xml()) + } } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupportTests.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupportTests.kt index 4ee256cc..810b5fc6 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupportTests.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/dsl/DSLSupportTests.kt @@ -5,199 +5,216 @@ import org.junit.Test class DSLSupportTests { - @Test - fun `splitGavtc with gav (1 of 1)`() { - assertThat(splitCoordinates("com.example:sample-lib:1.0", 3)).containsExactly("com.example", "sample-lib", "1.0") - val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib:1.0", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + @Test + fun `splitGavtc with gav (1 of 1)`() { + assertThat(splitCoordinates("com.example:sample-lib:1.0", 3)) + .containsExactly("com.example", "sample-lib", "1.0") + val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib:1.0", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isEqualTo("1.0") - } - - @Test - fun `splitGavtc with ga_ (1 of 2)`() { - assertThat(splitCoordinates("com.example:sample-lib:", 3)).containsExactly("com.example", "sample-lib", null) - val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib:", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isEqualTo("1.0") + } + + @Test + fun `splitGavtc with ga_ (1 of 2)`() { + assertThat(splitCoordinates("com.example:sample-lib:", 3)) + .containsExactly("com.example", "sample-lib", null) + val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib:", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with ga_ (2 of 2)`() { - assertThat(splitCoordinates("com.example:sample-lib", 3)).containsExactly("com.example", "sample-lib", null) - val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with ga_ (2 of 2)`() { + assertThat(splitCoordinates("com.example:sample-lib", 3)) + .containsExactly("com.example", "sample-lib", null) + val (groupId, artifactId, version) = splitCoordinates("com.example:sample-lib", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with g_v (1 of 1)`() { - assertThat(splitCoordinates("com.example::1.0", 3)).containsExactly("com.example", null, "1.0") - val (groupId, artifactId, version) = splitCoordinates("com.example::1.0", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with g_v (1 of 1)`() { + assertThat(splitCoordinates("com.example::1.0", 3)).containsExactly("com.example", null, "1.0") + val (groupId, artifactId, version) = splitCoordinates("com.example::1.0", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isEqualTo("1.0") - } - - @Test - fun `splitGavtc with g__ (1 of 3)`() { - assertThat(splitCoordinates("com.example::", 3)).containsExactly("com.example", null, null) - val (groupId, artifactId, version) = splitCoordinates("com.example::", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isEqualTo("1.0") + } + + @Test + fun `splitGavtc with g__ (1 of 3)`() { + assertThat(splitCoordinates("com.example::", 3)).containsExactly("com.example", null, null) + val (groupId, artifactId, version) = splitCoordinates("com.example::", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with g__ (2 of 3)`() { - assertThat(splitCoordinates("com.example:", 3)).containsExactly("com.example", null, null) - val (groupId, artifactId, version) = splitCoordinates("com.example:", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with g__ (2 of 3)`() { + assertThat(splitCoordinates("com.example:", 3)).containsExactly("com.example", null, null) + val (groupId, artifactId, version) = splitCoordinates("com.example:", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with g__ (3 of 3)`() { - assertThat(splitCoordinates("com.example", 3)).containsExactly("com.example", null, null) - val (groupId, artifactId, version) = splitCoordinates("com.example", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with g__ (3 of 3)`() { + assertThat(splitCoordinates("com.example", 3)).containsExactly("com.example", null, null) + val (groupId, artifactId, version) = splitCoordinates("com.example", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isEqualTo("com.example") - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with _av (1 of 1)`() { - assertThat(splitCoordinates(":sample-lib:1.0", 3)).containsExactly(null, "sample-lib", "1.0") - val (groupId, artifactId, version) = splitCoordinates(":sample-lib:1.0", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isEqualTo("com.example") + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with _av (1 of 1)`() { + assertThat(splitCoordinates(":sample-lib:1.0", 3)).containsExactly(null, "sample-lib", "1.0") + val (groupId, artifactId, version) = splitCoordinates(":sample-lib:1.0", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isEqualTo("1.0") - } - - @Test - fun `splitGavtc with _a_ (1 of 2)`() { - assertThat(splitCoordinates(":sample-lib:", 3)).containsExactly(null, "sample-lib", null) - val (groupId, artifactId, version) = splitCoordinates(":sample-lib", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isEqualTo("1.0") + } + + @Test + fun `splitGavtc with _a_ (1 of 2)`() { + assertThat(splitCoordinates(":sample-lib:", 3)).containsExactly(null, "sample-lib", null) + val (groupId, artifactId, version) = splitCoordinates(":sample-lib", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with _a_ (2 of 2)`() { - assertThat(splitCoordinates(":sample-lib", 3)).containsExactly(null, "sample-lib", null) - val (groupId, artifactId, version) = splitCoordinates(":sample-lib", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with _a_ (2 of 2)`() { + assertThat(splitCoordinates(":sample-lib", 3)).containsExactly(null, "sample-lib", null) + val (groupId, artifactId, version) = splitCoordinates(":sample-lib", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isEqualTo("sample-lib") - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with __v (1 of 1)`() { - assertThat(splitCoordinates("::1.0", 3)).containsExactly(null, null, "1.0") - val (groupId, artifactId, version) = splitCoordinates("::1.0", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isEqualTo("sample-lib") + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with __v (1 of 1)`() { + assertThat(splitCoordinates("::1.0", 3)).containsExactly(null, null, "1.0") + val (groupId, artifactId, version) = splitCoordinates("::1.0", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isEqualTo("1.0") - } - - @Test - fun `splitGavtc with ___ (1 of 3)`() { - assertThat(splitCoordinates("::", 3)).containsExactly(null, null, null) - val (groupId, artifactId, version) = splitCoordinates("::", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isEqualTo("1.0") + } + + @Test + fun `splitGavtc with ___ (1 of 3)`() { + assertThat(splitCoordinates("::", 3)).containsExactly(null, null, null) + val (groupId, artifactId, version) = splitCoordinates("::", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with ___ (2 of 3)`() { - assertThat(splitCoordinates(":", 3)).containsExactly(null, null, null) - val (groupId, artifactId, version) = splitCoordinates(":", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with ___ (2 of 3)`() { + assertThat(splitCoordinates(":", 3)).containsExactly(null, null, null) + val (groupId, artifactId, version) = splitCoordinates(":", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } - - @Test - fun `splitGavtc with ___ (3 of 3)`() { - assertThat(splitCoordinates("", 3)).containsExactly(null, null, null) - val (groupId, artifactId, version) = splitCoordinates("", 3) - val dep = Dependency().apply { - this.groupId = groupId - this.artifactId = artifactId - this.version = version + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } + + @Test + fun `splitGavtc with ___ (3 of 3)`() { + assertThat(splitCoordinates("", 3)).containsExactly(null, null, null) + val (groupId, artifactId, version) = splitCoordinates("", 3) + val dep = + Dependency().apply { + this.groupId = groupId + this.artifactId = artifactId + this.version = version } - assertThat(dep.groupId).isNull() - assertThat(dep.artifactId).isNull() - assertThat(dep.version).isNull() - } -} \ No newline at end of file + assertThat(dep.groupId).isNull() + assertThat(dep.artifactId).isNull() + assertThat(dep.version).isNull() + } +} diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/AbstractModelTestCase.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/AbstractModelTestCase.kt index d7b043b3..61c8d618 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/AbstractModelTestCase.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/AbstractModelTestCase.kt @@ -1,5 +1,6 @@ package org.sonatype.maven.polyglot.kotlin.testing +import java.io.File import org.apache.maven.model.Model import org.apache.maven.model.building.ModelProcessor import org.apache.maven.model.io.ModelReader @@ -10,57 +11,60 @@ import org.codehaus.plexus.PlexusConstants import org.codehaus.plexus.PlexusTestCase import org.junit.Assert import org.sonatype.maven.polyglot.kotlin.dsl.propertiesFactory -import java.io.File abstract class AbstractModelTestCase(testName: String) : PlexusTestCase() { - init { - name = testName - propertiesFactory = { org.sonatype.maven.polyglot.kotlin.util.Properties() } - } + init { + name = testName + propertiesFactory = { org.sonatype.maven.polyglot.kotlin.util.Properties() } + } - override fun customizeContainerConfiguration(configuration: ContainerConfiguration?) { - configuration?.autoWiring = true; - configuration?.classPathScanning = PlexusConstants.SCANNING_CACHE - } + override fun customizeContainerConfiguration(configuration: ContainerConfiguration?) { + configuration?.autoWiring = true + configuration?.classPathScanning = PlexusConstants.SCANNING_CACHE + } - protected val testBasePath: String = testName.removePrefix("test#").replace('#', '/') - private val testResources: File = File("target/test-classes") - private val testOutput: File = File("target/test-output") + protected val testBasePath: String = testName.removePrefix("test#").replace('#', '/') + private val testResources: File = File("target/test-classes") + private val testOutput: File = File("target/test-output") - private val kotlinModelWriter: ModelWriter = lookup(ModelWriter::class.java, "kotlin") + private val kotlinModelWriter: ModelWriter = lookup(ModelWriter::class.java, "kotlin") - private val kotlinModelReader: ModelReader = lookup(ModelReader::class.java, "kotlin") + private val kotlinModelReader: ModelReader = lookup(ModelReader::class.java, "kotlin") - private val xmlModelReader: ModelReader = lookup(ModelReader::class.java, "default") + private val xmlModelReader: ModelReader = lookup(ModelReader::class.java, "default") - private val xmlModelWriter: ModelWriter = lookup(ModelWriter::class.java, "default") + private val xmlModelWriter: ModelWriter = lookup(ModelWriter::class.java, "default") - protected val pomXml: File = testResources.resolve(testBasePath).resolve("pom.xml").also { assertThat(it).exists() } + protected val pomXml: File = + testResources.resolve(testBasePath).resolve("pom.xml").also { assertThat(it).exists() } - protected val pomKts: File = testResources.resolve(testBasePath).resolve("pom.kts").also { assertThat(it).exists() } + protected val pomKts: File = + testResources.resolve(testBasePath).resolve("pom.kts").also { assertThat(it).exists() } - protected fun File.xml2model(vararg options: Pair): Model = xmlModelReader.read(this, mapOf(*options) + mapOf(ModelProcessor.SOURCE to this)) + protected fun File.xml2model(vararg options: Pair): Model = + xmlModelReader.read(this, mapOf(*options) + mapOf(ModelProcessor.SOURCE to this)) - protected fun File.kts2model(vararg options: Pair): Model = kotlinModelReader.read(this, mapOf(*options) + mapOf(ModelProcessor.SOURCE to this)) + protected fun File.kts2model(vararg options: Pair): Model = + kotlinModelReader.read(this, mapOf(*options) + mapOf(ModelProcessor.SOURCE to this)) - protected fun Model.model2xml(vararg options: Pair): File { - val basedir = testOutput.resolve(testBasePath) - basedir.mkdirs() - val file = basedir.resolve("pom.xml") - xmlModelWriter.write(file, mapOf(*options), this) - return file - } + protected fun Model.model2xml(vararg options: Pair): File { + val basedir = testOutput.resolve(testBasePath) + basedir.mkdirs() + val file = basedir.resolve("pom.xml") + xmlModelWriter.write(file, mapOf(*options), this) + return file + } - protected fun Model.model2kts(vararg options: Pair): File { - val basedir = testOutput.resolve(testBasePath) - basedir.mkdirs() - val file = basedir.resolve("pom.kts") - kotlinModelWriter.write(file, mapOf(*options), this) - return file - } + protected fun Model.model2kts(vararg options: Pair): File { + val basedir = testOutput.resolve(testBasePath) + basedir.mkdirs() + val file = basedir.resolve("pom.kts") + kotlinModelWriter.write(file, mapOf(*options), this) + return file + } - protected fun assertEquals(expected: File, actual: File) { - Assert.assertEquals(expected.readText(), actual.readText()) - } + protected fun assertEquals(expected: File, actual: File) { + Assert.assertEquals(expected.readText(), actual.readText()) + } } diff --git a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/extensions.kt b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/extensions.kt index b72f3ef5..71c0d0f3 100644 --- a/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/extensions.kt +++ b/polyglot-kotlin/src/test/kotlin/org/sonatype/maven/polyglot/kotlin/testing/extensions.kt @@ -1,119 +1,118 @@ package org.sonatype.maven.polyglot.kotlin.testing -import org.apache.maven.model.Model -import org.apache.maven.model.io.DefaultModelReader -import org.apache.maven.model.io.DefaultModelWriter -import org.apache.maven.model.io.xpp3.MavenXpp3Writer -import org.assertj.core.api.Assertions.assertThat import java.io.ByteArrayOutputStream import java.io.Reader import java.io.StringReader import java.io.StringWriter import java.lang.reflect.Field +import org.apache.maven.model.Model +import org.apache.maven.model.io.DefaultModelReader +import org.apache.maven.model.io.DefaultModelWriter +import org.apache.maven.model.io.xpp3.MavenXpp3Writer +import org.assertj.core.api.Assertions.assertThat -/** - * Returns a [Reader] to the classpath resource named by this string. - */ +/** Returns a [Reader] to the classpath resource named by this string. */ internal fun String.asResource(): Reader? { - println("Reading $this") - return Thread.currentThread().contextClassLoader.getResourceAsStream(this)?.reader() + println("Reading $this") + return Thread.currentThread().contextClassLoader.getResourceAsStream(this)?.reader() } internal fun println(model: Model) { - println(toString(model)) + println(toString(model)) } internal fun toString(model: Model): String { - val output = StringWriter() - val writer = MavenXpp3Writer() -// writer.setFileComment("\nGenerated from pom.kts on ${java.util.Date()}\n") - writer.write(output, model) - return output.toString() + val output = StringWriter() + val writer = MavenXpp3Writer() + // writer.setFileComment("\nGenerated from pom.kts on ${java.util.Date()}\n") + writer.write(output, model) + return output.toString() } internal fun toByteArray(model: Model): ByteArray? { - val output = ByteArrayOutputStream() - val writer = MavenXpp3Writer() -// writer.setFileComment("\nGenerated from pom.kts on ${java.util.Date()}\n") - writer.write(output, model) - return output.toByteArray() + val output = ByteArrayOutputStream() + val writer = MavenXpp3Writer() + // writer.setFileComment("\nGenerated from pom.kts on ${java.util.Date()}\n") + writer.write(output, model) + return output.toByteArray() } /** - * Asserts that no data is lost during serialization by doing a field by field comparison between the original model - * and the deserialized model. + * Asserts that no data is lost during serialization by doing a field by field comparison between + * the original model and the deserialized model. */ internal fun assertNoDataLossOnSerialization(project: Model) { - // Serialize the project model - val options = HashMap() - val output = StringWriter() - DefaultModelWriter().write(output, options, project) + // Serialize the project model + val options = HashMap() + val output = StringWriter() + DefaultModelWriter().write(output, options, project) - // Verify that the project model deserializes with all its original data - val input = StringReader(output.toString()) - val actual = DefaultModelReader().read(input, options) - compare("project", Model::class.java, project, actual) + // Verify that the project model deserializes with all its original data + val input = StringReader(output.toString()) + val actual = DefaultModelReader().read(input, options) + compare("project", Model::class.java, project, actual) } -//-- Private Implementation ------------------------------------------------------------------------------------------// +// -- Private Implementation +// ------------------------------------------------------------------------------------------// private const val comparingMessage = "Comparing %-50s: %s%n" private fun compare(name: String, type: Class<*>, o1: Any?, o2: Any?) { - System.out.printf(comparingMessage, name, type.name) - System.out.printf("\texpected: %s%n", o1?.toString()?.replace("\n", "\n ")) - System.out.printf("\tactual: %s%n", o2?.toString()?.replace("\n", "\n ")) - if (o1 !== o2) { - if (String::class.java.isAssignableFrom(type)) { - assertThat(o2).isEqualTo(o1).withFailMessage("'$name' values are not equal") - } else if (List::class.java.isAssignableFrom(type)) { - if (o1 is List<*> && o2 is List<*>) { - assertThat(o2.size).isEqualTo(o1.size).withFailMessage("'$name' values are not equal") - for (i in o1.indices) { - compare("$name[$i]", o1[i]!!::class.java, o1[i], o2[i]) - } - } - } else if (Map::class.java.isAssignableFrom(type)) { - if (o1 is Map<*, *> && o2 is Map<*, *>) { - assertThat(o2.size).isEqualTo(o1.size).withFailMessage("'$name' values are not equal") - val keys = setOf(*o1.keys.toTypedArray(), *o2.keys.toTypedArray()) - for (key in keys) { - compare("$name['$key']", o1[key]!!::class.java, o1[key], o2[key]) - } - } - } else if (o1 != null && o2 != null) { - if (o2 is Model) { - // Calling getters on lazily populated fields - o2.developers - o2.contributors - o2.mailingLists - o2.build?.resources - o2.build?.testResources - o2.build?.filters - o2.modules - } - doWithFields(type) { field -> compare("$name.${field.name}", field, o1, o2) } - } else { - assertThat(o2).isEqualTo(o1).withFailMessage("'$name' values are not equal") + System.out.printf(comparingMessage, name, type.name) + System.out.printf("\texpected: %s%n", o1?.toString()?.replace("\n", "\n ")) + System.out.printf("\tactual: %s%n", o2?.toString()?.replace("\n", "\n ")) + if (o1 !== o2) { + if (String::class.java.isAssignableFrom(type)) { + assertThat(o2).isEqualTo(o1).withFailMessage("'$name' values are not equal") + } else if (List::class.java.isAssignableFrom(type)) { + if (o1 is List<*> && o2 is List<*>) { + assertThat(o2.size).isEqualTo(o1.size).withFailMessage("'$name' values are not equal") + for (i in o1.indices) { + compare("$name[$i]", o1[i]!!::class.java, o1[i], o2[i]) } + } + } else if (Map::class.java.isAssignableFrom(type)) { + if (o1 is Map<*, *> && o2 is Map<*, *>) { + assertThat(o2.size).isEqualTo(o1.size).withFailMessage("'$name' values are not equal") + val keys = setOf(*o1.keys.toTypedArray(), *o2.keys.toTypedArray()) + for (key in keys) { + compare("$name['$key']", o1[key]!!::class.java, o1[key], o2[key]) + } + } + } else if (o1 != null && o2 != null) { + if (o2 is Model) { + // Calling getters on lazily populated fields + o2.developers + o2.contributors + o2.mailingLists + o2.build?.resources + o2.build?.testResources + o2.build?.filters + o2.modules + } + doWithFields(type) { field -> compare("$name.${field.name}", field, o1, o2) } + } else { + assertThat(o2).isEqualTo(o1).withFailMessage("'$name' values are not equal") } + } } private fun compare(name: String, field: Field, o1: T, o2: T) { - field.isAccessible = true - val expected = field.get(o1) - val actual = field.get(o2) - compare(name, field.type, expected, actual) + field.isAccessible = true + val expected = field.get(o1) + val actual = field.get(o2) + compare(name, field.type, expected, actual) } private fun doWithFields(clazz: Class<*>, fieldCallback: (Field) -> Unit) { - var targetClass: Class<*>? = clazz - do { - val tc = targetClass!! - val fields = tc.declaredFields - for (field in fields) { - fieldCallback.invoke(field) - } - targetClass = tc.superclass - } while (targetClass != null && targetClass != Any::class.java) + var targetClass: Class<*>? = clazz + do { + val tc = targetClass!! + val fields = tc.declaredFields + for (field in fields) { + fieldCallback.invoke(field) + } + targetClass = tc.superclass + } while (targetClass != null && targetClass != Any::class.java) } diff --git a/polyglot-maven-plugin/pom.xml b/polyglot-maven-plugin/pom.xml index fbfe448c..8bd0f1ab 100644 --- a/polyglot-maven-plugin/pom.xml +++ b/polyglot-maven-plugin/pom.xml @@ -14,8 +14,8 @@ polyglot-maven-plugin - Polyglot :: Maven Plugin takari-maven-plugin + Polyglot :: Maven Plugin diff --git a/polyglot-maven-plugin/src/main/java/org/sonatype/maven/polyglot/plugin/ExecuteMojo.java b/polyglot-maven-plugin/src/main/java/org/sonatype/maven/polyglot/plugin/ExecuteMojo.java index 4edc5740..8067b8b5 100644 --- a/polyglot-maven-plugin/src/main/java/org/sonatype/maven/polyglot/plugin/ExecuteMojo.java +++ b/polyglot-maven-plugin/src/main/java/org/sonatype/maven/polyglot/plugin/ExecuteMojo.java @@ -12,7 +12,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.building.FileModelSource; @@ -38,99 +37,99 @@ * * @author Jason Dillon */ -@Mojo(name="execute", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) +@Mojo(name = "execute", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class ExecuteMojo extends AbstractMojo { - - @Component(role = ExecuteManager.class) - private ExecuteManager manager; - @Parameter(defaultValue = "${project}", required = true, readonly = true) - private MavenProject project; + @Component(role = ExecuteManager.class) + private ExecuteManager manager; - @Parameter(defaultValue = "${session}", required = true, readonly = true) - private MavenSession session; + @Parameter(defaultValue = "${project}", required = true, readonly = true) + private MavenProject project; - @Parameter(required = true, property="taskId") - private String taskId; + @Parameter(defaultValue = "${session}", required = true, readonly = true) + private MavenSession session; - @Parameter - private File nativePom; + @Parameter(required = true, property = "taskId") + private String taskId; - @Component(role = PolyglotModelManager.class) - private PolyglotModelManager modelManager; + @Parameter + private File nativePom; - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - Log log = getLog(); - Model model = project.getModel(); + @Component(role = PolyglotModelManager.class) + private PolyglotModelManager modelManager; - if (log.isDebugEnabled()) { - log.debug("Executing task '" + taskId + "' for model: " + model.getId()); - } + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + Log log = getLog(); + Model model = project.getModel(); - assert manager != null; - List tasks = manager.getTasks(model); - // if there are no tasks that means we run in proper maven and - // have to load the nativePom to setup the ExecuteManager - if (tasks.size() == 0 && nativePom != null) { - // TODO avoid parsing the nativePom for each task - tasks = manager.getTasks(modelFromNativePom(log)); - } - - ExecuteContext ctx = new ExecuteContext() { - @Override - public MavenProject getProject() { - return project; - } + if (log.isDebugEnabled()) { + log.debug("Executing task '" + taskId + "' for model: " + model.getId()); + } - @Override - public MavenSession getSession() { - return session; - } + assert manager != null; + List tasks = manager.getTasks(model); + // if there are no tasks that means we run in proper maven and + // have to load the nativePom to setup the ExecuteManager + if (tasks.size() == 0 && nativePom != null) { + // TODO avoid parsing the nativePom for each task + tasks = manager.getTasks(modelFromNativePom(log)); + } - @Override - public File getBasedir() { - return project.getBasedir(); - } + ExecuteContext ctx = new ExecuteContext() { + @Override + public MavenProject getProject() { + return project; + } + + @Override + public MavenSession getSession() { + return session; + } + + @Override + public File getBasedir() { + return project.getBasedir(); + } + + @Override + public Log getLog() { + return ExecuteMojo.this.getLog(); + } + }; + + for (ExecuteTask task : tasks) { + if (taskId.equals(task.getId())) { + log.debug("Executing task: " + task.getId()); + + try { + task.execute(ctx); + return; + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage(), e); + } + } + } - @Override - public Log getLog() { - return ExecuteMojo.this.getLog(); - } - }; + throw new MojoFailureException("Unable to find task for id: " + taskId); + } - for (ExecuteTask task : tasks) { - if (taskId.equals(task.getId())) { - log.debug("Executing task: " + task.getId()); + protected Model modelFromNativePom(Log log) throws MojoExecutionException, MojoFailureException { + Map options = new HashMap(); + options.put(ModelProcessor.SOURCE, new FileModelSource(nativePom)); + assert modelManager != null; try { - task.execute(ctx); - return; - } catch (Exception e) { - throw new MojoExecutionException(e.getMessage(), e); + ModelReader reader = modelManager.getReaderFor(options); + if (reader == null) { + throw new MojoExecutionException("no model reader found for " + nativePom); + } + if (log.isDebugEnabled()) { + log.debug("Parsing native pom " + nativePom); + } + return reader.read(nativePom, options); + } catch (IOException e) { + throw new MojoFailureException("error parsing " + nativePom, e); } - } - } - - throw new MojoFailureException("Unable to find task for id: " + taskId); - } - - protected Model modelFromNativePom(Log log) throws MojoExecutionException, MojoFailureException { - Map options = new HashMap(); - options.put(ModelProcessor.SOURCE, new FileModelSource(nativePom)); - - assert modelManager != null; - try { - ModelReader reader = modelManager.getReaderFor(options); - if (reader == null) { - throw new MojoExecutionException("no model reader found for " + nativePom); - } - if (log.isDebugEnabled()) { - log.debug("Parsing native pom " + nativePom); - } - return reader.read(nativePom, options); - } catch (IOException e) { - throw new MojoFailureException("error parsing " + nativePom, e); } - } -} \ No newline at end of file +} diff --git a/polyglot-maven-plugin/src/test/java/org/sonatype/maven/polyglot/plugin/VersionTest.java b/polyglot-maven-plugin/src/test/java/org/sonatype/maven/polyglot/plugin/VersionTest.java index 64c4bf10..172b0934 100644 --- a/polyglot-maven-plugin/src/test/java/org/sonatype/maven/polyglot/plugin/VersionTest.java +++ b/polyglot-maven-plugin/src/test/java/org/sonatype/maven/polyglot/plugin/VersionTest.java @@ -7,22 +7,16 @@ */ package org.sonatype.maven.polyglot.plugin; -import static org.junit.Assert.assertEquals; - import org.junit.Test; -import org.sonatype.maven.polyglot.Constants; -public class VersionTest -{ +public class VersionTest { @Test - public void test() - { + public void test() { /* assertEquals( "plugin version mismatched with the version used to create internal plugin configuration", - Constants.getVersion(), + Constants.getVersion(), System.getProperty( "projectversion" ) ); */ } - } diff --git a/polyglot-ruby/pom.xml b/polyglot-ruby/pom.xml index 2248c17d..df7674d8 100644 --- a/polyglot-ruby/pom.xml +++ b/polyglot-ruby/pom.xml @@ -22,6 +22,10 @@ takari-maven-component Polyglot :: Ruby + + 2.0.2 + + io.takari.polyglot @@ -42,10 +46,6 @@ - - 2.0.2 - - @@ -60,34 +60,6 @@ - - - org.jruby.maven - mavengem-wagon - ${mavengem-wagon.version} - - - - - maven-invoker-plugin - - ${project.build.directory}/it - - - - integration-test - - install - run - - - ${basedir}/src/it/settings.xml - ${project.build.directory}/local-repo - - - - - @@ -101,12 +73,8 @@ org.jruby.maven - - gem-maven-plugin - - - [1.0.1,) - + gem-maven-plugin + [1.0.1,) initialize @@ -121,6 +89,34 @@ + + + maven-invoker-plugin + + ${project.build.directory}/it + + + + integration-test + + install + run + + + ${basedir}/src/it/settings.xml + ${project.build.directory}/local-repo + + + + + + + + org.jruby.maven + mavengem-wagon + ${mavengem-wagon.version} + + build - + ../polyglot-common - - - mavengems - mavengem:https://rubygems.org - - - + + 3.0.2 + + rubygems @@ -157,9 +150,12 @@ - - 3.0.2 - + + + mavengems + mavengem:https://rubygems.org + + @@ -168,6 +164,9 @@ org.jruby.maven gem-maven-plugin ${jruby.plugins.version} + + provided + @@ -175,9 +174,6 @@ - - provided - diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/ConfigVisitor.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/ConfigVisitor.java index b1ef399c..6ec77ecb 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/ConfigVisitor.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/ConfigVisitor.java @@ -11,17 +11,18 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; - import org.codehaus.plexus.util.xml.Xpp3Dom; -class ConfigVisitor -{ +class ConfigVisitor { final Config config = new Config(); - static class Config - { + static class Config { static enum Type { - SINGLE, MULTI, MIXED, MAPS, MAP + SINGLE, + MULTI, + MIXED, + MAPS, + MAP } Type type; @@ -31,197 +32,156 @@ static enum Type { List> mapList; Map map; - void add( String value ) - { - if ( stringList != null ) - { - this.stringList.add( value ); - } - else if ( this.value == null ) - { + void add(String value) { + if (stringList != null) { + this.stringList.add(value); + } else if (this.value == null) { this.type = Type.SINGLE; this.value = value; - } - else - { + } else { this.type = Type.MULTI; this.stringList = new LinkedList(); - this.stringList.add( this.value ); - this.stringList.add( value ); + this.stringList.add(this.value); + this.stringList.add(value); this.value = null; } } - void add( Xpp3Dom item ) - { - if ( this.list == null ) - { + void add(Xpp3Dom item) { + if (this.list == null) { this.type = Type.MIXED; this.list = new LinkedList(); } - if ( item.getValue() == null ) - { - list.add( new ListItem( item ) ); - } - else - { - list.add( new ListItem( item.getValue() ) ); + if (item.getValue() == null) { + list.add(new ListItem(item)); + } else { + list.add(new ListItem(item.getValue())); } } - void add( Map map ) - { - if ( this.mapList == null ) - { + void add(Map map) { + if (this.mapList == null) { this.type = Type.MAPS; this.mapList = new LinkedList>(); } - this.mapList.add( map ); + this.mapList.add(map); } - void put( String name, Config config ) - { - if ( this.map == null ) - { + void put(String name, Config config) { + if (this.map == null) { this.type = Type.MAP; this.map = new LinkedHashMap(); } - this.map.put( name, config ); + this.map.put(name, config); } - Config get( String name ) - { - if ( this.map == null ) - { + Config get(String name) { + if (this.map == null) { this.type = Type.MAP; this.map = new LinkedHashMap(); } - if ( this.map.containsKey( name ) ) - { - return (Config) this.map.get( name ); - } - else - { + if (this.map.containsKey(name)) { + return (Config) this.map.get(name); + } else { Config config = new Config(); - this.map.put( name, config ); + this.map.put(name, config); return config; } } } - static class Leaf - { + + static class Leaf { private String value; private String name; - Leaf( String name, String value ) - { + + Leaf(String name, String value) { this.name = name; this.value = value; } - void accept( ConfigVisitor visitor ) - { - visitor.config.get( name ).add( value ); + void accept(ConfigVisitor visitor) { + visitor.config.get(name).add(value); } } - static class Node - { + static class Node { Xpp3Dom base; - Node( Xpp3Dom base ) - { + + Node(Xpp3Dom base) { this.base = base; } - void accept( ConfigVisitor visitor ) - { + + void accept(ConfigVisitor visitor) { ConfigVisitor nextVisitor = new ConfigVisitor(); - nextVisitor.visit( this ); - visitor.config.put( base.getName(), nextVisitor.config ); + nextVisitor.visit(this); + visitor.config.put(base.getName(), nextVisitor.config); } } - static class ListItem - { + static class ListItem { final String xml; final String value; - ListItem( String value ) - { + ListItem(String value) { this.value = value; this.xml = null; } - ListItem( Xpp3Dom xml ) - { + ListItem(Xpp3Dom xml) { this.value = null; - this.xml = xml.toString().replaceFirst( "\\s*", "" ); + this.xml = xml.toString().replaceFirst("\\s*", ""); } - boolean isXml() - { + boolean isXml() { return xml != null; } - public String toString() - { + public String toString() { return xml == null ? value : xml; } } - static class ListNode extends Node - { - ListNode( Xpp3Dom base ) - { - super( base ); + static class ListNode extends Node { + ListNode(Xpp3Dom base) { + super(base); } - void accept( ConfigVisitor visitor ) - { - if ( base.getChild( 0 ).getChildCount() == 0 ) - { + void accept(ConfigVisitor visitor) { + if (base.getChild(0).getChildCount() == 0) { Config list = new Config(); - for( Xpp3Dom child : base.getChildren() ) - { - list.add( child ); + for (Xpp3Dom child : base.getChildren()) { + list.add(child); } - visitor.config.put( base.getName(), list ); - } - else - { + visitor.config.put(base.getName(), list); + } else { Config list = new Config(); - for( Xpp3Dom child : base.getChildren() ) - { + for (Xpp3Dom child : base.getChildren()) { ConfigVisitor nextVisitor = new ConfigVisitor(); - nextVisitor.visit( new Node( child ) ); - list.add( nextVisitor.config.map ); + nextVisitor.visit(new Node(child)); + list.add(nextVisitor.config.map); } - visitor.config.put( base.getName(), list ); + visitor.config.put(base.getName(), list); } } } - void visit( Node node ) - { - for( String name: node.base.getAttributeNames() ) - { - new Leaf( "@" + name, - node.base.getAttribute( name ) - .replaceAll( "'", "\\\\'" ) ).accept( this ); - } - for ( Xpp3Dom child : node.base.getChildren() ) - { - if ( child.getChildCount() == 0 && child.getAttributeNames().length == 0 ) - { - new Leaf( child.getName(), child.getValue() ).accept( this ); - } - else if ( ( child.getChildCount() > 1 && child.getChild(0).getName().equals( child.getChild( 1 ).getName() ) ) - || ( child.getChildCount() == 1 && child.getName().equals( child.getChild( 0 ).getName() + "s" ) ) ) - { - new ListNode( child ).accept( this ); - } - else - { - new Node( child ).accept( this ); + void visit(Node node) { + for (String name : node.base.getAttributeNames()) { + new Leaf("@" + name, node.base.getAttribute(name).replaceAll("'", "\\\\'")).accept(this); + } + for (Xpp3Dom child : node.base.getChildren()) { + if (child.getChildCount() == 0 && child.getAttributeNames().length == 0) { + new Leaf(child.getName(), child.getValue()).accept(this); + } else if ((child.getChildCount() > 1 + && child.getChild(0) + .getName() + .equals(child.getChild(1).getName())) + || (child.getChildCount() == 1 + && child.getName().equals(child.getChild(0).getName() + "s"))) { + new ListNode(child).accept(this); + } else { + new Node(child).accept(this); } } } -} \ No newline at end of file +} diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyMapping.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyMapping.java index 10f47bfb..00058f63 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyMapping.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyMapping.java @@ -7,12 +7,10 @@ */ package org.sonatype.maven.polyglot.ruby; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.File; import java.io.FilenameFilter; - +import javax.inject.Named; +import javax.inject.Singleton; import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -21,38 +19,30 @@ * @author m.kristian */ @Singleton -@Named( "ruby" ) -public class RubyMapping extends MappingSupport -{ - public RubyMapping() - { - super( "ruby" ); - setPomNames( "pom.rb", "Mavenfile", "Jarfile", "Gemfile" ); - setAcceptLocationExtensions( ".rb", "Mavenfile", "Jarfile", "Gemfile", ".gemspec" ); - setAcceptOptionKeys( "ruby:4.0.0" ); - setPriority(1); - } +@Named("ruby") +public class RubyMapping extends MappingSupport { + public RubyMapping() { + super("ruby"); + setPomNames("pom.rb", "Mavenfile", "Jarfile", "Gemfile"); + setAcceptLocationExtensions(".rb", "Mavenfile", "Jarfile", "Gemfile", ".gemspec"); + setAcceptOptionKeys("ruby:4.0.0"); + setPriority(1); + } + + @Override + public File locatePom(File dir) { + File result = super.locatePom(dir); + if (result == null) { + String[] list = dir.list(new FilenameFilter() { - @Override - public File locatePom( File dir ) - { - File result = super.locatePom( dir ); - if ( result == null ) - { - String[] list = dir.list( new FilenameFilter() { - - public boolean accept( File dir, String name ) - { - return name.endsWith( ".gemspec" ); + public boolean accept(File dir, String name) { + return name.endsWith(".gemspec"); + } + }); + if (list.length == 1) { + result = new File(dir, list[0]); } - } ); - if ( list.length == 1 ) - { - result = new File( dir, list[ 0 ] ); - } - } - return result; - } - - + } + return result; + } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelReader.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelReader.java index 532b7528..5404f5c2 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelReader.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelReader.java @@ -7,15 +7,13 @@ */ package org.sonatype.maven.polyglot.ruby; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.util.Map; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.util.IOUtil; @@ -30,33 +28,31 @@ * @author m.kristian */ @Singleton -@Named( "ruby" ) +@Named("ruby") public class RubyModelReader extends ModelReaderSupport { @Inject ExecuteManager executeManager; - + @Inject SetupClassRealm setupManager; - - public Model read( final Reader input, final Map options ) - throws IOException { + + public Model read(final Reader input, final Map options) throws IOException { assert input != null; - // for testing that classloader does not need to be a ClassRealm, i.e. the test setup needs + // for testing that classloader does not need to be a ClassRealm, i.e. the test setup needs // to take care that all classes are in place - if ( getClass().getClassLoader() instanceof ClassRealm ) { - setupManager.setupArtifact( Constants.getGAV( "ruby" ), - (ClassRealm) getClass().getClassLoader() ); + if (getClass().getClassLoader() instanceof ClassRealm) { + setupManager.setupArtifact( + Constants.getGAV("ruby"), (ClassRealm) getClass().getClassLoader()); } - + // read the stream from our pom.rb into a String StringWriter ruby = new StringWriter(); - IOUtil.copy( input, ruby ); - + IOUtil.copy(input, ruby); + // parse the String and create a POM model - return new RubyParser( executeManager ).parse( ruby.toString(), - PolyglotModelUtil.getLocationFile( options ), - options ); + return new RubyParser(executeManager) + .parse(ruby.toString(), PolyglotModelUtil.getLocationFile(options), options); } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelWriter.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelWriter.java index bd750a74..bf6e85d1 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelWriter.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyModelWriter.java @@ -7,9 +7,6 @@ */ package org.sonatype.maven.polyglot.ruby; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Writer; import java.util.ArrayList; @@ -18,7 +15,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Activation; import org.apache.maven.model.ActivationFile; import org.apache.maven.model.ActivationOS; @@ -51,30 +49,29 @@ import org.sonatype.maven.polyglot.io.ModelWriterSupport; @Singleton -@Named( "ruby" ) +@Named("ruby") public class RubyModelWriter extends ModelWriterSupport { - protected Logger log = LoggerFactory.getLogger( RubyModelWriter.class ); + protected Logger log = LoggerFactory.getLogger(RubyModelWriter.class); - public void write( final Writer output, final Map options, - final Model model ) throws IOException { + public void write(final Writer output, final Map options, final Model model) throws IOException { assert output != null; assert model != null; - ModelPrinter p = new ModelPrinter( output ); - p.print( model ); + ModelPrinter p = new ModelPrinter(output); + p.print(model); } static class ModelPrinter { private final RubyPrintWriter p; - ModelPrinter( Writer output ) { + ModelPrinter(Writer output) { this.p = new RubyPrintWriter(output); } - void print( Model model ) { + void print(Model model) { - project( model ); + project(model); p.flush(); p.close(); @@ -94,21 +91,23 @@ void pluginRepositories(Repository... repositories) { } } - void distribution( DistributionManagement distribution ){ - if ( distribution != null ){ - p.printStartBlock( "distribution" ); - if ( distribution.getRepository() != null ){ - printRepositories("repository", distribution.getRepository() ); + void distribution(DistributionManagement distribution) { + if (distribution != null) { + p.printStartBlock("distribution"); + if (distribution.getRepository() != null) { + printRepositories("repository", distribution.getRepository()); } - if ( distribution.getSnapshotRepository() != null ){ - printRepositories("snapshot_repository", distribution.getSnapshotRepository() ); + if (distribution.getSnapshotRepository() != null) { + printRepositories("snapshot_repository", distribution.getSnapshotRepository()); } - if ( distribution.getSite() != null ){ + if (distribution.getSite() != null) { Site site = distribution.getSite(); - p.printWithOptions( "site", - options( "id", site.getId(), - "name", site.getName(), - "url", site.getUrl() ) ); + p.printWithOptions( + "site", + options( + "id", site.getId(), + "name", site.getName(), + "url", site.getUrl())); } p.printEndBlock(); p.println(); @@ -118,14 +117,13 @@ void distribution( DistributionManagement distribution ){ private Map options(Object... args) { Map options = new LinkedHashMap(); String key = null; - for( Object arg : args ){ - if( key == null ){ + for (Object arg : args) { + if (key == null) { key = arg.toString(); continue; - } - else { - if (arg != null ){ - options.put( key, arg ); + } else { + if (arg != null) { + options.put(key, arg); } key = null; } @@ -133,50 +131,43 @@ private Map options(Object... args) { return options; } - void sourceControl( Scm scm ){ - if ( scm != null ){ - p.printWithOptions( "source_control", - options( "url", scm.getUrl(), - "connection", scm.getConnection(), - "developer_connection", scm.getDeveloperConnection(), - "tag", scm.getTag().equals( "HEAD" ) ? null : scm.getTag() ) ); + void sourceControl(Scm scm) { + if (scm != null) { + p.printWithOptions( + "source_control", + options( + "url", scm.getUrl(), + "connection", scm.getConnection(), + "developer_connection", scm.getDeveloperConnection(), + "tag", scm.getTag().equals("HEAD") ? null : scm.getTag())); p.println(); } } - private void printRepositories(String name, - Repository... repositories) { - for (Repository r: repositories) { - if ( r.getReleases() == null && r.getSnapshots() == null ) - { - p.printWithOptions( name, - options( "id", r.getId(), - "name", r.getName(), - "url", r.getUrl() ) ); - } - else - { - p.printStartBlock( name, - options( "id", r.getId(), - "name", r.getName(), - "url", r.getUrl() ) ); - printRepositoryPolicy( "releases", r.getReleases() ); - printRepositoryPolicy( "snapshots", r.getSnapshots() ); + private void printRepositories(String name, Repository... repositories) { + for (Repository r : repositories) { + if (r.getReleases() == null && r.getSnapshots() == null) { + p.printWithOptions( + name, + options( + "id", r.getId(), + "name", r.getName(), + "url", r.getUrl())); + } else { + p.printStartBlock(name, options("id", r.getId(), "name", r.getName(), "url", r.getUrl())); + printRepositoryPolicy("releases", r.getReleases()); + printRepositoryPolicy("snapshots", r.getSnapshots()); p.printEndBlock(); } } } - private void printRepositoryPolicy( String name, RepositoryPolicy policy ) - { - if ( policy != null ) - { - if ( policy.getChecksumPolicy() == null && policy.getUpdatePolicy() == null ){ - p.println( name + " " + policy.isEnabled() ); - } - else - { - p.println( "TODO: " + policy ); + private void printRepositoryPolicy(String name, RepositoryPolicy policy) { + if (policy != null) { + if (policy.getChecksumPolicy() == null && policy.getUpdatePolicy() == null) { + p.println(name + " " + policy.isEnabled()); + } else { + p.println("TODO: " + policy); } } } @@ -187,11 +178,11 @@ void project(Model model) { name = model.getArtifactId(); } - p.printStartBlock( "project", name, model.getUrl() ); + p.printStartBlock("project", name, model.getUrl()); p.println(); - p.println( "model_version", model.getModelVersion() ); - p.println( "inception_year", model.getInceptionYear() ); + p.println("model_version", model.getModelVersion()); + p.println("inception_year", model.getInceptionYear()); id(model); parent(model.getParent()); @@ -201,186 +192,167 @@ void project(Model model) { description(model.getDescription()); - developers( model.getDevelopers() ); + developers(model.getDevelopers()); - issueManagement( model.getIssueManagement() ); + issueManagement(model.getIssueManagement()); - mailingLists( model.getMailingLists() ); + mailingLists(model.getMailingLists()); - repositories( toRepositoryArray( model.getRepositories() ) ); + repositories(toRepositoryArray(model.getRepositories())); - pluginRepositories( toRepositoryArray( model.getPluginRepositories() ) ); + pluginRepositories(toRepositoryArray(model.getPluginRepositories())); - sourceControl( model.getScm() ); + sourceControl(model.getScm()); - distribution( model.getDistributionManagement() ); + distribution(model.getDistributionManagement()); - properties( model.getProperties() ); + properties(model.getProperties()); - dependencies( model.getDependencies() ); + dependencies(model.getDependencies()); - modules( model.getModules() ); + modules(model.getModules()); - managements( model.getDependencyManagement(), model.getBuild() ); + managements(model.getDependencyManagement(), model.getBuild()); - build( model.getBuild(), model.getBuild() ); + build(model.getBuild(), model.getBuild()); - profiles( model.getProfiles() ); + profiles(model.getProfiles()); - reporting( model.getReporting() ); + reporting(model.getReporting()); p.printEndBlock(); } - private void mailingLists( List mailingLists ) - { - for( MailingList list : mailingLists ) - { - p.printStartBlock( "mailing_list", list.getName() ); - p.println( "subscribe", list.getSubscribe() ); - p.println( "unsubscribe", list.getUnsubscribe() ); - p.println( "post", list.getPost() ); + private void mailingLists(List mailingLists) { + for (MailingList list : mailingLists) { + p.printStartBlock("mailing_list", list.getName()); + p.println("subscribe", list.getSubscribe()); + p.println("unsubscribe", list.getUnsubscribe()); + p.println("post", list.getPost()); // not thread safe !! - list.getOtherArchives().add( 0, list.getArchive() ); - p.println( "archives", toArray( list.getOtherArchives() ) ); + list.getOtherArchives().add(0, list.getArchive()); + p.println("archives", toArray(list.getOtherArchives())); // keep model as is - not thread safe !! - list.getOtherArchives().remove( 0 ); + list.getOtherArchives().remove(0); p.printEndBlock(); p.println(); } } - private void issueManagement( IssueManagement issueManagement ) - { - if( issueManagement != null ) - { - p.println( "issue_management", issueManagement.getUrl(), issueManagement.getSystem() ); + private void issueManagement(IssueManagement issueManagement) { + if (issueManagement != null) { + p.println("issue_management", issueManagement.getUrl(), issueManagement.getSystem()); p.println(); } } - private void developers( List developers ) - { - for( Developer dev : developers ) - { - p.printStartBlock( "developer", dev.getId() ); - p.println( "name", dev.getName() ); - p.println( "email", dev.getEmail() ); - p.println( "roles", toArray( dev.getRoles() ) ); + private void developers(List developers) { + for (Developer dev : developers) { + p.printStartBlock("developer", dev.getId()); + p.println("name", dev.getName()); + p.println("email", dev.getEmail()); + p.println("roles", toArray(dev.getRoles())); p.printEndBlock(); p.println(); } } void reporting(Reporting reporting) { - if ( reporting != null ){ - p.printStartBlock( "reporting" ); - plugins( reporting.getPlugins() ); + if (reporting != null) { + p.printStartBlock("reporting"); + plugins(reporting.getPlugins()); p.printEndBlock(); p.println(); } } - void profiles( List profiles ) { - if ( profiles != null ){ - for( Profile profile: profiles ){ - p.print( "profile" ); - if (profile.getId() != null ){ - p.append( " '" ).append( profile.getId() ).append( "'" ); + void profiles(List profiles) { + if (profiles != null) { + for (Profile profile : profiles) { + p.print("profile"); + if (profile.getId() != null) { + p.append(" '").append(profile.getId()).append("'"); p.printStartBlock(); p.println(); - if ( profile.getActivation() != null ) - { + if (profile.getActivation() != null) { Activation activation = profile.getActivation(); - p.printStartBlock( "activation" ); + p.printStartBlock("activation"); { ActivationProperty prop = activation.getProperty(); - if ( prop != null ) - { + if (prop != null) { Map options = new LinkedHashMap(); - options.put( "name", prop.getName() ); - if ( prop.getValue() != null ) - { - options.put( "value", prop.getValue() ); + options.put("name", prop.getName()); + if (prop.getValue() != null) { + options.put("value", prop.getValue()); } - p.printWithOptions( "property", options ); + p.printWithOptions("property", options); } } { ActivationFile file = activation.getFile(); - if ( file != null ) - { + if (file != null) { Map options = new LinkedHashMap(); - if ( file.getExists() != null ) - { - options.put( "exists", file.getExists() ); + if (file.getExists() != null) { + options.put("exists", file.getExists()); } - if ( file.getMissing() != null ) - { - options.put( "missing", file.getMissing() ); + if (file.getMissing() != null) { + options.put("missing", file.getMissing()); } - p.printWithOptions( "file", options ); + p.printWithOptions("file", options); } } { String jdk = activation.getJdk(); - if ( jdk != null ) - { - p.print( "jdk", jdk ); + if (jdk != null) { + p.print("jdk", jdk); } } { - if ( activation.isActiveByDefault() ) - { - p.print( "active_by_default", "true" ); + if (activation.isActiveByDefault()) { + p.print("active_by_default", "true"); } } { ActivationOS os = activation.getOs(); - if ( os != null ) - { + if (os != null) { Map options = new LinkedHashMap(); - if ( os.getArch() != null ) - { - options.put( "arch", os.getArch() ); + if (os.getArch() != null) { + options.put("arch", os.getArch()); } - if ( os.getFamily() != null ) - { - options.put( "family", os.getFamily() ); + if (os.getFamily() != null) { + options.put("family", os.getFamily()); } - if ( os.getName() != null ) - { - options.put( "name", os.getName() ); + if (os.getName() != null) { + options.put("name", os.getName()); } - if ( os.getVersion() != null ) - { - options.put( "version", os.getVersion() ); + if (os.getVersion() != null) { + options.put("version", os.getVersion()); } - p.printWithOptions( "os", options ); + p.printWithOptions("os", options); } } p.printEndBlock(); p.println(); } - repositories( toRepositoryArray( profile.getRepositories() ) ); + repositories(toRepositoryArray(profile.getRepositories())); - pluginRepositories( toRepositoryArray( profile.getPluginRepositories() ) ); + pluginRepositories(toRepositoryArray(profile.getPluginRepositories())); - distribution( profile.getDistributionManagement() ); + distribution(profile.getDistributionManagement()); - properties( profile.getProperties() ); + properties(profile.getProperties()); - dependencies( profile.getDependencies() ); + dependencies(profile.getDependencies()); - modules( profile.getModules() ); + modules(profile.getModules()); - managements( profile.getDependencyManagement(), profile.getBuild() ); + managements(profile.getDependencyManagement(), profile.getBuild()); - build( profile.getBuild() ); + build(profile.getBuild()); - reporting( profile.getReporting() ); + reporting(profile.getReporting()); p.printEndBlock(); p.println(); @@ -396,59 +368,51 @@ void description(String description) { } } - void build( BuildBase build ) { - build( build, null ); + void build(BuildBase build) { + build(build, null); } - void build( BuildBase build, Build b ) { - if ( build != null ) { - plugins( build.getPlugins() ); - if ( build.getDefaultGoal() != null || - build.getDirectory() != null || - ( b != null && ( - b.getOutputDirectory() != null || - b.getTestOutputDirectory() != null || - b.getSourceDirectory() != null || - b.getTestSourceDirectory() != null ) ) || - build.getFinalName() != null || - build.getResources().size() > 0 || - build.getTestResources().size() > 0 ){ + void build(BuildBase build, Build b) { + if (build != null) { + plugins(build.getPlugins()); + if (build.getDefaultGoal() != null + || build.getDirectory() != null + || (b != null + && (b.getOutputDirectory() != null + || b.getTestOutputDirectory() != null + || b.getSourceDirectory() != null + || b.getTestSourceDirectory() != null)) + || build.getFinalName() != null + || build.getResources().size() > 0 + || build.getTestResources().size() > 0) { p.println(); - p.printStartBlock( "build" ); - if (build.getDefaultGoal() != null ) - { - p.println( "default_goal", build.getDefaultGoal() ); + p.printStartBlock("build"); + if (build.getDefaultGoal() != null) { + p.println("default_goal", build.getDefaultGoal()); } - if (build.getDirectory() != null ) - { - p.println( "directory", build.getDirectory() ); + if (build.getDirectory() != null) { + p.println("directory", build.getDirectory()); } - if ( b != null ) - { - if (b.getOutputDirectory() != null ) - { - p.println( "output_directory", b.getOutputDirectory() ); + if (b != null) { + if (b.getOutputDirectory() != null) { + p.println("output_directory", b.getOutputDirectory()); } - if (b.getTestOutputDirectory() != null ) - { - p.println( "test_output_directory", b.getTestOutputDirectory() ); + if (b.getTestOutputDirectory() != null) { + p.println("test_output_directory", b.getTestOutputDirectory()); } - if (b.getSourceDirectory() != null ) - { - p.println( "source_directory", b.getSourceDirectory() ); + if (b.getSourceDirectory() != null) { + p.println("source_directory", b.getSourceDirectory()); } - if (b.getTestSourceDirectory() != null ) - { - p.println( "test_source_directory", b.getTestSourceDirectory() ); + if (b.getTestSourceDirectory() != null) { + p.println("test_source_directory", b.getTestSourceDirectory()); } } - if ( build.getFinalName() != null ) - { - p.println( "final_name", build.getFinalName() ); + if (build.getFinalName() != null) { + p.println("final_name", build.getFinalName()); } - resource( "resource", build.getResources() ); - resource( "test_resource", build.getTestResources() ); + resource("resource", build.getResources()); + resource("test_resource", build.getTestResources()); p.printEndBlock(); p.println(); @@ -456,29 +420,28 @@ void build( BuildBase build, Build b ) { } } - private void resource( String name, List resources ) - { - for( Resource resource: resources ) - { + private void resource(String name, List resources) { + for (Resource resource : resources) { p.println(); - p.printStartBlock( name ); - p.println( "directory", resource.getDirectory() ); - p.println( "includes", toArray( resource.getIncludes() ) ); - p.println( "excludes", toArray( resource.getExcludes() ) ); - p.println( "target_path", resource.getTargetPath() ); + p.printStartBlock(name); + p.println("directory", resource.getDirectory()); + p.println("includes", toArray(resource.getIncludes())); + p.println("excludes", toArray(resource.getExcludes())); + p.println("target_path", resource.getTargetPath()); // default is false, i.e. null indicates default - p.println( "filtering", resource.isFiltering() ? "true" : null ); + p.println("filtering", resource.isFiltering() ? "true" : null); p.printEndBlock(); } } void managements(DependencyManagement dependencyManagement, BuildBase build) { - if ((dependencyManagement != null && !dependencyManagement - .getDependencies().isEmpty()) - || (build != null && build.getPluginManagement() != null && !build - .getPluginManagement().getPlugins().isEmpty())) { + if ((dependencyManagement != null + && !dependencyManagement.getDependencies().isEmpty()) + || (build != null + && build.getPluginManagement() != null + && !build.getPluginManagement().getPlugins().isEmpty())) { p.printStartBlock("overrides"); - if ( dependencyManagement != null ){ + if (dependencyManagement != null) { dependencies(dependencyManagement.getDependencies()); } if (build != null && build.getPluginManagement() != null) { @@ -499,24 +462,20 @@ void id(Model model) { if (version == null && model.getParent() != null) { version = model.getParent().getVersion(); } - p.println("id", groupId + ":" + model.getArtifactId() + ":" - + version); + p.println("id", groupId + ":" + model.getArtifactId() + ":" + version); } void parent(Parent parent) { if (parent != null) { - p.print("inherit", parent.getGroupId() + ":" - + parent.getArtifactId() + ":" + parent.getVersion()); - if (parent.getRelativePath() != null ) { - if ( parent.getRelativePath().equals( "../pom.xml" ) ) { - //p.append( ", '" ).append( "../pom.rb" ).append( "'" ); + p.print("inherit", parent.getGroupId() + ":" + parent.getArtifactId() + ":" + parent.getVersion()); + if (parent.getRelativePath() != null) { + if (parent.getRelativePath().equals("../pom.xml")) { + // p.append( ", '" ).append( "../pom.rb" ).append( "'" ); p.println(); - } - else { + } else { p.append(", '" + parent.getRelativePath() + "'").println(); } - } - else { + } else { p.println(); } } @@ -526,25 +485,24 @@ void properties(Properties properties) { if (!properties.isEmpty()) { List keys = new ArrayList(properties.keySet()); String prefix = "properties( "; - String indent = prefix.replaceAll( ".", " " ); - p.print( prefix ); + String indent = prefix.replaceAll(".", " "); + p.print(prefix); for (int i = 0; i < keys.size(); i++) { Object key = keys.get(i); if (i != 0) { - p.print( indent ); + p.print(indent); } - Object value = properties.get( key ); + Object value = properties.get(key); if (value != null) { if (value instanceof String) { - p.append( "'" + key + "' => '" + value + "'" ); + p.append("'" + key + "' => '" + value + "'"); } else { - p.append( "'" + key + "' => " + value ); + p.append("'" + key + "' => " + value); } if (i + 1 != keys.size()) { - p.append( "," ); - } - else { - p.append( " )" ); + p.append(","); + } else { + p.append(" )"); } p.println(); } @@ -571,7 +529,7 @@ void modules(List modules) { } } - void dependencies( List deps ) { + void dependencies(List deps) { for (int i = 0; i < deps.size(); i++) { Dependency d = deps.get(i); Map options = new HashMap(); @@ -587,76 +545,72 @@ void dependencies( List deps ) { gav = d.getGroupId() + ":" + d.getArtifactId(); } if (d.getClassifier() != null) { - if (d.getVersion() == null ){ - options.put( "classifier", d.getClassifier() ); - } - else { + if (d.getVersion() == null) { + options.put("classifier", d.getClassifier()); + } else { gav += ":" + d.getClassifier(); } } - if ( d.getScope() != null ){ - options.put( "scope", d.getScope() ); + if (d.getScope() != null) { + options.put("scope", d.getScope()); } - if ( d.getOptional() != null ){ - options.put( "optional", d.isOptional() ); + if (d.getOptional() != null) { + options.put("optional", d.isOptional()); } - if ( d.getExclusions().size() == 1 ) { - Exclusion e = d.getExclusions().get( 0 ); + if (d.getExclusions().size() == 1) { + Exclusion e = d.getExclusions().get(0); String ga = e.getGroupId() + ":" + e.getArtifactId(); - options.put( "exclusions", ga ); - } - else if ( d.getExclusions().size() > 1 ) { - List exclusions = new ArrayList( d.getExclusions().size() ); + options.put("exclusions", ga); + } else if (d.getExclusions().size() > 1) { + List exclusions = + new ArrayList(d.getExclusions().size()); for (Exclusion e : d.getExclusions()) { String ga = e.getGroupId() + ":" + e.getArtifactId(); - exclusions.add( ga ); + exclusions.add(ga); } - options.put( "exclusions", exclusions ); + options.put("exclusions", exclusions); } final String prefix = options.size() == 0 ? d.getType() + " " : d.getType() + "( "; - final String indent = prefix.replaceAll( ".", " " ); + final String indent = prefix.replaceAll(".", " "); - p.print( prefix ); - p.append( "'" ).append( gav ).append( "'" ); - if ( options.size() > 0 ) { - for( Map.Entry item : options.entrySet() ){ - p.append( "," ); + p.print(prefix); + p.append("'").append(gav).append("'"); + if (options.size() > 0) { + for (Map.Entry item : options.entrySet()) { + p.append(","); p.println(); - p.print( indent ); - p.append( ":" ); - p.append( item.getKey() ); - p.append( " => "); - if ( item.getValue() instanceof String ){ - p.append( "'" ); - p.append( item.getValue().toString() ); - p.append( "'" ); - } - else if ( item.getValue() instanceof Boolean ){ - p.append( item.getValue().toString() ); - } - else { + p.print(indent); + p.append(":"); + p.append(item.getKey()); + p.append(" => "); + if (item.getValue() instanceof String) { + p.append("'"); + p.append(item.getValue().toString()); + p.append("'"); + } else if (item.getValue() instanceof Boolean) { + p.append(item.getValue().toString()); + } else { @SuppressWarnings("unchecked") List list = (List) item.getValue(); boolean first = true; - p.append( "[ " ); - for( String ex: list ){ - if ( first ) { + p.append("[ "); + for (String ex : list) { + if (first) { first = false; - } - else { - p.append( "," ); + } else { + p.append(","); p.println(); - p.print( indent ); - p.append( " " ); + p.print(indent); + p.append(" "); } - p.append( "'" ); - p.append( ex ); - p.append( "'" ); + p.append("'"); + p.append(ex); + p.append("'"); } - p.append( " ]" ); + p.append(" ]"); } } - p.append( " )"); + p.append(" )"); } p.println(); } @@ -669,17 +623,16 @@ void plugins(List plugins) { for (int i = 0; i < plugins.size(); i++) { T container = plugins.get(i); String prefix = container.getConfiguration() == null ? "plugin " : "plugin( "; - String indent = prefix.replaceAll( ".", " " ); - p.print( prefix); + String indent = prefix.replaceAll(".", " "); + p.print(prefix); Plugin plugin = null; ReportPlugin rplugin = null; - if ( container instanceof Plugin ){ + if (container instanceof Plugin) { plugin = (Plugin) container; - pluginProlog( plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion() ); - } - else { + pluginProlog(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion()); + } else { rplugin = (ReportPlugin) container; - pluginProlog( rplugin.getGroupId(), rplugin.getArtifactId(), rplugin.getVersion() ); + pluginProlog(rplugin.getGroupId(), rplugin.getArtifactId(), rplugin.getVersion()); } if (!container.isInherited()) { p.append(", "); @@ -689,32 +642,37 @@ void plugins(List plugins) { p.append(", "); p.appendName("extensions").append(" => true"); } - p.printConfiguration( indent, container.getConfiguration() ); - if ( plugin != null && - ( !plugin.getExecutions().isEmpty() || !plugin.getDependencies().isEmpty() ) ){ + p.printConfiguration(indent, container.getConfiguration()); + if (plugin != null + && (!plugin.getExecutions().isEmpty() + || !plugin.getDependencies().isEmpty())) { p.printStartBlock(); - dependencies( plugin.getDependencies() ); - - for(PluginExecution exec : plugin.getExecutions()){ - p.printWithOptions( "execute_goals", - options( "id", "default".equals( exec.getId() ) ? null : exec.getId(), - "inherited", exec.isInherited() ? null : "false" , - "phase", exec.getPhase() ), - exec.getConfiguration(), - toArray( exec.getGoals() ) ); + dependencies(plugin.getDependencies()); + + for (PluginExecution exec : plugin.getExecutions()) { + p.printWithOptions( + "execute_goals", + options( + "id", "default".equals(exec.getId()) ? null : exec.getId(), + "inherited", exec.isInherited() ? null : "false", + "phase", exec.getPhase()), + exec.getConfiguration(), + toArray(exec.getGoals())); } p.printEndBlock(); } - if ( rplugin != null && !rplugin.getReportSets().isEmpty() ) { + if (rplugin != null && !rplugin.getReportSets().isEmpty()) { p.printStartBlock(); - for( ReportSet set : rplugin.getReportSets() ){ - p.printWithOptions( "report_set", - options( "id", "default".equals( set.getId() ) ? null : set.getId(), - "inherited", set.isInherited() ? null : "false" ), - set.getConfiguration(), - toArray( set.getReports() ) ); + for (ReportSet set : rplugin.getReportSets()) { + p.printWithOptions( + "report_set", + options( + "id", "default".equals(set.getId()) ? null : set.getId(), + "inherited", set.isInherited() ? null : "false"), + set.getConfiguration(), + toArray(set.getReports())); } p.printEndBlock(); } @@ -722,33 +680,31 @@ void plugins(List plugins) { } } - private String[] toArray( List list ) { - return list.toArray( new String[ list.size() ] ); + private String[] toArray(List list) { + return list.toArray(new String[list.size()]); } - private Repository[] toRepositoryArray( List list ) { - return list.toArray( new Repository[ list.size() ] ); + private Repository[] toRepositoryArray(List list) { + return list.toArray(new Repository[list.size()]); } - private void pluginProlog( String groupId, String artifactId, String version ) { - if( "org.apache.maven.plugins".equals( groupId ) && artifactId.startsWith( "maven-") ) { - String name = artifactId.replaceAll( "maven-|-plugin", ""); - if ( name.contains( "-" ) ){ - p.append( ":'" ).append( name ).append( "'" ); - } - else { - p.append( ":" ).append( name ); + private void pluginProlog(String groupId, String artifactId, String version) { + if ("org.apache.maven.plugins".equals(groupId) && artifactId.startsWith("maven-")) { + String name = artifactId.replaceAll("maven-|-plugin", ""); + if (name.contains("-")) { + p.append(":'").append(name).append("'"); + } else { + p.append(":").append(name); } - if ( version != null ){ - p.append( ", '").append( version ).append( "'" ); + if (version != null) { + p.append(", '").append(version).append("'"); } - } - else { - p.append( "'").append( groupId ).append( ":" ).append( artifactId ); - if ( version != null ){ - p.append( ":" ).append( version ); + } else { + p.append("'").append(groupId).append(":").append(artifactId); + if (version != null) { + p.append(":").append(version); } - p.append( "'" ); + p.append("'"); } } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyParser.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyParser.java index 4a03240c..d00dc79a 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyParser.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyParser.java @@ -8,15 +8,11 @@ package org.sonatype.maven.polyglot.ruby; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.util.Map; - import org.apache.maven.model.Model; import org.jruby.embed.IsolatedScriptingContainer; import org.jruby.embed.PathType; - import org.sonatype.maven.polyglot.execute.ExecuteManager; import org.sonatype.maven.polyglot.ruby.execute.RubyExecuteTaskFactory; @@ -35,26 +31,23 @@ public class RubyParser { private final RubyExecuteTaskFactory factory; - public RubyParser( ExecuteManager executeManager ) throws IOException - { + public RubyParser(ExecuteManager executeManager) throws IOException { this.executeManager = executeManager; this.jruby = new IsolatedScriptingContainer(); - this.parser = jruby.runScriptlet( PathType.CLASSPATH, "parser.rb" ); - this.factory = new RubyExecuteTaskFactory( jruby ); + this.parser = jruby.runScriptlet(PathType.CLASSPATH, "parser.rb"); + this.factory = new RubyExecuteTaskFactory(jruby); } // synchronize it since it is not clear how threadsafe everything is - public synchronized Model parse( String ruby, File source, Map options ) - { - Model model = this.jruby.callMethod( this.parser, - "parse", - new Object[] { ruby, - this.factory, - source != null ? source.getAbsolutePath() : null }, - Model.class ); - model.setPomFile( source ); - executeManager.register( model, this.factory.getExecuteTasks() ); - executeManager.install( model, options ); + public synchronized Model parse(String ruby, File source, Map options) { + Model model = this.jruby.callMethod( + this.parser, + "parse", + new Object[] {ruby, this.factory, source != null ? source.getAbsolutePath() : null}, + Model.class); + model.setPomFile(source); + executeManager.register(model, this.factory.getExecuteTasks()); + executeManager.install(model, options); return model; } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyPrintWriter.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyPrintWriter.java index 10c5c7b4..d5258f69 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyPrintWriter.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/RubyPrintWriter.java @@ -13,7 +13,6 @@ import java.io.PrintWriter; import java.io.Writer; import java.util.Map; - import org.codehaus.plexus.util.xml.Xpp3Dom; import org.sonatype.maven.polyglot.ruby.ConfigVisitor.Config; import org.sonatype.maven.polyglot.ruby.ConfigVisitor.ListItem; @@ -42,10 +41,10 @@ public void print(String value) { } void print(String name, String... values) { - if ( values.length == 1 && values[0] == null) { + if (values.length == 1 && values[0] == null) { return; } - append( current ).append( name ).append( " " ); + append(current).append(name).append(" "); boolean first = true; for (String value : values) { if (value != null) { @@ -54,237 +53,192 @@ void print(String name, String... values) { } else { append(", "); } - if(value.startsWith(":")){ + if (value.startsWith(":")) { append(value); - } - else { - append("'").append( escape( value ) ).append("'"); + } else { + append("'").append(escape(value)).append("'"); } } } } - private String escape( String value ) - { - return value.replaceAll( "([^\\\\])'", "$1\\\\'" ); + private String escape(String value) { + return value.replaceAll("([^\\\\])'", "$1\\\\'"); } - + public void println(String name) { print(name); println(); } void println(String name, String... values) { - if ( values.length == 1 && values[0] == null ) - { + if (values.length == 1 && values[0] == null) { return; } - print( name, values ); + print(name, values); println(); } - void printWithOptions( String prefix, Map options, String... args ){ - printWithOptions( prefix, options, null, args ); + void printWithOptions(String prefix, Map options, String... args) { + printWithOptions(prefix, options, null, args); } - void printWithOptions( String prefix, Map options, boolean newLine, String... args ){ - printWithOptions( prefix, options, null, newLine, args ); + void printWithOptions(String prefix, Map options, boolean newLine, String... args) { + printWithOptions(prefix, options, null, newLine, args); } - void printWithOptions( String prefix, Map options, Object config, String... args) - { - printWithOptions( prefix, options, config, true, args ); + void printWithOptions(String prefix, Map options, Object config, String... args) { + printWithOptions(prefix, options, config, true, args); } - void printWithOptions( String prefix, Map options, Object config, boolean newLine, String... args) - { - if ( !options.isEmpty() || config != null ) - { + void printWithOptions(String prefix, Map options, Object config, boolean newLine, String... args) { + if (!options.isEmpty() || config != null) { prefix += "("; - print( prefix, args ); - String indent = prefix.replaceAll( ".", " " ) + ' '; + print(prefix, args); + String indent = prefix.replaceAll(".", " ") + ' '; boolean first = args.length == 0; - for( Map.Entry item: options.entrySet() ) - { - if ( first ) - { + for (Map.Entry item : options.entrySet()) { + if (first) { first = false; - } - else - { + } else { append(",").println(); - print( indent ); + print(indent); } - appendName( item.getKey() ).append( " => " ); - if ( item.getValue() instanceof String ) - { - append( "'" ).append( escape( item.getValue().toString() ) ).append( "'" ); - } - else { - append( item.getValue().toString() ); + appendName(item.getKey()).append(" => "); + if (item.getValue() instanceof String) { + append("'").append(escape(item.getValue().toString())).append("'"); + } else { + append(item.getValue().toString()); } } - if ( config != null ) - { - printConfiguration( indent, config ); - if (newLine ) - { + if (config != null) { + printConfiguration(indent, config); + if (newLine) { println(); } - } - else - { - append( " )" ); - if (newLine ) - { + } else { + append(" )"); + if (newLine) { println(); } } - } - else - { - println( prefix, args ); + } else { + println(prefix, args); } } - void printConfiguration( String indent, Object config ) { - if (config != null ){ + void printConfiguration(String indent, Object config) { + if (config != null) { Xpp3Dom configuration = (Xpp3Dom) config; if (configuration.getChildCount() != 0) { append(","); println(); ConfigVisitor visitor = new ConfigVisitor(); - visitor.visit( new Node( configuration ) ); - printHashConfig( indent, visitor.config.map ); + visitor.visit(new Node(configuration)); + printHashConfig(indent, visitor.config.map); } - append( " )"); + append(" )"); } } void printHashConfig(String indent, Map base) { - printHashConfig( indent, base, false ); + printHashConfig(indent, base, false); } - RubyPrintWriter appendName( String name ) - { - if ( name.matches( "^[a-zA-Z_]*$" ) ) - { - append( ":" ).append( name ); - } - else - { - append( "'" ).append( escape( name ) ).append( "'" ); + RubyPrintWriter appendName(String name) { + if (name.matches("^[a-zA-Z_]*$")) { + append(":").append(name); + } else { + append("'").append(escape(name)).append("'"); } return this; } - void printHashConfig(String indent, Map base, boolean skipFirst ) { + void printHashConfig(String indent, Map base, boolean skipFirst) { boolean first = true; - for( Map.Entry entry: base.entrySet() ) - { - if ( first ) - { + for (Map.Entry entry : base.entrySet()) { + if (first) { first = false; - if ( !skipFirst ) - { - print( indent ); + if (!skipFirst) { + print(indent); } - } - else - { - append( "," ).println(); - print( indent ); + } else { + append(",").println(); + print(indent); } Config config = entry.getValue(); - switch ( config.type ) - { - case SINGLE: - append( "'" ).append( entry.getKey() ).append( "' => " ); - if ( config.value != null ) - { - append( " '" ).append( escape( config.value ) ).append( "'" ); - } - else - { - append( "nil" ); - } - break; - case MULTI: - append( "'" ).append( entry.getKey() ).append( "' => [" ); - String ind = indent + " " + entry.getKey().replaceAll( ".", " " ); - int count = config.stringList.size(); - for (int j = 0; j < count; ) - { - String c = config.stringList.get(j); - if ( c != null ) - { - append( " '" ).append( escape( c ) ).append( "'" ); - } - else - { - append( "nil" ); - } - if( ++j < count ) - { - append( "," ); - println(); - print( ind ); - } - } - append( " ]" ); - break; - case MIXED: - append( "'" ).append( entry.getKey() ).append( "' => [" ); - ind = indent + " " + entry.getKey().replaceAll( ".", " " ); - count = config.list.size(); - for (int j = 0; j < count; ) - { - ListItem c = config.list.get(j); - if ( c.isXml() ) - { - append( " xml( '" ).append( escape( c.xml ) ).append( "' )" ); + switch (config.type) { + case SINGLE: + append("'").append(entry.getKey()).append("' => "); + if (config.value != null) { + append(" '").append(escape(config.value)).append("'"); + } else { + append("nil"); } - else - { - append( " '" ).append( escape( c.value ) ).append( "'" ); + break; + case MULTI: + append("'").append(entry.getKey()).append("' => ["); + String ind = indent + " " + entry.getKey().replaceAll(".", " "); + int count = config.stringList.size(); + for (int j = 0; j < count; ) { + String c = config.stringList.get(j); + if (c != null) { + append(" '").append(escape(c)).append("'"); + } else { + append("nil"); + } + if (++j < count) { + append(","); + println(); + print(ind); + } } - if( ++j < count ) - { - append( "," ); - println(); - print( ind ); + append(" ]"); + break; + case MIXED: + append("'").append(entry.getKey()).append("' => ["); + ind = indent + " " + entry.getKey().replaceAll(".", " "); + count = config.list.size(); + for (int j = 0; j < count; ) { + ListItem c = config.list.get(j); + if (c.isXml()) { + append(" xml( '").append(escape(c.xml)).append("' )"); + } else { + append(" '").append(escape(c.value)).append("'"); + } + if (++j < count) { + append(","); + println(); + print(ind); + } } - } - append( " ]" ); - break; - case MAPS: - append( "'" ).append( entry.getKey() ).append( "' => [" ); - ind = indent + " " + entry.getKey().replaceAll( ".", " " ); - count = config.mapList.size(); - for (int j = 0; j < count; ) - { - Map c = config.mapList.get(j); - append( " { " ); - printHashConfig( " " + ind + INDENT, c, true ); - append( " }" ); - if( ++j < count ) - { - append( "," ); - println(); - print( ind ); + append(" ]"); + break; + case MAPS: + append("'").append(entry.getKey()).append("' => ["); + ind = indent + " " + entry.getKey().replaceAll(".", " "); + count = config.mapList.size(); + for (int j = 0; j < count; ) { + Map c = config.mapList.get(j); + append(" { "); + printHashConfig(" " + ind + INDENT, c, true); + append(" }"); + if (++j < count) { + append(","); + println(); + print(ind); + } } - } - append( " ]" ); - break; - case MAP: - append( "'" ).append( entry.getKey() ).append( "' => {" ).println(); - printHashConfig( indent + INDENT, - entry.getValue().map, false ); - println(); - print( indent ); - append( "}" ); - break; - default: + append(" ]"); + break; + case MAP: + append("'").append(entry.getKey()).append("' => {").println(); + printHashConfig(indent + INDENT, entry.getValue().map, false); + println(); + print(indent); + append("}"); + break; + default: } } } @@ -295,17 +249,14 @@ void printStartBlock(String name) { } void printStartBlock(String name, String... values) { - printStartBlock( name, null, values ); + printStartBlock(name, null, values); } void printStartBlock(String name, Map options, String... values) { - if ( options != null ) - { - printWithOptions( name, options, false, values ); - } - else - { - print( name, values ); + if (options != null) { + printWithOptions(name, options, false, values); + } else { + print(name, values); } printStartBlock(); } @@ -321,5 +272,4 @@ void printEndBlock() { append(current).append("end"); println(); } - -} \ No newline at end of file +} diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SetupClassRealm.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SetupClassRealm.java index a06bb3ca..4736ac64 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SetupClassRealm.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SetupClassRealm.java @@ -7,17 +7,15 @@ */ package org.sonatype.maven.polyglot.ruby; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.File; import java.io.FileFilter; import java.net.MalformedURLException; import java.net.URL; import java.util.Set; import java.util.TreeSet; - +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; @@ -35,115 +33,113 @@ public class SetupClassRealm { @Inject protected LegacySupport legacySupport; + private static final String JRUBY_HOME = "polyglot.jruby.home"; - public void setupArtifact( String gav, ClassRealm realm) throws MalformedURLException - { - try - { + public void setupArtifact(String gav, ClassRealm realm) throws MalformedURLException { + try { // test if class is already there - realm.loadClass( "org.jruby.embed.ScriptingContainer" ); - } - catch (ClassNotFoundException e) - { - + realm.loadClass("org.jruby.embed.ScriptingContainer"); + } catch (ClassNotFoundException e) { + // add the provided jars for the given artifact - setup( gav, realm ); + setup(gav, realm); } } - - private void setup( String gav, ClassRealm realm ) throws MalformedURLException - { - // looking into another JRUBY_HOME is for jruby itself only to allow - // jruby build to use itself for bootstraping + + private void setup(String gav, ClassRealm realm) throws MalformedURLException { + // looking into another JRUBY_HOME is for jruby itself only to allow + // jruby build to use itself for bootstraping // see if we have shall use jruby from somewhere else - String jrubyHome = System.getenv( "POLYGLOT_JRUBY_HOME" ); - if ( jrubyHome == null ){ - jrubyHome = System.getProperty( JRUBY_HOME ); + String jrubyHome = System.getenv("POLYGLOT_JRUBY_HOME"); + if (jrubyHome == null) { + jrubyHome = System.getProperty(JRUBY_HOME); } - if ( jrubyHome == null ){ - jrubyHome = legacySupport.getSession().getRequest().getUserProperties().getProperty( JRUBY_HOME ); + if (jrubyHome == null) { + jrubyHome = + legacySupport.getSession().getRequest().getUserProperties().getProperty(JRUBY_HOME); } - if ( jrubyHome == null ){ - jrubyHome = legacySupport.getSession().getRequest().getSystemProperties().getProperty( JRUBY_HOME ); + if (jrubyHome == null) { + jrubyHome = legacySupport + .getSession() + .getRequest() + .getSystemProperties() + .getProperty(JRUBY_HOME); } - if ( jrubyHome == null && legacySupport.getSession().getCurrentProject() != null ){ - jrubyHome = legacySupport.getSession().getCurrentProject().getProperties().getProperty( JRUBY_HOME ); + if (jrubyHome == null && legacySupport.getSession().getCurrentProject() != null) { + jrubyHome = legacySupport + .getSession() + .getCurrentProject() + .getProperties() + .getProperty(JRUBY_HOME); } - if (jrubyHome != null ){ - - setupFromJrubyHome( jrubyHome, realm ); - - } - else { - + if (jrubyHome != null) { + + setupFromJrubyHome(jrubyHome, realm); + + } else { + // use jruby from an artifact - doSetupArtifact( gav, realm ); + doSetupArtifact(gav, realm); } } - protected void setupFromJrubyHome( String jrubyHome, ClassRealm realm) - throws MalformedURLException - { - System.setProperty( JRUBY_HOME, jrubyHome ); + protected void setupFromJrubyHome(String jrubyHome, ClassRealm realm) throws MalformedURLException { + System.setProperty(JRUBY_HOME, jrubyHome); - File[] jars = new File( jrubyHome, "lib" ).listFiles( new FileFilter() { + File[] jars = new File(jrubyHome, "lib").listFiles(new FileFilter() { - public boolean accept( File pathname ) - { - return pathname.getName().endsWith( ".jar" ); + public boolean accept(File pathname) { + return pathname.getName().endsWith(".jar"); } - } ); - if ( jars == null || jars.length == 0 ){ - throw new RuntimeException( "found jruby-home variable but no jruby.jar: " + jrubyHome ); + }); + if (jars == null || jars.length == 0) { + throw new RuntimeException("found jruby-home variable but no jruby.jar: " + jrubyHome); } - for( File jar : jars ){ - realm.addURL( jar.toURI().toURL() ); + for (File jar : jars) { + realm.addURL(jar.toURI().toURL()); } } - public void doSetupArtifact( String gav, ClassRealm realm ) - throws MalformedURLException - { - String[] parts = gav.split( ":" ); - Artifact root = system.createArtifact( parts[ 0 ], parts[ 1 ], parts[ 2 ], "pom" ); + public void doSetupArtifact(String gav, ClassRealm realm) throws MalformedURLException { + String[] parts = gav.split(":"); + Artifact root = system.createArtifact(parts[0], parts[1], parts[2], "pom"); ArtifactResolutionResult result; - result = system.resolve( new ArtifactResolutionRequest() - .setArtifact( root ) - .setCollectionFilter( new ArtifactFilter() { - - public boolean include( Artifact artifact ) - { - return !"polyglot-common".equals( artifact.getArtifactId() ) && - !"test".equals( artifact.getScope() ); - } - } ) - .setResolveRoot( true ) - .setForceUpdate( true ) - .setOffline( legacySupport.getSession().getRequest().isOffline() ) - .setMirrors( legacySupport.getSession().getRequest().getMirrors() ) - .setProxies( legacySupport.getSession().getRequest().getProxies() ) - .setServers( legacySupport.getSession().getRequest().getServers()) - .setLocalRepository( legacySupport.getSession().getRequest().getLocalRepository() ) - .setRemoteRepositories( legacySupport.getSession().getRequest().getRemoteRepositories() ) - .setResolveTransitively( true ) ); + result = system.resolve(new ArtifactResolutionRequest() + .setArtifact(root) + .setCollectionFilter(new ArtifactFilter() { + + public boolean include(Artifact artifact) { + return !"polyglot-common".equals(artifact.getArtifactId()) + && !"test".equals(artifact.getScope()); + } + }) + .setResolveRoot(true) + .setForceUpdate(true) + .setOffline(legacySupport.getSession().getRequest().isOffline()) + .setMirrors(legacySupport.getSession().getRequest().getMirrors()) + .setProxies(legacySupport.getSession().getRequest().getProxies()) + .setServers(legacySupport.getSession().getRequest().getServers()) + .setLocalRepository(legacySupport.getSession().getRequest().getLocalRepository()) + .setRemoteRepositories(legacySupport.getSession().getRequest().getRemoteRepositories()) + .setResolveTransitively(true)); // get searchable list of existing urls Set urls = new TreeSet(); - for( URL url : realm.getURLs() ){ - urls.add( url.toString() ); + for (URL url : realm.getURLs()) { + urls.add(url.toString()); } - for( Artifact a: result.getArtifacts() ){ - if ( "jar".equals( a.getType() ) && a.getFile() != null ){ + for (Artifact a : result.getArtifacts()) { + if ("jar".equals(a.getType()) && a.getFile() != null) { URL url = a.getFile().toURI().toURL(); // add only if not already exist - if ( !urls.contains( url.toString() ) ){ - realm.addURL( a.getFile().toURI().toURL() ); + if (!urls.contains(url.toString())) { + realm.addURL(a.getFile().toURI().toURL()); } } - } + } } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SortedProperties.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SortedProperties.java index 8d813a8f..35cdcce0 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SortedProperties.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/SortedProperties.java @@ -11,18 +11,17 @@ public class SortedProperties extends Properties { - public SortedProperties(Properties props) { - super(props); - } + public SortedProperties(Properties props) { + super(props); + } - @Override - public synchronized Enumeration keys() { - return Collections.enumeration(new TreeSet(keySet())); - } - - @Override - public synchronized Set keySet() { - return new TreeSet(super.keySet()); - } + @Override + public synchronized Enumeration keys() { + return Collections.enumeration(new TreeSet(keySet())); + } + @Override + public synchronized Set keySet() { + return new TreeSet(super.keySet()); + } } diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTask.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTask.java index ae0452ba..ccd3df41 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTask.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTask.java @@ -42,10 +42,10 @@ public void execute(final ExecuteContext context) throws Exception { @Override public String toString() { - return getClass().getSimpleName() + "{" + - "id='" + getId() + '\'' + - ", phase='" + getPhase() + '\'' + - ( getProfileId() == null ? "" : ", profile='" + getProfileId() + '\'' ) + - "," + script + "}"; + return getClass().getSimpleName() + "{" + "id='" + + getId() + '\'' + ", phase='" + + getPhase() + '\'' + (getProfileId() == null ? "" : ", profile='" + getProfileId() + '\'') + + "," + + script + "}"; } -} \ No newline at end of file +} diff --git a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTaskFactory.java b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTaskFactory.java index 8b504f9d..1a6fa968 100644 --- a/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTaskFactory.java +++ b/polyglot-ruby/src/main/java/org/sonatype/maven/polyglot/ruby/execute/RubyExecuteTaskFactory.java @@ -12,7 +12,6 @@ import java.util.LinkedList; import java.util.List; - import org.jruby.embed.ScriptingContainer; import org.sonatype.maven.polyglot.execute.ExecuteTask; @@ -20,21 +19,21 @@ public class RubyExecuteTaskFactory { private ScriptingContainer jruby; private List tasks = new LinkedList(); - public RubyExecuteTaskFactory( ScriptingContainer jruby ) { + public RubyExecuteTaskFactory(ScriptingContainer jruby) { this.jruby = jruby; } - public void addExecuteTask( String id, String phase, String profileId, Object script ){ - RubyExecuteTask task = new RubyExecuteTask( jruby ); - task.setId( id ); - task.setPhase( phase ); - task.setProfileId( profileId ); - task.setScript( script ); + public void addExecuteTask(String id, String phase, String profileId, Object script) { + RubyExecuteTask task = new RubyExecuteTask(jruby); + task.setId(id); + task.setPhase(phase); + task.setProfileId(profileId); + task.setScript(script); - this.tasks.add( task ); + this.tasks.add(task); } - public List getExecuteTasks(){ + public List getExecuteTasks() { return tasks; } -} \ No newline at end of file +} diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/AbstractInjectedTestCase.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/AbstractInjectedTestCase.java index e1cc9c23..80407bb1 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/AbstractInjectedTestCase.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/AbstractInjectedTestCase.java @@ -18,10 +18,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.model.io.ModelWriter; @@ -45,54 +43,50 @@ public abstract class AbstractInjectedTestCase extends InjectedTestCase { @Named("${basedir}/src/test/poms") protected File poms; - private File specs; - private File specs() - { - if( specs == null) - { - File mavenTools = gems.listFiles( new FileFilter() { - @Override - public boolean accept( File f ) - { - return f.getName().startsWith( "maven-tools-" ); + private File specs; + + private File specs() { + if (specs == null) { + File mavenTools = gems.listFiles(new FileFilter() { + @Override + public boolean accept(File f) { + return f.getName().startsWith("maven-tools-"); } - } )[ 0 ]; - specs = new File( mavenTools, "spec" ); - } - return specs; + })[0]; + specs = new File(mavenTools, "spec"); + } + return specs; } - - protected void assertModels( String pomRuby, boolean debug ) throws Exception - { - - File dir = new File( specs(), pomRuby ).getParentFile(); - File pom = new File( dir, "pom.xml" ); - if( !pom.exists() ) - { - pom = new File( dir.getParentFile(), "pom.xml" ); + + protected void assertModels(String pomRuby, boolean debug) throws Exception { + + File dir = new File(specs(), pomRuby).getParentFile(); + File pom = new File(dir, "pom.xml"); + if (!pom.exists()) { + pom = new File(dir.getParentFile(), "pom.xml"); } - assertModels( pom, pomRuby, debug ); + assertModels(pom, pomRuby, debug); } - protected void assertModels( String pomXml, String pomRuby, boolean debug ) throws Exception { - assertModels( new File( specs(), pomXml ), pomRuby, debug ); + protected void assertModels(String pomXml, String pomRuby, boolean debug) throws Exception { + assertModels(new File(specs(), pomXml), pomRuby, debug); } - - protected void assertModels( File pom, String pomRuby, boolean debug ) throws Exception { + + protected void assertModels(File pom, String pomRuby, boolean debug) throws Exception { MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream( pom )); - + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + // // Read in the Ruby POM // RubyModelReader rubyModelReader = new RubyModelReader(); final PolyglotModelManager modelManager = new PolyglotModelManager() { { - mappings = new ArrayList(); + mappings = new ArrayList(); } }; - modelManager.addMapping( new RubyMapping() ); + modelManager.addMapping(new RubyMapping()); rubyModelReader.executeManager = new ExecuteManagerImpl() { { manager = modelManager; @@ -100,108 +94,102 @@ protected void assertModels( File pom, String pomRuby, boolean debug ) throws Ex }; rubyModelReader.setupManager = new SetupClassRealm(); - File pomRubyFile = new File( specs(), pomRuby ); - Reader reader = new FileReader( pomRubyFile ); + File pomRubyFile = new File(specs(), pomRuby); + Reader reader = new FileReader(pomRubyFile); Map options = new HashMap(); - options.put( ModelProcessor.SOURCE, pomRubyFile.toURI().toURL() ); - Model rubyModel = rubyModelReader.read( reader, options ); - - assertModels( xmlModel, rubyModel, debug ); + options.put(ModelProcessor.SOURCE, pomRubyFile.toURI().toURL()); + Model rubyModel = rubyModelReader.read(reader, options); + + assertModels(xmlModel, rubyModel, debug); } - protected void assertRoundtrip( String pomName, boolean debug ) throws Exception { - File pom = new File( poms, pomName ); - MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); - Model xmlModel = xmlModelReader.read(new FileInputStream( pom )); - - // - // Write out the Ruby POM - // - ModelWriter writer = new RubyModelWriter(); - StringWriter w = new StringWriter(); - writer.write( w, new HashMap(), xmlModel ); - - if ( debug ){ - // Let's take a look at see what's there - System.out.println(w.toString()); - } - - // - // Read in the Ruby POM - // - RubyModelReader rubyModelReader = new RubyModelReader(); + protected void assertRoundtrip(String pomName, boolean debug) throws Exception { + File pom = new File(poms, pomName); + MavenXpp3Reader xmlModelReader = new MavenXpp3Reader(); + Model xmlModel = xmlModelReader.read(new FileInputStream(pom)); + + // + // Write out the Ruby POM + // + ModelWriter writer = new RubyModelWriter(); + StringWriter w = new StringWriter(); + writer.write(w, new HashMap(), xmlModel); + + if (debug) { + // Let's take a look at see what's there + System.out.println(w.toString()); + } + + // + // Read in the Ruby POM + // + RubyModelReader rubyModelReader = new RubyModelReader(); final PolyglotModelManager modelManager = new PolyglotModelManager() { { - mappings = new ArrayList(); + mappings = new ArrayList(); } }; - modelManager.addMapping( new RubyMapping() ); + modelManager.addMapping(new RubyMapping()); rubyModelReader.executeManager = new ExecuteManagerImpl() { { manager = modelManager; } }; - rubyModelReader.setupManager = new SetupClassRealm(); - if ( debug ) - { - System.out.println(w.toString()); - } - StringReader reader = new StringReader( w.toString() ); - Model rubyModel = rubyModelReader.read( reader, new HashMap() ); - - // - // Test for fidelity - // - assertNotNull( rubyModel ); - - assertModels( xmlModel, rubyModel, debug ); - } - - private void assertModels( Model xmlModel, Model rubyModel, boolean debug ) - throws IOException - { - MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); - StringWriter ruby = new StringWriter(); - xmlWriter.write(ruby, rubyModel); - StringWriter xml = new StringWriter(); - xmlWriter.write(xml, xmlModel); - - if ( debug ) - { - // Let's take a look at see what's there - System.out.println(xml.toString()); - System.out.println(ruby.toString()); - } - - assertEquals( simplify( xml, debug ), simplify( ruby, debug ) ); - } - - private String simplify( StringWriter xml, boolean debug ) - { - String x = xml.toString() - // no whitespace - .replaceAll( "\\s", "") - // no process instructions - .replaceFirst("<\\?.*\\?>", "") - // properties have different ordering - .replaceAll(".*?", "") + rubyModelReader.setupManager = new SetupClassRealm(); + if (debug) { + System.out.println(w.toString()); + } + StringReader reader = new StringReader(w.toString()); + Model rubyModel = rubyModelReader.read(reader, new HashMap()); + + // + // Test for fidelity + // + assertNotNull(rubyModel); + + assertModels(xmlModel, rubyModel, debug); + } + + private void assertModels(Model xmlModel, Model rubyModel, boolean debug) throws IOException { + MavenXpp3Writer xmlWriter = new MavenXpp3Writer(); + StringWriter ruby = new StringWriter(); + xmlWriter.write(ruby, rubyModel); + StringWriter xml = new StringWriter(); + xmlWriter.write(xml, xmlModel); + + if (debug) { + // Let's take a look at see what's there + System.out.println(xml.toString()); + System.out.println(ruby.toString()); + } + + assertEquals(simplify(xml, debug), simplify(ruby, debug)); + } + + private String simplify(StringWriter xml, boolean debug) { + String x = xml.toString() + // no whitespace + .replaceAll("\\s", "") + // no process instructions + .replaceFirst("<\\?.*\\?>", "") + // properties have different ordering + .replaceAll(".*?", "") // allow old style plugin definition to match new one .replaceAll("\\$\\{tesla.version\\}", Constants.getVersion()) // the test cases still use the old groupIds and artifactIds .replaceAll("io.tesla.polyglot", "io.takari.polyglot") .replaceAll("tesla-polyglot", "polyglot") - // for the pom_with_execute test - // hardcoded version from maven-tools, could change more versions then + // for the pom_with_execute test + // hardcoded version from maven-tools, could change more versions then // the one from this plugin .replaceAll("[0-9]+(-SNAPSHOT)?", VERSION_PATTERN) - // fix absolute path for test_pom_from_jarfile - .replaceAll("..basedir./myfirst.jar", "uri:classloader:/myfirst.jar") + // fix absolute path for test_pom_from_jarfile + .replaceAll("..basedir./myfirst.jar", "uri:classloader:/myfirst.jar") // some of the configuration tags are empty - unify them .replaceAll(">", "/>"); - if ( debug ) - { - System.out.println(x); - } - return x; - } + if (debug) { + System.out.println(x); + } + return x; + } } diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelRoundtripTest.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelRoundtripTest.java index 17b5bae0..52affcae 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelRoundtripTest.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelRoundtripTest.java @@ -7,37 +7,35 @@ */ package org.sonatype.maven.polyglot.ruby; - // that is just a random collection of real world pom.xml !!! public class RubyModelRoundtripTest extends AbstractInjectedTestCase { - - public void testSitebricksPom() throws Exception { - assertRoundtrip( "sitebricks-pom.xml", false ); - } - - public void testSitebricksParentPom() throws Exception { - assertRoundtrip( "sitebricks-parent-pom.xml", false ); - } - - public void testJRubyCorePom() throws Exception { - assertRoundtrip( "jruby-core-pom.xml", false ); - } - - public void testJRubyParentPom() throws Exception { - assertRoundtrip( "jruby-parent-pom.xml", false ); - } - - public void testJRubyTestPom() throws Exception { - assertRoundtrip( "jruby-test-pom.xml", false ); - } - - public void testMavenParentPom() throws Exception { - assertRoundtrip( "maven-parent-pom.xml", false ); - } - - public void testJrubyOsgiTestPom() throws Exception { - assertRoundtrip( "jruby-osgi-test-pom.xml", false ); - } + public void testSitebricksPom() throws Exception { + assertRoundtrip("sitebricks-pom.xml", false); + } + + public void testSitebricksParentPom() throws Exception { + assertRoundtrip("sitebricks-parent-pom.xml", false); + } + + public void testJRubyCorePom() throws Exception { + assertRoundtrip("jruby-core-pom.xml", false); + } + + public void testJRubyParentPom() throws Exception { + assertRoundtrip("jruby-parent-pom.xml", false); + } + + public void testJRubyTestPom() throws Exception { + assertRoundtrip("jruby-test-pom.xml", false); + } + + public void testMavenParentPom() throws Exception { + assertRoundtrip("maven-parent-pom.xml", false); + } + + public void testJrubyOsgiTestPom() throws Exception { + assertRoundtrip("jruby-osgi-test-pom.xml", false); + } } diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelWithExecuteTasksTest.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelWithExecuteTasksTest.java index 15466f2c..7100a142 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelWithExecuteTasksTest.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyModelWithExecuteTasksTest.java @@ -15,10 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.inject.Named; - import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.plugin.logging.Log; @@ -46,13 +44,13 @@ public void testRubyModelWriter() throws Exception { final PolyglotModelManager modelManager = new PolyglotModelManager() { { mappings = new ArrayList(); - } - }; - modelManager.addMapping( new RubyMapping() ); - rubyModelReader.executeManager = new ExecuteManagerImpl() { - { - manager = modelManager; - } + } + }; + modelManager.addMapping(new RubyMapping()); + rubyModelReader.executeManager = new ExecuteManagerImpl() { + { + manager = modelManager; + } }; rubyModelReader.setupManager = new SetupClassRealm(); @@ -60,11 +58,10 @@ public void testRubyModelWriter() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); System.setOut(new PrintStream(bytes)); try { - + Map options = new HashMap(); - options.put( "ruby:4.0.0", true ); - final Model rubyModel = rubyModelReader.read( new FileReader(pom), - options ); + options.put("ruby:4.0.0", true); + final Model rubyModel = rubyModelReader.read(new FileReader(pom), options); // // Test for fidelity @@ -80,20 +77,19 @@ public MavenProject getProject() { public MavenSession getSession() { return null; } - + public File getBasedir() { return getProject().getBasedir(); } - + public Log getLog() { return null; } }; - List tasks = rubyModelReader.executeManager.getTasks( - rubyModel); + List tasks = rubyModelReader.executeManager.getTasks(rubyModel); tasks.get(0).execute(context); - assertEquals( "Execute Ruby Tasks", bytes.toString() ); + assertEquals("Execute Ruby Tasks", bytes.toString()); bytes.reset(); tasks.get(1).execute(context); @@ -101,9 +97,8 @@ public Log getLog() { bytes.reset(); tasks.get(2).execute(context); - assertEquals("#()); - // // Write out the xml POM // @@ -69,9 +65,8 @@ public void testRubyModelReaderXmlOutput() throws Exception { // Let's take a look at see what's there // System.out.println(w.toString()); - File pomXml = new File(poms, "pom.xml"); - assertEquals( w.toString(), IOUtil.toString( new FileInputStream( pomXml ) ) ); + assertEquals(w.toString(), IOUtil.toString(new FileInputStream(pomXml))); } public void testRubyModelWriter() throws Exception { @@ -87,12 +82,12 @@ public void testRubyModelWriter() throws Exception { writer.write(w, new HashMap(), xmlModel); // Let's take a look at see what's there - //System.out.println(w.toString()); + // System.out.println(w.toString()); - assertRubyModel( w.toString() ); + assertRubyModel(w.toString()); } - private void assertRubyModel( String rubyPom ) throws IOException { + private void assertRubyModel(String rubyPom) throws IOException { // // Read in the Ruby POM @@ -101,9 +96,8 @@ private void assertRubyModel( String rubyPom ) throws IOException { rubyModelReader.executeManager = new ExecuteManagerImpl(); rubyModelReader.setupManager = new SetupClassRealm(); - StringReader r = new StringReader( rubyPom ); - Model rubyModel = rubyModelReader - .read(r, new HashMap()); + StringReader r = new StringReader(rubyPom); + Model rubyModel = rubyModelReader.read(r, new HashMap()); // // Test for fidelity // @@ -120,9 +114,9 @@ void testMavenModelForCompleteness(Model model) { // // gav // - assertEquals("org.apache.maven:maven:3.0.4-SNAPSHOT", model - .getGroupId() - + ":" + model.getArtifactId() + ":" + model.getVersion()); + assertEquals( + "org.apache.maven:maven:3.0.4-SNAPSHOT", + model.getGroupId() + ":" + model.getArtifactId() + ":" + model.getVersion()); // // packaging // @@ -140,123 +134,114 @@ void testMavenModelForCompleteness(Model model) { // // parent // - assertEquals("org.eclipse.tesla:tesla:3", model.getParent() - .getGroupId() - + ":" - + model.getParent().getArtifactId() - + ":" - + model.getParent().getVersion()); + assertEquals( + "org.eclipse.tesla:tesla:3", + model.getParent().getGroupId() + + ":" + + model.getParent().getArtifactId() + + ":" + + model.getParent().getVersion()); // // properties // assertEquals("1.7", model.getProperties().getProperty("gossipVersion")); assertEquals("1.12", model.getProperties().getProperty("aetherVersion")); assertEquals("4.8.2", model.getProperties().getProperty("junitVersion")); - assertEquals("2.0.6", model.getProperties().getProperty( - "plexusUtilsVersion")); - assertEquals("2.4", model.getProperties().getProperty( - "classWorldsVersion")); - assertEquals("UTF-8", model.getProperties().getProperty( - "project.build.sourceEncoding")); - assertEquals("yyyyMMddHHmm", model.getProperties().getProperty( - "maven.build.timestamp.format")); - assertEquals("2.2.1", model.getProperties().getProperty( - "sisuInjectVersion")); - assertEquals("1.4.1", model.getProperties().getProperty( - "modelloVersion")); - assertEquals("Eclipse Tesla", model.getProperties().getProperty( - "distributionName")); - assertEquals("1.5.5", model.getProperties() - .getProperty("plexusVersion")); - assertEquals("3.0.4-SNAPSHOT", model.getProperties().getProperty( - "mavenVersion")); - assertEquals("1.2_Java1.3", model.getProperties().getProperty( - "easyMockVersion")); + assertEquals("2.0.6", model.getProperties().getProperty("plexusUtilsVersion")); + assertEquals("2.4", model.getProperties().getProperty("classWorldsVersion")); + assertEquals("UTF-8", model.getProperties().getProperty("project.build.sourceEncoding")); + assertEquals("yyyyMMddHHmm", model.getProperties().getProperty("maven.build.timestamp.format")); + assertEquals("2.2.1", model.getProperties().getProperty("sisuInjectVersion")); + assertEquals("1.4.1", model.getProperties().getProperty("modelloVersion")); + assertEquals("Eclipse Tesla", model.getProperties().getProperty("distributionName")); + assertEquals("1.5.5", model.getProperties().getProperty("plexusVersion")); + assertEquals("3.0.4-SNAPSHOT", model.getProperties().getProperty("mavenVersion")); + assertEquals("1.2_Java1.3", model.getProperties().getProperty("easyMockVersion")); assertEquals("2.3", model.getProperties().getProperty("jlineVersion")); assertEquals("1.3", model.getProperties().getProperty("jxpathVersion")); - assertEquals("true", model.getProperties().getProperty( - "maven.test.redirectTestOutputToFile")); - assertEquals("1.2", model.getProperties().getProperty( - "commonsCliVersion")); - assertEquals("UTF-8", model.getProperties().getProperty( - "project.reporting.outputEncoding")); - assertEquals("1.14", model.getProperties().getProperty( - "plexusInterpolationVersion")); - assertEquals("Tesla", model.getProperties().getProperty( - "distributionShortName")); - assertEquals("1.0-beta-7", model.getProperties().getProperty( - "wagonVersion")); - assertEquals("${maven.build.timestamp}", model.getProperties() - .getProperty("build.timestamp")); - assertEquals("1.3", model.getProperties().getProperty( - "securityDispatcherVersion")); - assertEquals("eclipse-tesla", model.getProperties().getProperty( - "distributionId")); + assertEquals("true", model.getProperties().getProperty("maven.test.redirectTestOutputToFile")); + assertEquals("1.2", model.getProperties().getProperty("commonsCliVersion")); + assertEquals("UTF-8", model.getProperties().getProperty("project.reporting.outputEncoding")); + assertEquals("1.14", model.getProperties().getProperty("plexusInterpolationVersion")); + assertEquals("Tesla", model.getProperties().getProperty("distributionShortName")); + assertEquals("1.0-beta-7", model.getProperties().getProperty("wagonVersion")); + assertEquals("${maven.build.timestamp}", model.getProperties().getProperty("build.timestamp")); + assertEquals("1.3", model.getProperties().getProperty("securityDispatcherVersion")); + assertEquals("eclipse-tesla", model.getProperties().getProperty("distributionId")); assertEquals("1.6.1", model.getProperties().getProperty("slf4jVersion")); assertEquals("1.7", model.getProperties().getProperty("cipherVersion")); - assertEquals("3.0.4-SNAPSHOT", model.getProperties().getProperty( - "gshellVersion")); + assertEquals("3.0.4-SNAPSHOT", model.getProperties().getProperty("gshellVersion")); // // dependencies // - assertEquals("junit:junit:${junitVersion}", gav(model.getDependencies() - .get(0))); + assertEquals("junit:junit:${junitVersion}", gav(model.getDependencies().get(0))); assertEquals("test", model.getDependencies().get(0).getScope()); // // dependencyManager // - assertEquals("org.apache.maven:maven-model:${project.version}", + assertEquals( + "org.apache.maven:maven-model:${project.version}", gav(model.getDependencyManagement().getDependencies().get(0))); - assertEquals("org.apache.maven:maven-core:${project.version}", + assertEquals( + "org.apache.maven:maven-core:${project.version}", gav(model.getDependencyManagement().getDependencies().get(5))); assertEquals( "org.sonatype.sisu:sisu-inject-plexus:${sisuInjectVersion}", gav(model.getDependencyManagement().getDependencies().get(12))); - assertEquals("org.slf4j:slf4j-simple:${slf4jVersion}", gav(model - .getDependencyManagement().getDependencies().get(18))); - assertEquals("runtime", model.getDependencyManagement() - .getDependencies().get(18).getScope()); - assertEquals("commons-cli:commons-cli:${commonsCliVersion}", gav(model - .getDependencyManagement().getDependencies().get(31))); - assertEquals(2, model.getDependencyManagement().getDependencies().get( - 31).getExclusions().size()); - assertEquals("commons-lang:commons-lang", gav(model - .getDependencyManagement().getDependencies().get(31) - .getExclusions().get(0))); - assertEquals("commons-logging:commons-logging", gav(model - .getDependencyManagement().getDependencies().get(31) - .getExclusions().get(1))); - assertEquals("org.sonatype.jline:jline:${jlineVersion}", gav(model - .getDependencyManagement().getDependencies().get(61))); - assertEquals("tests", model.getDependencyManagement().getDependencies() - .get(61).getClassifier()); + assertEquals( + "org.slf4j:slf4j-simple:${slf4jVersion}", + gav(model.getDependencyManagement().getDependencies().get(18))); + assertEquals( + "runtime", + model.getDependencyManagement().getDependencies().get(18).getScope()); + assertEquals( + "commons-cli:commons-cli:${commonsCliVersion}", + gav(model.getDependencyManagement().getDependencies().get(31))); + assertEquals( + 2, + model.getDependencyManagement() + .getDependencies() + .get(31) + .getExclusions() + .size()); + assertEquals( + "commons-lang:commons-lang", + gav(model.getDependencyManagement() + .getDependencies() + .get(31) + .getExclusions() + .get(0))); + assertEquals( + "commons-logging:commons-logging", + gav(model.getDependencyManagement() + .getDependencies() + .get(31) + .getExclusions() + .get(1))); + assertEquals( + "org.sonatype.jline:jline:${jlineVersion}", + gav(model.getDependencyManagement().getDependencies().get(61))); + assertEquals( + "tests", + model.getDependencyManagement().getDependencies().get(61).getClassifier()); // // pluginManager // Plugin p = model.getBuild().getPluginManagement().getPlugins().get(0); - assertEquals( - "org.codehaus.plexus:plexus-component-metadata:${plexusVersion}", - gav(p)); + assertEquals("org.codehaus.plexus:plexus-component-metadata:${plexusVersion}", gav(p)); assertNull(p.getConfiguration()); p = model.getBuild().getPluginManagement().getPlugins().get(6); - assertEquals( - "org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5", - gav(p)); + assertEquals("org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5", gav(p)); assertNull(p.getConfiguration()); p = model.getBuild().getPluginManagement().getPlugins().get(1); - assertEquals( - "org.apache.maven.plugins:maven-compiler-plugin:2.3.2", - gav(p)); + assertEquals("org.apache.maven.plugins:maven-compiler-plugin:2.3.2", gav(p)); assertNotNull(p.getConfiguration()); - assertEquals("1.5", ((Xpp3Dom) p.getConfiguration()).getChild( - "source").getValue()); + assertEquals("1.5", ((Xpp3Dom) p.getConfiguration()).getChild("source").getValue()); p = model.getBuild().getPluginManagement().getPlugins().get(4); - assertEquals( - "org.codehaus.modello:modello-maven-plugin:${modelloVersion}", - gav(p)); + assertEquals("org.codehaus.modello:modello-maven-plugin:${modelloVersion}", gav(p)); assertNotNull(p.getConfiguration()); - assertEquals("true", ((Xpp3Dom) p.getConfiguration()).getChild( - "useJava5").getValue()); + assertEquals( + "true", ((Xpp3Dom) p.getConfiguration()).getChild("useJava5").getValue()); // // modules // @@ -278,11 +263,9 @@ void testMavenModelForCompleteness(Model model) { // plugins // p = model.getBuild().getPlugins().get(0); - assertEquals("org.codehaus.mojo:animal-sniffer-maven-plugin:1.6", - gav(p)); + assertEquals("org.codehaus.mojo:animal-sniffer-maven-plugin:1.6", gav(p)); assertNotNull(p.getConfiguration()); - Xpp3Dom config = ((Xpp3Dom) p.getConfiguration()).getChild( - "signature"); + Xpp3Dom config = ((Xpp3Dom) p.getConfiguration()).getChild("signature"); assertNull(config.getValue()); assertEquals("org.codehaus.mojo.signature", config.getChild("groupId").getValue()); assertEquals("java15", config.getChild("artifactId").getValue()); @@ -308,18 +291,18 @@ void testMavenModelForCompleteness(Model model) { assertEquals("test-index", goals.get(1)); p = model.getBuild().getPlugins().get(2); - assertEquals( - "com.mycila.maven-license-plugin:maven-license-plugin:1.9.0", - gav(p)); + assertEquals("com.mycila.maven-license-plugin:maven-license-plugin:1.9.0", gav(p)); assertNotNull(p.getConfiguration()); - assertEquals("true", ((Xpp3Dom) p.getConfiguration()).getChild( - "aggregate").getValue()); - assertEquals("true", ((Xpp3Dom) p.getConfiguration()).getChild( - "strictCheck").getValue()); - assertEquals("false", ((Xpp3Dom) p.getConfiguration()).getChild( - "useDefaultExcludes").getValue()); - assertEquals("${project.basedir}/header.txt", ((Xpp3Dom) p - .getConfiguration()).getChild("header").getValue()); + assertEquals( + "true", ((Xpp3Dom) p.getConfiguration()).getChild("aggregate").getValue()); + assertEquals( + "true", ((Xpp3Dom) p.getConfiguration()).getChild("strictCheck").getValue()); + assertEquals( + "false", + ((Xpp3Dom) p.getConfiguration()).getChild("useDefaultExcludes").getValue()); + assertEquals( + "${project.basedir}/header.txt", + ((Xpp3Dom) p.getConfiguration()).getChild("header").getValue()); config = ((Xpp3Dom) p.getConfiguration()).getChild("excludes"); assertNull(config.getValue()); diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemfileTest.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemfileTest.java index 315d7797..c9973329 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemfileTest.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemfileTest.java @@ -7,43 +7,41 @@ */ package org.sonatype.maven.polyglot.ruby; - public class RubyReaderWithGemfileTest extends AbstractInjectedTestCase { - public void testGemfile() throws Exception { - assertModels( "gemfile/Mavenfile", false ); - } + public void testGemfile() throws Exception { + assertModels("gemfile/Mavenfile", false); + } - public void testGemfileWithAccessToModel() throws Exception { - assertModels( "gemfile_with_access_to_model/Mavenfile", false ); - } + public void testGemfileWithAccessToModel() throws Exception { + assertModels("gemfile_with_access_to_model/Mavenfile", false); + } - public void testGemfileWithExtras() throws Exception { - assertModels( "gemfile_with_extras/Mavenfile", false ); - } + public void testGemfileWithExtras() throws Exception { + assertModels("gemfile_with_extras/Mavenfile", false); + } - public void testGemfileIncludeJars() throws Exception { - assertModels( "gemfile_include_jars/Mavenfile", false ); - } + public void testGemfileIncludeJars() throws Exception { + assertModels("gemfile_include_jars/Mavenfile", false); + } - public void testGemfileWithSource() throws Exception { - assertModels( "gemfile_with_source/Mavenfile", false ); - } + public void testGemfileWithSource() throws Exception { + assertModels("gemfile_with_source/Mavenfile", false); + } - public void testGemfileWithSourceAndNoJar() throws Exception { - assertModels( "gemfile_with_source_and_no_jar/Mavenfile", false ); - } - - public void testGemfileWithCustomSource() throws Exception { - assertModels( "gemfile_with_custom_source/Mavenfile", false ); - } + public void testGemfileWithSourceAndNoJar() throws Exception { + assertModels("gemfile_with_source_and_no_jar/Mavenfile", false); + } - public void testGemfileWithSourceAndCustomJarname() throws Exception { - assertModels( "gemfile_with_source_and_custom_jarname/Mavenfile", false ); - } + public void testGemfileWithCustomSource() throws Exception { + assertModels("gemfile_with_custom_source/Mavenfile", false); + } - public void testGemfileWithCustomSourceAndCustomJarname() throws Exception { - assertModels( "gemfile_with_custom_source_and_custom_jarname/Mavenfile", false ); - } + public void testGemfileWithSourceAndCustomJarname() throws Exception { + assertModels("gemfile_with_source_and_custom_jarname/Mavenfile", false); + } + public void testGemfileWithCustomSourceAndCustomJarname() throws Exception { + assertModels("gemfile_with_custom_source_and_custom_jarname/Mavenfile", false); + } } diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemspecsTest.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemspecsTest.java index 82a3a1ec..4ae1776a 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemspecsTest.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithGemspecsTest.java @@ -7,51 +7,51 @@ */ package org.sonatype.maven.polyglot.ruby; - public class RubyReaderWithGemspecsTest extends AbstractInjectedTestCase { - public void testGemspec() throws Exception { - assertModels( "gemspec/Mavenfile", false ); - } - - public void testGemspecInProfile() throws Exception { - assertModels( "gemspec_in_profile/Mavenfile", false ); - } - - public void testGemspecWithAccessToModel() throws Exception { - assertModels( "gemspec_with_access_to_model/Mavenfile", false ); - } - - public void testGemspecWithExtras() throws Exception { - assertModels( "gemspec_with_extras/Mavenfile", false ); - } - - public void testGemspecIncludeJars() throws Exception { - assertModels( "gemspec_include_jars/Mavenfile", false ); - } - - public void testGemspecWithSource() throws Exception { - assertModels( "gemspec_with_source/Mavenfile", false ); - } - - public void testGemspecWithSourceAndNoJar() throws Exception { - assertModels( "gemspec_with_source_and_no_jar/pom.xml", - "gemspec_with_source_and_no_jar/Mavenfile", false ); - } - - public void testGemspecWithCustomSource() throws Exception { - assertModels( "gemspec_with_custom_source/pom.xml", - "gemspec_with_custom_source/Mavenfile", false ); - } - - public void testGemspecWithSourceAndCustomJarname() throws Exception { - assertModels( "gemspec_with_source_and_custom_jarname/pom.xml", - "gemspec_with_source_and_custom_jarname/Mavenfile", false ); - } - - public void testGemspecWithCustomSourceAndCustomJarname() throws Exception { - assertModels( "gemspec_with_custom_source_and_custom_jarname/pom.xml", - "gemspec_with_custom_source_and_custom_jarname/Mavenfile", false ); - } - + public void testGemspec() throws Exception { + assertModels("gemspec/Mavenfile", false); + } + + public void testGemspecInProfile() throws Exception { + assertModels("gemspec_in_profile/Mavenfile", false); + } + + public void testGemspecWithAccessToModel() throws Exception { + assertModels("gemspec_with_access_to_model/Mavenfile", false); + } + + public void testGemspecWithExtras() throws Exception { + assertModels("gemspec_with_extras/Mavenfile", false); + } + + public void testGemspecIncludeJars() throws Exception { + assertModels("gemspec_include_jars/Mavenfile", false); + } + + public void testGemspecWithSource() throws Exception { + assertModels("gemspec_with_source/Mavenfile", false); + } + + public void testGemspecWithSourceAndNoJar() throws Exception { + assertModels("gemspec_with_source_and_no_jar/pom.xml", "gemspec_with_source_and_no_jar/Mavenfile", false); + } + + public void testGemspecWithCustomSource() throws Exception { + assertModels("gemspec_with_custom_source/pom.xml", "gemspec_with_custom_source/Mavenfile", false); + } + + public void testGemspecWithSourceAndCustomJarname() throws Exception { + assertModels( + "gemspec_with_source_and_custom_jarname/pom.xml", + "gemspec_with_source_and_custom_jarname/Mavenfile", + false); + } + + public void testGemspecWithCustomSourceAndCustomJarname() throws Exception { + assertModels( + "gemspec_with_custom_source_and_custom_jarname/pom.xml", + "gemspec_with_custom_source_and_custom_jarname/Mavenfile", + false); + } } diff --git a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithPomTest.java b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithPomTest.java index e7cfb371..a760f80b 100644 --- a/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithPomTest.java +++ b/polyglot-ruby/src/test/java/org/sonatype/maven/polyglot/ruby/RubyReaderWithPomTest.java @@ -7,167 +7,211 @@ */ package org.sonatype.maven.polyglot.ruby; - public class RubyReaderWithPomTest extends AbstractInjectedTestCase { - public void testPomMavenStyle() throws Exception { - assertModels( "pom_maven_style/pom.rb", false ); - } - - public void testPomMavenAlternativeStyle() throws Exception { - assertModels( "pom_maven_alternative_style/pom.rb", false ); - } - - public void testPomMavenHashStyle() throws Exception { - assertModels( "pom_maven_hash_style/pom.rb", false ); - } - - public void testMavenfile() throws Exception { - assertModels( "mavenfile/Mavenfile", false ); - } - - // cd target/rubygems-provided/gems/maven-tools-1.1.0 - // find spec/*/* -name pom.xml | sed -e s/spec.// -e s/.pom.xml// -e "s/\(.*\)/ public void test_\1() throws Exception {\n assertModels( \"\1\/Mavenfile\", false );\n }/" - public void test_gemfile() throws Exception { - assertModels( "gemfile/Mavenfile", false ); - } - public void test_gemfile_include_jars() throws Exception { - assertModels( "gemfile_include_jars/Mavenfile", false ); - } - public void test_gemfile_with_access_to_model() throws Exception { - assertModels( "gemfile_with_access_to_model/Mavenfile", false ); - } - public void test_gemfile_with_custom_source() throws Exception { - assertModels( "gemfile_with_custom_source/Mavenfile", false ); - } - public void test_gemfile_with_custom_source_and_custom_jarname() throws Exception { - assertModels( "gemfile_with_custom_source_and_custom_jarname/Mavenfile", false ); - } - public void test_gemfile_with_extras() throws Exception { - assertModels( "gemfile_with_extras/Mavenfile", false ); - } - public void test_gemfile_with_groups() throws Exception { - assertModels( "gemfile_with_groups/Mavenfile", false ); - } - public void test_gemfile_with_groups_and_lockfile() throws Exception { - assertModels( "gemfile_with_groups_and_lockfile/Mavenfile", false ); - } - public void test_gemfile_with_jars_lock() throws Exception { - assertModels( "gemfile_with_jars_lock/Mavenfile", false ); - } - public void test_gemfile_with_lock() throws Exception { - assertModels( "gemfile_with_lock/Mavenfile", false ); - } - public void test_gemfile_with_path() throws Exception { - assertModels( "gemfile_with_path/Mavenfile", false ); - } - public void test_gemfile_with_platforms() throws Exception { - assertModels( "gemfile_with_platforms/Mavenfile", false ); - } - public void test_gemfile_with_source() throws Exception { - assertModels( "gemfile_with_source/Mavenfile", false ); - } - public void test_gemfile_with_source_and_custom_jarname() throws Exception { - assertModels( "gemfile_with_source_and_custom_jarname/Mavenfile", false ); - } - public void test_gemfile_with_source_and_no_jar() throws Exception { - assertModels( "gemfile_with_source_and_no_jar/Mavenfile", false ); - } - public void test_gemfile_with_test_group() throws Exception { - assertModels( "gemfile_with_test_group/Mavenfile", false ); - } - public void test_gemfile_with_two_sources() throws Exception { - assertModels( "gemfile_with_two_sources/Mavenfile", false ); - } - public void test_gemfile_without_gemspec() throws Exception { - assertModels( "gemfile_without_gemspec/Mavenfile", false ); - } - public void test_gemspec() throws Exception { - assertModels( "gemspec/Mavenfile", false ); - } - public void test_gemspec_in_profile() throws Exception { - assertModels( "gemspec_in_profile/Mavenfile", false ); - } - public void test_gemspec_include_jars() throws Exception { - assertModels( "gemspec_include_jars/Mavenfile", false ); - } - public void test_gemspec_no_rubygems_repo() throws Exception { - assertModels( "gemspec_no_rubygems_repo/Mavenfile", false ); - } - public void test_gemspec_prerelease() throws Exception { - assertModels( "gemspec_prerelease/Mavenfile", false ); - } - public void test_gemspec_prerelease_snapshot() throws Exception { - assertModels( "gemspec_prerelease_snapshot/Mavenfile", false ); - } - public void test_gemspec_with_access_to_model() throws Exception { - assertModels( "gemspec_with_access_to_model/Mavenfile", false ); - } - public void test_gemspec_with_custom_source() throws Exception { - assertModels( "gemspec_with_custom_source/Mavenfile", false ); - } - public void test_gemspec_with_custom_source_and_custom_jarname() throws Exception { - assertModels( "gemspec_with_custom_source_and_custom_jarname/Mavenfile", false ); - } - public void test_gemspec_with_extras() throws Exception { - assertModels( "gemspec_with_extras/Mavenfile", false ); - } - public void test_gemspec_with_jar_dependencies() throws Exception { - assertModels( "gemspec_with_jar_dependencies/Mavenfile", false ); - } - public void test_gemspec_with_jars_lock() throws Exception { - assertModels( "gemspec_with_jars_lock/Mavenfile", false ); - } - public void test_gemspec_with_prereleased_dependency() throws Exception { - assertModels( "gemspec_with_prereleased_dependency/Mavenfile", false ); - } - public void test_gemspec_with_prereleased_dependency_and_no_repo() throws Exception { - assertModels( "gemspec_with_prereleased_dependency_and_no_repo/Mavenfile", false ); - } - public void test_gemspec_with_source() throws Exception { - assertModels( "gemspec_with_source/Mavenfile", false ); - } - public void test_gemspec_with_source_and_custom_jarname() throws Exception { - assertModels( "gemspec_with_source_and_custom_jarname/Mavenfile", false ); - } - public void test_gemspec_with_source_and_no_jar() throws Exception { - assertModels( "gemspec_with_source_and_no_jar/Mavenfile", false ); - } - public void test_mavenfile_jrubyJar() throws Exception { - assertModels( "mavenfile_jrubyJar/Mavenfile", false ); - } - public void test_mavenfile_jrubyWar() throws Exception { - assertModels( "mavenfile_jrubyWar/Mavenfile", false ); - } - public void test_pom_from_jarfile() throws Exception { - assertModels( "pom_from_jarfile/pom.rb", false ); - } - public void test_pom_from_jarfile_and_empty_lock() throws Exception { - assertModels( "pom_from_jarfile_and_empty_lock/pom.rb", false ); - } - public void test_pom_from_jarfile_and_lock() throws Exception { - assertModels( "pom_from_jarfile_and_lock/pom.rb", false ); - } - public void test_pom_from_jarfile_and_skip_lock() throws Exception { - assertModels( "pom_from_jarfile_and_skip_lock/pom.rb", false ); - } - public void test_pom_from_jarfile_help_only() throws Exception { - assertModels( "pom_from_jarfile_help_only/pom.rb", false ); - } - public void test_pom_from_jarfile_with_exclusions() throws Exception { - assertModels( "pom_from_jarfile_with_exclusions/pom.rb", false ); - } - public void test_pom_from_jarfile_with_jruby() throws Exception { - assertModels( "pom_from_jarfile_with_jruby/pom.rb", false ); - } - public void test_pom_from_jarfile_with_repos() throws Exception { - assertModels( "pom_from_jarfile_with_repos/pom.rb", false ); - } - // the maven-tools has a hard-coded version of this - // polyglot-ruby version. the test will remove the -SNAPSHOT - // of this version - public void test_pom_with_execute() throws Exception { - // FIXME execute tasks are not inheritable -// assertModels( "pom_with_execute/pom.rb", false ); - } + public void testPomMavenStyle() throws Exception { + assertModels("pom_maven_style/pom.rb", false); + } + + public void testPomMavenAlternativeStyle() throws Exception { + assertModels("pom_maven_alternative_style/pom.rb", false); + } + + public void testPomMavenHashStyle() throws Exception { + assertModels("pom_maven_hash_style/pom.rb", false); + } + + public void testMavenfile() throws Exception { + assertModels("mavenfile/Mavenfile", false); + } + + // cd target/rubygems-provided/gems/maven-tools-1.1.0 + // find spec/*/* -name pom.xml | sed -e s/spec.// -e s/.pom.xml// -e "s/\(.*\)/ public void test_\1() throws + // Exception {\n assertModels( \"\1\/Mavenfile\", false );\n }/" + public void test_gemfile() throws Exception { + assertModels("gemfile/Mavenfile", false); + } + + public void test_gemfile_include_jars() throws Exception { + assertModels("gemfile_include_jars/Mavenfile", false); + } + + public void test_gemfile_with_access_to_model() throws Exception { + assertModels("gemfile_with_access_to_model/Mavenfile", false); + } + + public void test_gemfile_with_custom_source() throws Exception { + assertModels("gemfile_with_custom_source/Mavenfile", false); + } + + public void test_gemfile_with_custom_source_and_custom_jarname() throws Exception { + assertModels("gemfile_with_custom_source_and_custom_jarname/Mavenfile", false); + } + + public void test_gemfile_with_extras() throws Exception { + assertModels("gemfile_with_extras/Mavenfile", false); + } + + public void test_gemfile_with_groups() throws Exception { + assertModels("gemfile_with_groups/Mavenfile", false); + } + + public void test_gemfile_with_groups_and_lockfile() throws Exception { + assertModels("gemfile_with_groups_and_lockfile/Mavenfile", false); + } + + public void test_gemfile_with_jars_lock() throws Exception { + assertModels("gemfile_with_jars_lock/Mavenfile", false); + } + + public void test_gemfile_with_lock() throws Exception { + assertModels("gemfile_with_lock/Mavenfile", false); + } + + public void test_gemfile_with_path() throws Exception { + assertModels("gemfile_with_path/Mavenfile", false); + } + + public void test_gemfile_with_platforms() throws Exception { + assertModels("gemfile_with_platforms/Mavenfile", false); + } + + public void test_gemfile_with_source() throws Exception { + assertModels("gemfile_with_source/Mavenfile", false); + } + + public void test_gemfile_with_source_and_custom_jarname() throws Exception { + assertModels("gemfile_with_source_and_custom_jarname/Mavenfile", false); + } + + public void test_gemfile_with_source_and_no_jar() throws Exception { + assertModels("gemfile_with_source_and_no_jar/Mavenfile", false); + } + + public void test_gemfile_with_test_group() throws Exception { + assertModels("gemfile_with_test_group/Mavenfile", false); + } + + public void test_gemfile_with_two_sources() throws Exception { + assertModels("gemfile_with_two_sources/Mavenfile", false); + } + + public void test_gemfile_without_gemspec() throws Exception { + assertModels("gemfile_without_gemspec/Mavenfile", false); + } + + public void test_gemspec() throws Exception { + assertModels("gemspec/Mavenfile", false); + } + + public void test_gemspec_in_profile() throws Exception { + assertModels("gemspec_in_profile/Mavenfile", false); + } + + public void test_gemspec_include_jars() throws Exception { + assertModels("gemspec_include_jars/Mavenfile", false); + } + + public void test_gemspec_no_rubygems_repo() throws Exception { + assertModels("gemspec_no_rubygems_repo/Mavenfile", false); + } + + public void test_gemspec_prerelease() throws Exception { + assertModels("gemspec_prerelease/Mavenfile", false); + } + + public void test_gemspec_prerelease_snapshot() throws Exception { + assertModels("gemspec_prerelease_snapshot/Mavenfile", false); + } + + public void test_gemspec_with_access_to_model() throws Exception { + assertModels("gemspec_with_access_to_model/Mavenfile", false); + } + + public void test_gemspec_with_custom_source() throws Exception { + assertModels("gemspec_with_custom_source/Mavenfile", false); + } + + public void test_gemspec_with_custom_source_and_custom_jarname() throws Exception { + assertModels("gemspec_with_custom_source_and_custom_jarname/Mavenfile", false); + } + + public void test_gemspec_with_extras() throws Exception { + assertModels("gemspec_with_extras/Mavenfile", false); + } + + public void test_gemspec_with_jar_dependencies() throws Exception { + assertModels("gemspec_with_jar_dependencies/Mavenfile", false); + } + + public void test_gemspec_with_jars_lock() throws Exception { + assertModels("gemspec_with_jars_lock/Mavenfile", false); + } + + public void test_gemspec_with_prereleased_dependency() throws Exception { + assertModels("gemspec_with_prereleased_dependency/Mavenfile", false); + } + + public void test_gemspec_with_prereleased_dependency_and_no_repo() throws Exception { + assertModels("gemspec_with_prereleased_dependency_and_no_repo/Mavenfile", false); + } + + public void test_gemspec_with_source() throws Exception { + assertModels("gemspec_with_source/Mavenfile", false); + } + + public void test_gemspec_with_source_and_custom_jarname() throws Exception { + assertModels("gemspec_with_source_and_custom_jarname/Mavenfile", false); + } + + public void test_gemspec_with_source_and_no_jar() throws Exception { + assertModels("gemspec_with_source_and_no_jar/Mavenfile", false); + } + + public void test_mavenfile_jrubyJar() throws Exception { + assertModels("mavenfile_jrubyJar/Mavenfile", false); + } + + public void test_mavenfile_jrubyWar() throws Exception { + assertModels("mavenfile_jrubyWar/Mavenfile", false); + } + + public void test_pom_from_jarfile() throws Exception { + assertModels("pom_from_jarfile/pom.rb", false); + } + + public void test_pom_from_jarfile_and_empty_lock() throws Exception { + assertModels("pom_from_jarfile_and_empty_lock/pom.rb", false); + } + + public void test_pom_from_jarfile_and_lock() throws Exception { + assertModels("pom_from_jarfile_and_lock/pom.rb", false); + } + + public void test_pom_from_jarfile_and_skip_lock() throws Exception { + assertModels("pom_from_jarfile_and_skip_lock/pom.rb", false); + } + + public void test_pom_from_jarfile_help_only() throws Exception { + assertModels("pom_from_jarfile_help_only/pom.rb", false); + } + + public void test_pom_from_jarfile_with_exclusions() throws Exception { + assertModels("pom_from_jarfile_with_exclusions/pom.rb", false); + } + + public void test_pom_from_jarfile_with_jruby() throws Exception { + assertModels("pom_from_jarfile_with_jruby/pom.rb", false); + } + + public void test_pom_from_jarfile_with_repos() throws Exception { + assertModels("pom_from_jarfile_with_repos/pom.rb", false); + } + // the maven-tools has a hard-coded version of this + // polyglot-ruby version. the test will remove the -SNAPSHOT + // of this version + public void test_pom_with_execute() throws Exception { + // FIXME execute tasks are not inheritable + // assertModels( "pom_with_execute/pom.rb", false ); + } } diff --git a/polyglot-scala/.scalafmt.conf b/polyglot-scala/.scalafmt.conf new file mode 100644 index 00000000..0cbd9901 --- /dev/null +++ b/polyglot-scala/.scalafmt.conf @@ -0,0 +1,23 @@ +# Newer versions won't work with Java 8! +version = "3.8.1" + +align.openParenCallSite = false +align.preset = none +align.stripMargin = true + +assumeStandardLibraryStripMargin = true + +continuationIndent.callSite = 2 +continuationIndent.defnSite = 4 + +docstrings.oneline = keep +docstrings.style = Asterisk +docstrings.wrap = no + +maxColumn = 100 + +newlines.source = keep + +project.git = true + +runner.dialect = scala213 diff --git a/polyglot-scala/pom.xml b/polyglot-scala/pom.xml index e5e00e5e..8e30973c 100644 --- a/polyglot-scala/pom.xml +++ b/polyglot-scala/pom.xml @@ -18,11 +18,6 @@ polyglot-scala takari-maven-component Polyglot :: Scala - - - 2.13.14 - 2.13 - @@ -36,6 +31,11 @@ + + 2.13.14 + 2.13 + + io.takari.polyglot @@ -65,7 +65,7 @@ scala-library ${scala.version} - + org.scala-lang scala-reflect @@ -77,7 +77,7 @@ scala-compiler ${scala.version} - + org.specs2 specs2-junit_${scala.bin.version} @@ -86,9 +86,49 @@ + + + + false + + sonatype-public-grid + https://repository.sonatype.org/content/groups/sonatype-public-grid/ + + + - src/main/scala - src/test/scala + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + net.alchim31.maven + scala-maven-plugin + [3.3.0,) + + add-source + compile + testCompile + + + + + + + + + + + + org.apache.maven.plugins @@ -148,54 +188,28 @@ true false true - verify + + verify + + + com.diffplug.spotless + spotless-maven-plugin + + + + 3.8.1 + ${project.basedir}/.scalafmt.conf + + + + - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - net.alchim31.maven - scala-maven-plugin - [3.3.0,) - - add-source - compile - testCompile - - - - - - - - - - - - + src/main/scala + src/test/scala - - - sonatype-public-grid - https://repository.sonatype.org/content/groups/sonatype-public-grid/ - - false - - - - diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaMapping.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaMapping.scala index 03dcbbc0..bf65813c 100755 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaMapping.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaMapping.scala @@ -19,4 +19,4 @@ class ScalaMapping extends MappingSupport("scala") { setAcceptLocationExtensions(".scala") setAcceptOptionKeys("scala:4.0.0") setPriority(1) -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelReader.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelReader.scala index a6e4b9df..66409c9f 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelReader.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelReader.scala @@ -16,7 +16,7 @@ import org.sonatype.maven.polyglot.scala.eval.Eval import java.io._ import java.util -import javax.inject.{ Named, Inject } +import javax.inject.{Named, Inject} import org.apache.maven.model.io.ModelParseException import org.apache.maven.model.io.ModelReader @@ -24,9 +24,42 @@ import org.apache.maven.model.Model import org.codehaus.plexus.util.FileUtils import org.codehaus.plexus.util.IOUtil import org.codehaus.plexus.util.io.RawInputStreamFacade -import org.sonatype.maven.polyglot.execute.{ ExecuteContext, ExecuteTask, ExecuteManager } +import org.sonatype.maven.polyglot.execute.{ExecuteContext, ExecuteTask, ExecuteManager} import org.sonatype.maven.polyglot.PolyglotModelUtil -import org.sonatype.maven.polyglot.scala.model.{ Activation => ScalaActivation, ActivationFile => ScalaActivationFile, ActivationOS => ScalaActivationOS, ActivationProperty => ScalaActivationProperty, Build => ScalaBuild, BuildBase => ScalaBuildBase, CiManagement => ScalaCiManagement, Config => ScalaConfig, Contributor => ScalaContributor, DependencyManagement => ScalaDependencyManagement, Dependency => ScalaDependency, DeploymentRepository => ScalaDeploymentRepository, Developer => ScalaDeveloper, DistributionManagement => ScalaDistributionManagement, Execution => ScalaExecution, Extension => ScalaExtension, IssueManagement => ScalaIssueManagement, License => ScalaLicense, MailingList => ScalaMailingList, Model => ScalaModel, Notifier => ScalaNotifier, Organization => ScalaOrganization, Parent => ScalaParent, Plugin => ScalaPlugin, PluginManagement => ScalaPluginManagement, Relocation => ScalaRelocation, RepositoryPolicy => ScalaRepositoryPolicy, Repository => ScalaRepository, Resource => ScalaResource, Scm => ScalaScm, Site => ScalaSite, _ } +import org.sonatype.maven.polyglot.scala.model.{ + Activation => ScalaActivation, + ActivationFile => ScalaActivationFile, + ActivationOS => ScalaActivationOS, + ActivationProperty => ScalaActivationProperty, + Build => ScalaBuild, + BuildBase => ScalaBuildBase, + CiManagement => ScalaCiManagement, + Config => ScalaConfig, + Contributor => ScalaContributor, + DependencyManagement => ScalaDependencyManagement, + Dependency => ScalaDependency, + DeploymentRepository => ScalaDeploymentRepository, + Developer => ScalaDeveloper, + DistributionManagement => ScalaDistributionManagement, + Execution => ScalaExecution, + Extension => ScalaExtension, + IssueManagement => ScalaIssueManagement, + License => ScalaLicense, + MailingList => ScalaMailingList, + Model => ScalaModel, + Notifier => ScalaNotifier, + Organization => ScalaOrganization, + Parent => ScalaParent, + Plugin => ScalaPlugin, + PluginManagement => ScalaPluginManagement, + Relocation => ScalaRelocation, + RepositoryPolicy => ScalaRepositoryPolicy, + Repository => ScalaRepository, + Resource => ScalaResource, + Scm => ScalaScm, + Site => ScalaSite, + _ +} /** * implicit conversions around the "pimp my library" approach for converting Scala models to their Maven types. @@ -41,7 +74,8 @@ object ScalaConverters { implicit def enrichScalaActivationOS(v: ScalaActivationOS): ConvertibleScalaActivationOS = new ConvertibleScalaActivationOS(v) - implicit def enrichScalaActivationProperty(v: ScalaActivationProperty): ConvertibleScalaActivationProperty = + implicit def enrichScalaActivationProperty(v: ScalaActivationProperty) + : ConvertibleScalaActivationProperty = new ConvertibleScalaActivationProperty(v) implicit def enrichScalaBuild(v: ScalaBuild): ConvertibleScalaBuild = @@ -62,16 +96,19 @@ object ScalaConverters { implicit def enrichScalaDependency(v: ScalaDependency): ConvertibleScalaDependency = new ConvertibleScalaDependency(v) - implicit def enrichScalaDependencyManagement(v: ScalaDependencyManagement): ConvertibleScalaDependencyManagement = + implicit def enrichScalaDependencyManagement(v: ScalaDependencyManagement) + : ConvertibleScalaDependencyManagement = new ConvertibleScalaDependencyManagement(v) - implicit def enrichScalaDeploymentRepository(v: ScalaDeploymentRepository): ConvertibleScalaDeploymentRepository = + implicit def enrichScalaDeploymentRepository(v: ScalaDeploymentRepository) + : ConvertibleScalaDeploymentRepository = new ConvertibleScalaDeploymentRepository(v) implicit def enrichScalaDeveloper(v: ScalaDeveloper): ConvertibleScalaDeveloper = new ConvertibleScalaDeveloper(v) - implicit def enrichScalaDistributionManagement(v: ScalaDistributionManagement): ConvertibleScalaDistributionManagement = + implicit def enrichScalaDistributionManagement(v: ScalaDistributionManagement) + : ConvertibleScalaDistributionManagement = new ConvertibleScalaDistributionManagement(v) implicit def enrichScalaExecution(v: ScalaExecution): ConvertibleScalaExecution = @@ -80,7 +117,8 @@ object ScalaConverters { implicit def enrichScalaExtension(v: ScalaExtension): ConvertibleScalaExtension = new ConvertibleScalaExtension(v) - implicit def enrichScalaIssueManagement(v: ScalaIssueManagement): ConvertibleScalaIssueManagement = + implicit def enrichScalaIssueManagement(v: ScalaIssueManagement) + : ConvertibleScalaIssueManagement = new ConvertibleScalaIssueManagement(v) implicit def enrichScalaLicense(v: ScalaLicense): ConvertibleScalaLicense = @@ -104,7 +142,8 @@ object ScalaConverters { implicit def enrichScalaPlugin(v: ScalaPlugin): ConvertibleScalaPlugin = new ConvertibleScalaPlugin(v) - implicit def enrichScalaPluginManagement(v: ScalaPluginManagement): ConvertibleScalaPluginManagement = + implicit def enrichScalaPluginManagement(v: ScalaPluginManagement) + : ConvertibleScalaPluginManagement = new ConvertibleScalaPluginManagement(v) implicit def enrichScalaPrerequisites(v: Prerequisites): ConvertibleScalaPrerequisites = @@ -113,7 +152,8 @@ object ScalaConverters { implicit def enrichScalaProfile(v: Profile): ConvertibleScalaProfile = new ConvertibleScalaProfile(v) - implicit def enrichScalaReleasePolicy(v: ScalaRepositoryPolicy): ConvertibleScalaRepositoryPolicy = + implicit def enrichScalaReleasePolicy(v: ScalaRepositoryPolicy) + : ConvertibleScalaRepositoryPolicy = new ConvertibleScalaRepositoryPolicy(v) implicit def enrichScalaRelocation(v: ScalaRelocation): ConvertibleScalaRelocation = @@ -181,8 +221,10 @@ class ScalaModelReader @Inject() (executeManager: ExecuteManager) extends ModelR private def locateEvalPomFile(options: util.Map[String, _]): File = { val targetDir = Option(System.getProperty("polyglot.scala.outputdir")).getOrElse("target") val source = PolyglotModelUtil.getLocation(options) - val binVersion = _root_.scala.util.Properties.versionNumberString.split("[.]").take(2).mkString(".") - val evalTarget = new File(new File(source).getParent, targetDir + File.separator + "scalamodel_" + binVersion) + val binVersion = + _root_.scala.util.Properties.versionNumberString.split("[.]").take(2).mkString(".") + val evalTarget = + new File(new File(source).getParent, targetDir + File.separator + "scalamodel_" + binVersion) evalTarget.mkdirs() new File(evalTarget, "pom.scala") } @@ -192,19 +234,18 @@ class ScalaModelReader @Inject() (executeManager: ExecuteManager) extends ModelR * * We provide an [[MvnIncludePreprocessor]] that resolves files and classes from an (externally) defined directory * and the the current classloader. - * */ class MvnEval(target: Option[File], includeBaseDir: File) extends Eval(target) { /* - * This is a preprocessor that can include files by requesting them from the given resolvers. - * - * This preprocessor support lines starting with: `//#include`. - * - * @example //#include file-name.scala - * - * Note that it is *not* recursive. Included files cannot have includes - */ + * This is a preprocessor that can include files by requesting them from the given resolvers. + * + * This preprocessor support lines starting with: `//#include`. + * + * @example //#include file-name.scala + * + * Note that it is *not* recursive. Included files cannot have includes + */ class MvnIncludePreprocessor(resolvers: Seq[Resolver]) extends Preprocessor { def maximumRecursionDepth = 100 @@ -252,7 +293,11 @@ class ScalaModelReader @Inject() (executeManager: ExecuteManager) extends ModelR ) } - private def eval(evalPomFile: File, sourcePomFile: File, options: util.Map[String, _]): ScalaModel = { + private def eval( + evalPomFile: File, + sourcePomFile: File, + options: util.Map[String, _] + ): ScalaModel = { val sourceFile = new File(PolyglotModelUtil.getLocation(options)) // ensure, we always use the project base directory to resolve includes val includeBaseDir = sourceFile.getParentFile() @@ -268,13 +313,20 @@ class ScalaModelReader @Inject() (executeManager: ExecuteManager) extends ModelR throw new ModelParseException( "Cannot compile pom file: " + sourceFile + "\nYou can run 'mvn -Deval.debug' to see the resolved scala file.", - 0, 0, e) + 0, + 0, + e + ) case e: Throwable => throw new ModelParseException("Could not process pom file: " + sourceFile, 0, 0, e) } } - private def registerExecutors(m: Model, options: util.Map[String, _], tasks: immutable.Seq[Task]): Unit = { + private def registerExecutors( + m: Model, + options: util.Map[String, _], + tasks: immutable.Seq[Task] + ): Unit = { import scala.jdk.CollectionConverters._ executeManager.register(m, tasks.map(new ScalaTask(_).asInstanceOf[ExecuteTask]).asJava) executeManager.install(m, options) diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelWriter.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelWriter.scala index 7c3c0e57..bbb20565 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelWriter.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/ScalaModelWriter.scala @@ -11,7 +11,43 @@ import java.io.Writer import java.util import org.sonatype.maven.polyglot.io.ModelWriterSupport import org.bitbucket.inkytonik.kiama.output.PrettyPrinter -import org.apache.maven.model.{ Activation => MavenActivation, ActivationFile => MavenActivationFile, ActivationOS => MavenActivationOS, ActivationProperty => MavenActivationProperty, Build => MavenBuild, BuildBase => MavenBuildBase, CiManagement => MavenCiManagement, Contributor => MavenContributor, DependencyManagement => MavenDependencyManagement, Dependency => MavenDependency, DeploymentRepository => MavenDeploymentRepository, Developer => MavenDeveloper, DistributionManagement => MavenDistributionManagement, PluginExecution => MavenExecution, Extension => MavenExtension, IssueManagement => MavenIssueManagement, License => MavenLicense, MailingList => MavenMailingList, Model => MavenModel, Notifier => MavenNotifier, Organization => MavenOrganization, Parent => MavenParent, Plugin => MavenPlugin, PluginManagement => MavenPluginManagement, Prerequisites => MavenPrerequisites, Profile => MavenProfile, Relocation => MavenRelocation, RepositoryPolicy => MavenRepositoryPolicy, Repository => MavenRepository, Resource => MavenResource, Scm => MavenScm, Site => MavenSite, Reporting => MavenReporting, ReportPlugin => MavenReportPlugin, ReportSet => MavenReportSet } +import org.apache.maven.model.{ + Activation => MavenActivation, + ActivationFile => MavenActivationFile, + ActivationOS => MavenActivationOS, + ActivationProperty => MavenActivationProperty, + Build => MavenBuild, + BuildBase => MavenBuildBase, + CiManagement => MavenCiManagement, + Contributor => MavenContributor, + DependencyManagement => MavenDependencyManagement, + Dependency => MavenDependency, + DeploymentRepository => MavenDeploymentRepository, + Developer => MavenDeveloper, + DistributionManagement => MavenDistributionManagement, + PluginExecution => MavenExecution, + Extension => MavenExtension, + IssueManagement => MavenIssueManagement, + License => MavenLicense, + MailingList => MavenMailingList, + Model => MavenModel, + Notifier => MavenNotifier, + Organization => MavenOrganization, + Parent => MavenParent, + Plugin => MavenPlugin, + PluginManagement => MavenPluginManagement, + Prerequisites => MavenPrerequisites, + Profile => MavenProfile, + Relocation => MavenRelocation, + RepositoryPolicy => MavenRepositoryPolicy, + Repository => MavenRepository, + Resource => MavenResource, + Scm => MavenScm, + Site => MavenSite, + Reporting => MavenReporting, + ReportPlugin => MavenReportPlugin, + ReportSet => MavenReportSet +} import org.sonatype.maven.polyglot.scala.model._ import scala.collection.immutable import scala.language.implicitConversions @@ -42,10 +78,14 @@ object ScalaPrettyPrinter extends PrettyPrinter { } def mapStrings(m: Map[String, String]): Doc = { - "Map" <> lparen <> nest(lsep(m.map(me => dquotes(me._1) <+> "->" <+> dquotes(me._2)).toSeq, comma)) <@> rparen + "Map" <> lparen <> nest(lsep( + m.map(me => dquotes(me._1) <+> "->" <+> dquotes(me._2)).toSeq, + comma + )) <@> rparen } - def seqString(s: immutable.Seq[String]): Doc = "Seq" <> lparen <> nest(lsep(s.map(dquotes(_)), comma)) <@> rparen + def seqString(s: immutable.Seq[String]): Doc = + "Seq" <> lparen <> nest(lsep(s.map(dquotes(_)), comma)) <@> rparen def seq(s: immutable.Seq[Doc]): Doc = "Seq" <> lparen <> nest(lsep(s, comma)) <@> rparen @@ -79,7 +119,8 @@ object ScalaPrettyPrinter extends PrettyPrinter { implicit def enrichPrettiedConfig(v: Config): PrettiedConfig = new PrettiedConfig(v) - implicit def enrichPrettiedConfigurationContainer(v: ConfigurationContainer): PrettiedConfigurationContainer = + implicit def enrichPrettiedConfigurationContainer(v: ConfigurationContainer) + : PrettiedConfigurationContainer = new PrettiedConfigurationContainer(v) implicit def enrichPrettiedContributor(v: Contributor): PrettiedContributor = @@ -88,16 +129,19 @@ object ScalaPrettyPrinter extends PrettyPrinter { implicit def enrichPrettiedDependency(v: Dependency): PrettiedDependency = new PrettiedDependency(v) - implicit def enrichPrettiedDependencyManagement(v: DependencyManagement): PrettiedDependencyManagement = + implicit def enrichPrettiedDependencyManagement(v: DependencyManagement) + : PrettiedDependencyManagement = new PrettiedDependencyManagement(v) - implicit def enrichPrettiedDeploymentRepository(v: DeploymentRepository): PrettiedDeploymentRepository = + implicit def enrichPrettiedDeploymentRepository(v: DeploymentRepository) + : PrettiedDeploymentRepository = new PrettiedDeploymentRepository(v) implicit def enrichPrettiedDeveloper(v: Developer): PrettiedDeveloper = new PrettiedDeveloper(v) - implicit def enrichPrettiedDistributionManagement(v: DistributionManagement): PrettiedDistributionManagement = + implicit def enrichPrettiedDistributionManagement(v: DistributionManagement) + : PrettiedDistributionManagement = new PrettiedDistributionManagement(v) implicit def enrichPrettiedExecution(v: Execution): PrettiedExecution = @@ -193,13 +237,15 @@ object MavenConverters { implicit def enrichConvertibleActivation(v: MavenActivation): ConvertibleMavenActivation = new ConvertibleMavenActivation(v) - implicit def enrichConvertibleActivationFile(v: MavenActivationFile): ConvertibleMavenActivationFile = + implicit def enrichConvertibleActivationFile(v: MavenActivationFile) + : ConvertibleMavenActivationFile = new ConvertibleMavenActivationFile(v) implicit def enrichConvertibleActivationOS(v: MavenActivationOS): ConvertibleMavenActivationOS = new ConvertibleMavenActivationOS(v) - implicit def enrichConvertibleActivationProperty(v: MavenActivationProperty): ConvertibleMavenActivationProperty = + implicit def enrichConvertibleActivationProperty(v: MavenActivationProperty) + : ConvertibleMavenActivationProperty = new ConvertibleMavenActivationProperty(v) implicit def enrichConvertibleBuild(v: MavenBuild): ConvertibleMavenBuild = @@ -220,16 +266,19 @@ object MavenConverters { implicit def enrichConvertibleDependency(v: MavenDependency): ConvertibleMavenDependency = new ConvertibleMavenDependency(v) - implicit def enrichConvertibleDependencyManagement(v: MavenDependencyManagement): ConvertibleMavenDependencyManagement = + implicit def enrichConvertibleDependencyManagement(v: MavenDependencyManagement) + : ConvertibleMavenDependencyManagement = new ConvertibleMavenDependencyManagement(v) - implicit def enrichConvertibleDeploymentRepository(v: MavenDeploymentRepository): ConvertibleMavenDeploymentRepository = + implicit def enrichConvertibleDeploymentRepository(v: MavenDeploymentRepository) + : ConvertibleMavenDeploymentRepository = new ConvertibleMavenDeploymentRepository(v) implicit def enrichConvertibleDeveloper(v: MavenDeveloper): ConvertibleMavenDeveloper = new ConvertibleMavenDeveloper(v) - implicit def enrichConvertibleDistributionManagement(v: MavenDistributionManagement): ConvertibleMavenDistributionManagement = + implicit def enrichConvertibleDistributionManagement(v: MavenDistributionManagement) + : ConvertibleMavenDistributionManagement = new ConvertibleMavenDistributionManagement(v) implicit def enrichConvertibleExecution(v: MavenExecution): ConvertibleMavenExecution = @@ -241,10 +290,12 @@ object MavenConverters { implicit def enrichConvertibleGav(v: (String, String, String)): ConvertibleMavenGav = new ConvertibleMavenGav(v) - implicit def enrichConvertibleGroupArtifactId(v: (String, String)): ConvertibleMavenGroupArtifactId = + implicit def enrichConvertibleGroupArtifactId(v: (String, String)) + : ConvertibleMavenGroupArtifactId = new ConvertibleMavenGroupArtifactId(v) - implicit def enrichConvertibleIssueManagement(v: MavenIssueManagement): ConvertibleMavenIssueManagement = + implicit def enrichConvertibleIssueManagement(v: MavenIssueManagement) + : ConvertibleMavenIssueManagement = new ConvertibleMavenIssueManagement(v) implicit def enrichConvertibleLicense(v: MavenLicense): ConvertibleMavenLicense = @@ -268,10 +319,12 @@ object MavenConverters { implicit def enrichConvertiblePlugin(v: MavenPlugin): ConvertibleMavenPlugin = new ConvertibleMavenPlugin(v) - implicit def enrichConvertiblePluginManagement(v: MavenPluginManagement): ConvertibleMavenPluginManagement = + implicit def enrichConvertiblePluginManagement(v: MavenPluginManagement) + : ConvertibleMavenPluginManagement = new ConvertibleMavenPluginManagement(v) - implicit def enrichConvertiblePrerequisites(v: MavenPrerequisites): ConvertibleMavenPrerequisites = + implicit def enrichConvertiblePrerequisites(v: MavenPrerequisites) + : ConvertibleMavenPrerequisites = new ConvertibleMavenPrerequisites(v) implicit def enrichConvertibleProfile(v: MavenProfile): ConvertibleMavenProfile = @@ -280,7 +333,8 @@ object MavenConverters { implicit def enrichConvertibleRelocation(v: MavenRelocation): ConvertibleMavenRelocation = new ConvertibleMavenRelocation(v) - implicit def enrichConvertibleRepositoryPolicy(v: MavenRepositoryPolicy): ConvertibleMavenRepositoryPolicy = + implicit def enrichConvertibleRepositoryPolicy(v: MavenRepositoryPolicy) + : ConvertibleMavenRepositoryPolicy = new ConvertibleMavenRepositoryPolicy(v) implicit def enrichConvertibleRepository(v: MavenRepository): ConvertibleMavenRepository = diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/eval/Eval.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/eval/Eval.scala index 53c247b2..223a31f8 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/eval/Eval.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/eval/Eval.scala @@ -40,7 +40,8 @@ object Eval { private val classCleaner: Regex = "\\W".r class CompilerException(val messages: List[List[String]]) extends Exception( - "Compiler exception " + messages.map(_.mkString("\n")).mkString("\n")) + "Compiler exception " + messages.map(_.mkString("\n")).mkString("\n") + ) trait MessageCollector { val messages: mutable.Seq[List[String]] @@ -70,19 +71,27 @@ object Eval { class Eval(target: Option[File]) { import Eval._ - private lazy val compilerPath = try { - classPathOfClass("scala.tools.nsc.Interpreter") - } catch { - case e: Throwable => - throw new RuntimeException("Unable to load Scala interpreter from classpath (scala-compiler jar is missing?)", e) - } + private lazy val compilerPath = + try { + classPathOfClass("scala.tools.nsc.Interpreter") + } catch { + case e: Throwable => + throw new RuntimeException( + "Unable to load Scala interpreter from classpath (scala-compiler jar is missing?)", + e + ) + } - private lazy val libPath = try { - classPathOfClass("scala.AnyVal") - } catch { - case e: Throwable => - throw new RuntimeException("Unable to load scala base object from classpath (scala-library jar is missing?)", e) - } + private lazy val libPath = + try { + classPathOfClass("scala.AnyVal") + } catch { + case e: Throwable => + throw new RuntimeException( + "Unable to load scala base object from classpath (scala-library jar is missing?)", + e + ) + } /** * Preprocessors to run the code through before it is passed to the Scala compiler. @@ -100,7 +109,7 @@ class Eval(target: Option[File]) { new FilesystemResolver(new File("." + File.separator + "config")) ) ++ Option(System.getProperty("com.twitter.util.Eval.includePath")) - .fold(Seq[Resolver]()){ path => + .fold(Seq[Resolver]()) { path => Seq[Resolver](new FilesystemResolver(new File(path))) } ) @@ -113,7 +122,8 @@ class Eval(target: Option[File]) { protected lazy val compilerSettings: Settings = new EvalSettings(target) // Primary encapsulation around native Scala compiler - private[this] lazy val compiler = new StringCompiler(codeWrapperLineOffset, target, compilerSettings, compilerMessageHandler) + private[this] lazy val compiler = + new StringCompiler(codeWrapperLineOffset, target, compilerSettings, compilerMessageHandler) /** * run preprocessors on our string, returning a String that is the processed source @@ -147,7 +157,9 @@ class Eval(target: Option[File]) { def apply[T](files: File*): T = { if (target.isDefined) { val targetDir = target.get - val unprocessedSource = files.map { f => Using.resource(Source.fromFile(f))(_.mkString) }.mkString("\n") + val unprocessedSource = files.map { f => + Using.resource(Source.fromFile(f))(_.mkString) + }.mkString("\n") val processed = sourceForString(unprocessedSource) val sourceChecksum = uniqueId(processed, None) val checksumFile = new File(targetDir, "checksum") @@ -169,10 +181,12 @@ class Eval(target: Option[File]) { // so, clean it hash it and slap it on the end of Evaluator val cleanBaseName = fileToClassName(files(0)) val className = "Evaluator__%s_%s".format( - cleanBaseName, sourceChecksum) + cleanBaseName, + sourceChecksum + ) applyProcessed(className, processed, resetState = false) } else { - apply(files.map {f => Using.resource(Source.fromFile(f))(_.mkString) }.mkString("\n"), true) + apply(files.map { f => Using.resource(Source.fromFile(f))(_.mkString) }.mkString("\n"), true) } } @@ -263,7 +277,9 @@ class Eval(target: Option[File]) { } def findClass(className: String): Class[_] = { - compiler.findClass(className).getOrElse { throw new ClassNotFoundException("no such class: " + className) } + compiler.findClass(className).getOrElse { + throw new ClassNotFoundException("no such class: " + className) + } } private[scala] def resetReporter(): Unit = { @@ -340,8 +356,10 @@ class Eval(target: Option[File]) { lazy val impliedClassPath: List[String] = { def getClassPath(cl: ClassLoader, acc: List[List[String]] = List.empty): List[List[String]] = { val cp = cl match { - case urlClassLoader: URLClassLoader => urlClassLoader.getURLs.filter(_.getProtocol == "file"). - map(u => new File(u.toURI).getPath).toList + case urlClassLoader: URLClassLoader => + urlClassLoader.getURLs.filter(_.getProtocol == "file").map(u => + new File(u.toURI).getPath + ).toList case _ => Nil } cl.getParent match { @@ -354,18 +372,24 @@ class Eval(target: Option[File]) { val currentClassPath = classPath.head // if there's just one thing in the classpath, and it's a jar, assume an executable jar. - currentClassPath ::: (if (currentClassPath.size == 1 && currentClassPath.head.endsWith(".jar")) { - val jarFile = currentClassPath.head - val relativeRoot = new File(jarFile).getParentFile() - val nestedClassPath = new JarFile(jarFile).getManifest.getMainAttributes.getValue("Class-Path") - if (nestedClassPath eq null) { - Nil - } else { - nestedClassPath.split(" ").map { f => new File(relativeRoot, f).getAbsolutePath }.toList - } - } else { - Nil - }) ::: classPath.tail.flatten + currentClassPath ::: (if ( + currentClassPath.size == 1 && currentClassPath.head.endsWith(".jar") + ) { + val jarFile = currentClassPath.head + val relativeRoot = new File(jarFile).getParentFile() + val nestedClassPath = new JarFile( + jarFile + ).getManifest.getMainAttributes.getValue("Class-Path") + if (nestedClassPath eq null) { + Nil + } else { + nestedClassPath.split(" ").map { f => + new File(relativeRoot, f).getAbsolutePath + }.toList + } + } else { + Nil + }) ::: classPath.tail.flatten } trait Preprocessor { @@ -464,7 +488,11 @@ class Eval(target: Option[File]) { * around one of these and reuse it. */ private class StringCompiler( - lineOffset: Int, targetDir: Option[File], settings: Settings, messageHandler: Option[Reporter]) { + lineOffset: Int, + targetDir: Option[File], + settings: Settings, + messageHandler: Option[Reporter] + ) { val cache = new mutable.HashMap[String, Class[_]]() val target = compilerOutputDir @@ -476,15 +504,19 @@ class Eval(target: Option[File]) { ERROR -> new AtomicInteger(0), WARNING -> new AtomicInteger(0), INFO -> new AtomicInteger(0) - ) override def hasErrors: Boolean = super.hasErrors || (counts(ERROR).get() > 0) - override def doReport(pos: Position, msg: String, severity: Severity, actions: List[CodeAction]): Unit = { + override def doReport( + pos: Position, + msg: String, + severity: Severity, + actions: List[CodeAction] + ): Unit = { counts(severity).intValue() val severityName = severity match { - case ERROR => "error: " + case ERROR => "error: " case WARNING => "warning: " case _ => "" } @@ -497,12 +529,12 @@ class Eval(target: Option[File]) { } messages += (severityName + lineMessage + ": " + msg) :: (if (pos.isDefined) { - pos.finalPosition.lineContent.stripLineEnd :: - (" " * (pos.column - 1) + "^") :: - Nil - } else { - Nil - }) + pos.finalPosition.lineContent.stripLineEnd :: + (" " * (pos.column - 1) + "^") :: + Nil + } else { + Nil + }) } override def reset(): Unit = { @@ -580,7 +612,7 @@ class Eval(target: Option[File]) { if (Debug.enabled) Debug.printWithLineNumbers(code) - //reset reporter, or will always throw exception after one error while resetState==false + // reset reporter, or will always throw exception after one error while resetState==false resetReporter() // if you're looking for the performance hit, it's 1/2 this line... @@ -614,4 +646,4 @@ class Eval(target: Option[File]) { } } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Activation.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Activation.scala index 82fbfcee..6c7d0568 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Activation.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Activation.scala @@ -8,21 +8,21 @@ package org.sonatype.maven.polyglot.scala.model class Activation( - val activeByDefault: Boolean, - val jdk: Option[String], - val os: Option[ActivationOS], - val property: Option[ActivationProperty], - val file: Option[ActivationFile] - ) + val activeByDefault: Boolean, + val jdk: Option[String], + val os: Option[ActivationOS], + val property: Option[ActivationProperty], + val file: Option[ActivationFile] +) object Activation { def apply( - activeByDefault: Boolean = false, - jdk: String = null, - os: ActivationOS = null, - property: ActivationProperty = null, - file: ActivationFile = null - ) = + activeByDefault: Boolean = false, + jdk: String = null, + os: ActivationOS = null, + property: ActivationProperty = null, + file: ActivationFile = null + ) = new Activation( activeByDefault, Option(jdk), @@ -32,13 +32,14 @@ object Activation { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedActivation(p: Activation) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() - Option(p.activeByDefault).filterNot(_ == false).foreach(abd => args += assign("activeByDefault", abd.toString)) + Option(p.activeByDefault).filterNot(_ == false).foreach(abd => + args += assign("activeByDefault", abd.toString) + ) p.jdk.foreach(args += assignString("jdk", _)) p.os.foreach(os => args += assign("os", os.asDoc)) p.property.foreach(p => args += assign("property", p.asDoc)) @@ -47,7 +48,6 @@ class PrettiedActivation(p: Activation) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{Activation => MavenActivation} @@ -75,4 +75,4 @@ class ConvertibleScalaActivation(a: Activation) { ma.setProperty(a.property.map(_.asJava).orNull) ma } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationFile.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationFile.scala index 8f0c4150..ca00eb80 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationFile.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationFile.scala @@ -8,22 +8,21 @@ package org.sonatype.maven.polyglot.scala.model class ActivationFile( - val missing: Option[String], - val exists: Option[String] - ) + val missing: Option[String], + val exists: Option[String] +) object ActivationFile { def apply( - missing: String = null, - exists: String = null - ) = + missing: String = null, + exists: String = null + ) = new ActivationFile( Option(missing), Option(exists) ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedActivationFile(aFile: ActivationFile) { @@ -35,7 +34,6 @@ class PrettiedActivationFile(aFile: ActivationFile) { } } - import org.apache.maven.model.{ActivationFile => MavenActivationFile} class ConvertibleMavenActivationFile(maFile: MavenActivationFile) { @@ -54,4 +52,4 @@ class ConvertibleScalaActivationFile(aFile: ActivationFile) { maFile.setExists(aFile.exists.orNull) maFile } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationProperty.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationProperty.scala index 01a70777..b2b91deb 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationProperty.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivationProperty.scala @@ -8,22 +8,21 @@ package org.sonatype.maven.polyglot.scala.model class ActivationProperty( - val name: Option[String], - val value: Option[String] - ) + val name: Option[String], + val value: Option[String] +) object ActivationProperty { def apply( - name: String = null, - value: String = null - ) = + name: String = null, + value: String = null + ) = new ActivationProperty( Option(name), Option(value) ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedActivationProperty(ap: ActivationProperty) { @@ -35,7 +34,6 @@ class PrettiedActivationProperty(ap: ActivationProperty) { } } - import org.apache.maven.model.{ActivationProperty => MavenActivationProperty} class ConvertibleMavenActivationProperty(map: MavenActivationProperty) { @@ -54,4 +52,4 @@ class ConvertibleScalaActivationProperty(ap: ActivationProperty) { map.setValue(ap.value.orNull) map } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivatorOS.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivatorOS.scala index 51d9a699..7278e1c4 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivatorOS.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ActivatorOS.scala @@ -8,19 +8,19 @@ package org.sonatype.maven.polyglot.scala.model class ActivationOS( - val name: Option[String], - val family: Option[String], - val arch: Option[String], - val version: Option[String] - ) + val name: Option[String], + val family: Option[String], + val arch: Option[String], + val version: Option[String] +) object ActivationOS { def apply( - name: String = null, - family: String = null, - arch: String = null, - version: String = null - ) = + name: String = null, + family: String = null, + arch: String = null, + version: String = null + ) = new ActivationOS( Option(name), Option(family), @@ -29,7 +29,6 @@ object ActivationOS { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedActivationOS(aos: ActivationOS) { @@ -43,7 +42,6 @@ class PrettiedActivationOS(aos: ActivationOS) { } } - import org.apache.maven.model.{ActivationOS => MavenActivationOS} class ConvertibleMavenActivationOS(maos: MavenActivationOS) { @@ -66,4 +64,4 @@ class ConvertibleScalaActivationOS(aos: ActivationOS) { maos.setVersion(aos.version.orNull) maos } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Build.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Build.scala index 080e7a79..3d5de219 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Build.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Build.scala @@ -10,53 +10,51 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Build( - val sourceDirectory: Option[String], - val scriptSourceDirectory: Option[String], - val testSourceDirectory: Option[String], - val outputDirectory: Option[String], - val testOutputDirectory: Option[String], - val extensions: immutable.Seq[Extension], - defaultGoal: Option[String], - resources: immutable.Seq[Resource], - testResources: immutable.Seq[Resource], - directory: Option[String], - finalName: Option[String], - filters: immutable.Seq[String], - pluginManagement: Option[PluginManagement], - plugins: immutable.Seq[Plugin], - tasks: immutable.Seq[Task] - ) - extends - BuildBase( - defaultGoal, - resources, - testResources, - directory, - finalName, - filters, - pluginManagement, - plugins, - tasks - ) + val sourceDirectory: Option[String], + val scriptSourceDirectory: Option[String], + val testSourceDirectory: Option[String], + val outputDirectory: Option[String], + val testOutputDirectory: Option[String], + val extensions: immutable.Seq[Extension], + defaultGoal: Option[String], + resources: immutable.Seq[Resource], + testResources: immutable.Seq[Resource], + directory: Option[String], + finalName: Option[String], + filters: immutable.Seq[String], + pluginManagement: Option[PluginManagement], + plugins: immutable.Seq[Plugin], + tasks: immutable.Seq[Task] +) extends BuildBase( + defaultGoal, + resources, + testResources, + directory, + finalName, + filters, + pluginManagement, + plugins, + tasks + ) object Build { def apply( - sourceDirectory: String = null, - scriptSourceDirectory: String = null, - testSourceDirectory: String = null, - outputDirectory: String = null, - testOutputDirectory: String = null, - extensions: immutable.Seq[Extension] = Nil, - defaultGoal: String = null, - resources: immutable.Seq[Resource] = Nil, - testResources: immutable.Seq[Resource] = Nil, - directory: String = null, - finalName: String = null, - filters: immutable.Seq[String] = Nil, - pluginManagement: PluginManagement = null, - plugins: immutable.Seq[Plugin] = Nil, - tasks: immutable.Seq[Task] = Nil - ) = + sourceDirectory: String = null, + scriptSourceDirectory: String = null, + testSourceDirectory: String = null, + outputDirectory: String = null, + testOutputDirectory: String = null, + extensions: immutable.Seq[Extension] = Nil, + defaultGoal: String = null, + resources: immutable.Seq[Resource] = Nil, + testResources: immutable.Seq[Resource] = Nil, + directory: String = null, + finalName: String = null, + filters: immutable.Seq[String] = Nil, + pluginManagement: PluginManagement = null, + plugins: immutable.Seq[Plugin] = Nil, + tasks: immutable.Seq[Task] = Nil + ) = new Build( Option(sourceDirectory), Option(scriptSourceDirectory), @@ -76,7 +74,6 @@ object Build { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedBuild(b: Build) { @@ -87,13 +84,14 @@ class PrettiedBuild(b: Build) { b.testSourceDirectory.foreach(args += assignString("testSourceDirectory", _)) b.outputDirectory.foreach(args += assignString("outputDirectory", _)) b.testOutputDirectory.foreach(args += assignString("testOutputDirectory", _)) - Some(b.extensions).filterNot(_.isEmpty).foreach(es => args += assign("extensions", seq(es.map(_.asDoc)))) + Some(b.extensions).filterNot(_.isEmpty).foreach(es => + args += assign("extensions", seq(es.map(_.asDoc))) + ) args ++= b.asDocArgs `object`("Build", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Build => MavenBuild} @@ -140,4 +138,4 @@ class ConvertibleScalaBuild(b: Build) { mb.setTestResources(b.testResources.map(_.asJava).asJava) mb } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/BuildBase.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/BuildBase.scala index d103511a..2979a5cc 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/BuildBase.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/BuildBase.scala @@ -10,29 +10,29 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class BuildBase( - val defaultGoal: Option[String], - val resources: immutable.Seq[Resource], - val testResources: immutable.Seq[Resource], - val directory: Option[String], - val finalName: Option[String], - val filters: immutable.Seq[String], - val pluginManagement: Option[PluginManagement], - val plugins: immutable.Seq[Plugin], - val tasks: immutable.Seq[Task] - ) + val defaultGoal: Option[String], + val resources: immutable.Seq[Resource], + val testResources: immutable.Seq[Resource], + val directory: Option[String], + val finalName: Option[String], + val filters: immutable.Seq[String], + val pluginManagement: Option[PluginManagement], + val plugins: immutable.Seq[Plugin], + val tasks: immutable.Seq[Task] +) object BuildBase { def apply( - defaultGoal: String = null, - resources: immutable.Seq[Resource] = Nil, - testResources: immutable.Seq[Resource] = Nil, - directory: String = null, - finalName: String = null, - filters: immutable.Seq[String] = Nil, - pluginManagement: PluginManagement = null, - plugins: immutable.Seq[Plugin] = Nil, - tasks: immutable.Seq[Task] = Nil - ) = + defaultGoal: String = null, + resources: immutable.Seq[Resource] = Nil, + testResources: immutable.Seq[Resource] = Nil, + directory: String = null, + finalName: String = null, + filters: immutable.Seq[String] = Nil, + pluginManagement: PluginManagement = null, + plugins: immutable.Seq[Plugin] = Nil, + tasks: immutable.Seq[Task] = Nil + ) = new BuildBase( Option(defaultGoal), resources, @@ -46,7 +46,6 @@ object BuildBase { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedBuildBase(b: BuildBase) { @@ -57,19 +56,24 @@ class PrettiedBuildBase(b: BuildBase) { def asDocArgs: immutable.Seq[Doc] = { val args = scala.collection.mutable.ListBuffer[Doc]() b.defaultGoal.foreach(args += assignString("defaultGoal", _)) - Some(b.resources).filterNot(_.isEmpty).foreach(r => args += assign("resources", seq(r.map(_.asDoc)))) - Some(b.testResources).filterNot(_.isEmpty).foreach(trs => args += assign("testResources", seq(trs.map(_.asDoc)))) + Some(b.resources).filterNot(_.isEmpty).foreach(r => + args += assign("resources", seq(r.map(_.asDoc))) + ) + Some(b.testResources).filterNot(_.isEmpty).foreach(trs => + args += assign("testResources", seq(trs.map(_.asDoc))) + ) b.directory.foreach(args += assignString("directory", _)) b.finalName.foreach(args += assignString("finalName", _)) Some(b.filters).filterNot(_.isEmpty).foreach(f => args += assign("filters", seqString(f))) b.pluginManagement.foreach(pm => args += assign("pluginManagement", pm.asDoc)) - Some(b.plugins).filterNot(_.isEmpty).foreach(ps => args += assign("plugins", seq(ps.map(_.asDoc)))) + Some(b.plugins).filterNot(_.isEmpty).foreach(ps => + args += assign("plugins", seq(ps.map(_.asDoc))) + ) Some(b.tasks).filterNot(_.isEmpty).foreach(ps => args += assign("tasks", seq(ps.map(_.asDoc)))) args.toList } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{BuildBase => MavenBuildBase} @@ -104,4 +108,4 @@ class ConvertibleScalaBuildBase(b: BuildBase) { mb.setTestResources(b.testResources.map(_.asJava).asJava) mb } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/CiManagement.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/CiManagement.scala index 9084c23c..f28d1fe7 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/CiManagement.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/CiManagement.scala @@ -10,16 +10,17 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class CiManagement( - val notifiers: immutable.Seq[Notifier], - val system: Option[String], - val url: Option[String] - ) + val notifiers: immutable.Seq[Notifier], + val system: Option[String], + val url: Option[String] +) object CiManagement { def apply( - notifiers: immutable.Seq[Notifier] = Nil, - system: String = null, - url: String = null) = + notifiers: immutable.Seq[Notifier] = Nil, + system: String = null, + url: String = null + ) = new CiManagement( notifiers, Option(system), @@ -27,20 +28,20 @@ object CiManagement { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedCiManagement(c: CiManagement) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() - Some(c.notifiers).filterNot(_.isEmpty).foreach(n => args += assign("notifiers", seq(n.map(_.asDoc)))) + Some(c.notifiers).filterNot(_.isEmpty).foreach(n => + args += assign("notifiers", seq(n.map(_.asDoc))) + ) c.system.foreach(args += assignString("system", _)) c.url.foreach(args += assignString("url", _)) `object`("CiManagement", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{CiManagement => MavenCiManagement} @@ -65,4 +66,4 @@ class ConvertibleScalaCiManagement(cm: CiManagement) { mcm.setUrl(cm.url.orNull) mcm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Config.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Config.scala index 35a5dee8..f5224426 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Config.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Config.scala @@ -42,9 +42,9 @@ import scala.language.postfixOps * * * }}} - * */ class Config(val elements: immutable.Seq[(String, Option[Any])]) { + /** * Returns a new Config with contains the elements of this and the other config. */ @@ -62,7 +62,8 @@ object Config extends Dynamic { def applyDynamicNamed(method: String)(params: (String, Any)*): Config = if (method == "apply") new Config(params map { - case (k, Optional(v)) if k.startsWith("$at") && k.size > 3 => s"@${sanitizeElementName(k.substring(3))}" -> v + case (k, Optional(v)) if k.startsWith("$at") && k.size > 3 => + s"@${sanitizeElementName(k.substring(3))}" -> v case (k, Optional(v)) => sanitizeElementName(k) -> v } toList) else throw new UnsupportedOperationException @@ -86,7 +87,9 @@ object Config extends Dynamic { def sanitizeElementName(k: String): String = { val r = elementStartCharMapping.foldLeft(k)((k, m) => m._1.replaceAllIn(k, found => m._2)) if (r.length() > 1) { - r.substring(0, 1) + elementCharMapping.foldLeft(r.substring(1))((k, m) => m._1.replaceAllIn(k, found => m._2)) + r.substring(0, 1) + elementCharMapping.foldLeft(r.substring(1))((k, m) => + m._1.replaceAllIn(k, found => m._2) + ) } else r } } @@ -164,4 +167,4 @@ class ConvertibleScalaConfig(config: Config) { private val doc = addChildren(new Xpp3Dom("configuration"), config) def asJava: Xpp3Dom = doc -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ConfigurationContainer.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ConfigurationContainer.scala index b0e1386f..d6dfc954 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ConfigurationContainer.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ConfigurationContainer.scala @@ -8,9 +8,9 @@ package org.sonatype.maven.polyglot.scala.model abstract class ConfigurationContainer( - val inherited: Boolean, - val configuration: Option[Config] - ) + val inherited: Boolean, + val configuration: Option[Config] +) import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ @@ -23,4 +23,4 @@ class PrettiedConfigurationContainer(cc: ConfigurationContainer) { cc.configuration.foreach(c => args += assign("configuration", c.asDoc)) args.toList } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Contributor.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Contributor.scala index 9193b264..7461a0ba 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Contributor.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Contributor.scala @@ -10,25 +10,25 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Contributor( - val email: Option[String], - val name: Option[String], - val organization: Option[String], - val organizationUrl: Option[String], - val roles: immutable.Seq[String], - val timezone: Option[String], - val url: Option[String] - ) + val email: Option[String], + val name: Option[String], + val organization: Option[String], + val organizationUrl: Option[String], + val roles: immutable.Seq[String], + val timezone: Option[String], + val url: Option[String] +) object Contributor { def apply( - email: String = null, - name: String = null, - organization: String = null, - organizationUrl: String = null, - roles: immutable.Seq[String] = Nil, - timezone: String = null, - url: String = null - ) = + email: String = null, + name: String = null, + organization: String = null, + organizationUrl: String = null, + roles: immutable.Seq[String] = Nil, + timezone: String = null, + url: String = null + ) = new Contributor( Option(email), Option(name), @@ -40,7 +40,6 @@ object Contributor { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedContributor(c: Contributor) { @@ -59,7 +58,6 @@ class PrettiedContributor(c: Contributor) { } } - import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Contributor => MavenContributor} @@ -89,4 +87,4 @@ class ConvertibleScalaContributor(c: Contributor) { mc.setUrl(c.url.orNull) mc } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Dependency.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Dependency.scala index b86bea3d..c6764f6d 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Dependency.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Dependency.scala @@ -16,19 +16,21 @@ class Dependency( val scope: Option[String], val systemPath: Option[String], val exclusions: immutable.Seq[GroupArtifactId], - val optional: Boolean) { + val optional: Boolean +) { /** * Returns a derived dependency with the given new properties. */ def copy( - gav: Gav = gav, - `type`: String = `type`, - classifier: Option[String] = this.classifier, - scope: Option[String] = this.scope, - systemPath: Option[String] = this.systemPath, - exclusions: immutable.Seq[GroupArtifactId] = exclusions, - optional: Boolean = optional): Dependency = + gav: Gav = gav, + `type`: String = `type`, + classifier: Option[String] = this.classifier, + scope: Option[String] = this.scope, + systemPath: Option[String] = this.systemPath, + exclusions: immutable.Seq[GroupArtifactId] = exclusions, + optional: Boolean = optional + ): Dependency = new Dependency(gav, `type`, classifier, scope, systemPath, exclusions, optional) /** @@ -41,7 +43,7 @@ class Dependency( * This is internally done by setting an universal exclusion (`"*" % "*"`). */ def intransitive: Dependency = copy(exclusions = immutable.Seq("*" % "*")) - + /** * Returns a derived dependency with the given scope. */ @@ -51,14 +53,14 @@ class Dependency( object Dependency { def apply( - gav: Gav, - `type`: String = "jar", - classifier: String = null, - scope: String = null, - systemPath: String = null, - exclusions: immutable.Seq[GroupArtifactId] = immutable.Seq.empty, - optional: Boolean = false - ) = + gav: Gav, + `type`: String = "jar", + classifier: String = null, + scope: String = null, + systemPath: String = null, + exclusions: immutable.Seq[GroupArtifactId] = immutable.Seq.empty, + optional: Boolean = false + ) = new Dependency( gav, `type`, @@ -70,7 +72,6 @@ object Dependency { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedDependency(d: Dependency) { @@ -80,7 +81,9 @@ class PrettiedDependency(d: Dependency) { val systemPathAssigned = d.systemPath.isDefined val exclusionsAssigned = d.exclusions.nonEmpty val optionalAssigned = d.optional - if (typeAssigned || classifierAssigned || systemPathAssigned || exclusionsAssigned || optionalAssigned) { + if ( + typeAssigned || classifierAssigned || systemPathAssigned || exclusionsAssigned || optionalAssigned + ) { val args = scala.collection.mutable.ListBuffer(d.gav.asDoc) if (typeAssigned) args += assignString("`type`", d.`type`) d.classifier.foreach(args += assignString("classifier", _)) @@ -97,7 +100,6 @@ class PrettiedDependency(d: Dependency) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Dependency => MavenDependency, Exclusion => MavenExclusion} @@ -136,4 +138,4 @@ class ConvertibleScalaDependency(d: Dependency) { md.setVersion(d.gav.version.orNull) md } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DependencyManagement.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DependencyManagement.scala index 77822d6a..91583176 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DependencyManagement.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DependencyManagement.scala @@ -21,15 +21,19 @@ import java.util class PrettiedDependencyManagement(dm: DependencyManagement) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() - Some(dm.dependencies).filterNot(_.isEmpty).foreach(ps => args += assign("dependencies", seq(ps.map(_.asDoc)))) + Some(dm.dependencies).filterNot(_.isEmpty).foreach(ps => + args += assign("dependencies", seq(ps.map(_.asDoc))) + ) `object`("DependencyManagement", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ -import org.apache.maven.model.{Dependency => MavenDependency, DependencyManagement => MavenDependencyManagement} +import org.apache.maven.model.{ + Dependency => MavenDependency, + DependencyManagement => MavenDependencyManagement +} class ConvertibleMavenDependencyManagement(mdm: MavenDependencyManagement) { def asScala: DependencyManagement = { @@ -50,4 +54,4 @@ class ConvertibleScalaDependencyManagement(dm: DependencyManagement) { mdm.setDependencies(new util.ArrayList[MavenDependency](dm.dependencies.map(_.asJava).asJava)) mdm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DeploymentRepository.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DeploymentRepository.scala index e9cf42ac..77f79dc3 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DeploymentRepository.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DeploymentRepository.scala @@ -8,34 +8,32 @@ package org.sonatype.maven.polyglot.scala.model class DeploymentRepository( - val uniqueVersion: Boolean, - override val releases: Option[RepositoryPolicy], - override val snapshots: Option[RepositoryPolicy], - override val id: Option[String], - override val name: Option[String], - override val url: Option[String], - override val layout: String - ) - extends - Repository( - releases, - snapshots, - id, - name, - url, - layout - ) + val uniqueVersion: Boolean, + override val releases: Option[RepositoryPolicy], + override val snapshots: Option[RepositoryPolicy], + override val id: Option[String], + override val name: Option[String], + override val url: Option[String], + override val layout: String +) extends Repository( + releases, + snapshots, + id, + name, + url, + layout + ) object DeploymentRepository { def apply( - uniqueVersion: Boolean = true, - releases: RepositoryPolicy = null, - snapshots: RepositoryPolicy = null, - id: String = null, - name: String = null, - url: String = null, - layout: String = "default" - ) = + uniqueVersion: Boolean = true, + releases: RepositoryPolicy = null, + snapshots: RepositoryPolicy = null, + id: String = null, + name: String = null, + url: String = null, + layout: String = "default" + ) = new DeploymentRepository( uniqueVersion, Option(releases), @@ -47,19 +45,19 @@ object DeploymentRepository { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedDeploymentRepository(dr: DeploymentRepository) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() - Option(dr.uniqueVersion).filterNot(_ == true).foreach(uv => args += assign("uniqueVersion", uv.toString)) + Option(dr.uniqueVersion).filterNot(_ == true).foreach(uv => + args += assign("uniqueVersion", uv.toString) + ) args ++= dr.asInstanceOf[Repository].asDocArgs `object`("DeploymentRepository", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{DeploymentRepository => MavenDeploymentRepository} @@ -91,4 +89,4 @@ class ConvertibleScalaDeploymentRepository(dr: DeploymentRepository) { mdr.setLayout(dr.layout) mdr } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Developer.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Developer.scala index 7fcdd554..a09cb393 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Developer.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Developer.scala @@ -10,37 +10,35 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Developer( - val id: Option[String], - override val email: Option[String], - override val name: Option[String], - override val organization: Option[String], - override val organizationUrl: Option[String], - override val roles: immutable.Seq[String], - override val timezone: Option[String], - override val url: Option[String] - ) - extends - Contributor( - email, - name, - organization, - organizationUrl, - roles, - timezone, - url - ) + val id: Option[String], + override val email: Option[String], + override val name: Option[String], + override val organization: Option[String], + override val organizationUrl: Option[String], + override val roles: immutable.Seq[String], + override val timezone: Option[String], + override val url: Option[String] +) extends Contributor( + email, + name, + organization, + organizationUrl, + roles, + timezone, + url + ) object Developer { def apply( - id: String = null, - email: String = null, - name: String = null, - organization: String = null, - organizationUrl: String = null, - roles: immutable.Seq[String] = Nil, - timezone: String = null, - url: String = null - ): Developer = + id: String = null, + email: String = null, + name: String = null, + organization: String = null, + organizationUrl: String = null, + roles: immutable.Seq[String] = Nil, + timezone: String = null, + url: String = null + ): Developer = new Developer( Option(id), Option(email), @@ -53,7 +51,6 @@ object Developer { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedDeveloper(d: Developer) { @@ -65,7 +62,6 @@ class PrettiedDeveloper(d: Developer) { } } - import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Developer => MavenDeveloper} @@ -97,4 +93,4 @@ class ConvertibleScalaDeveloper(d: Developer) { md.setUrl(d.url.orNull) md } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DistributionManagement.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DistributionManagement.scala index 03c69f72..edf37126 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DistributionManagement.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/DistributionManagement.scala @@ -8,23 +8,23 @@ package org.sonatype.maven.polyglot.scala.model class DistributionManagement( - val repository: Option[DeploymentRepository], - val snapshotRepository: Option[DeploymentRepository], - val site: Option[Site], - val downloadUrl: Option[String], - val relocation: Option[Relocation], - val status: Option[String] - ) + val repository: Option[DeploymentRepository], + val snapshotRepository: Option[DeploymentRepository], + val site: Option[Site], + val downloadUrl: Option[String], + val relocation: Option[Relocation], + val status: Option[String] +) object DistributionManagement { def apply( - repository: DeploymentRepository = null, - snapshotRepository: DeploymentRepository = null, - site: Site = null, - downloadUrl: String = null, - relocation: Relocation = null, - status: String = null - ): DistributionManagement = + repository: DeploymentRepository = null, + snapshotRepository: DeploymentRepository = null, + site: Site = null, + downloadUrl: String = null, + relocation: Relocation = null, + status: String = null + ): DistributionManagement = new DistributionManagement( Option(repository), Option(snapshotRepository), @@ -35,7 +35,6 @@ object DistributionManagement { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedDistributionManagement(dm: DistributionManagement) { @@ -51,7 +50,6 @@ class PrettiedDistributionManagement(dm: DistributionManagement) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{DistributionManagement => MavenDistributionManagement} @@ -81,4 +79,4 @@ class ConvertibleScalaDistributionManagement(dm: DistributionManagement) { mdm.setStatus(dm.status.orNull) mdm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Execution.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Execution.scala index 419c38d7..2dff181a 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Execution.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Execution.scala @@ -10,21 +10,21 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Execution( - val id: String, - val phase: Option[String], - val goals: immutable.Seq[String], - override val inherited: Boolean, - override val configuration: Option[Config] - ) extends ConfigurationContainer(inherited, configuration) + val id: String, + val phase: Option[String], + val goals: immutable.Seq[String], + override val inherited: Boolean, + override val configuration: Option[Config] +) extends ConfigurationContainer(inherited, configuration) object Execution { def apply( - id: String = "default", - phase: String = null, - goals: immutable.Seq[String] = immutable.Seq.empty, - inherited: Boolean = true, - configuration: Config = null - ): Execution = { + id: String = "default", + phase: String = null, + goals: immutable.Seq[String] = immutable.Seq.empty, + inherited: Boolean = true, + configuration: Config = null + ): Execution = { new Execution( id, Option(phase), @@ -35,7 +35,6 @@ object Execution { } } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedExecution(e: Execution) { @@ -49,7 +48,6 @@ class PrettiedExecution(e: Execution) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{PluginExecution => MavenExecution} @@ -78,4 +76,4 @@ class ConvertibleScalaExecution(e: Execution) { me.setInherited(e.inherited) me } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Extension.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Extension.scala index 6154a831..3f70e7c6 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Extension.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Extension.scala @@ -13,7 +13,6 @@ object Extension { def apply(gav: Gav) = new Extension(gav) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedExtension(e: Extension) { @@ -23,7 +22,6 @@ class PrettiedExtension(e: Extension) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{Extension => MavenExtension} @@ -43,4 +41,4 @@ class ConvertibleScalaExtension(e: Extension) { me.setVersion(e.gav.version.orNull) me } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Gav.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Gav.scala index 34cdef12..08b12c1f 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Gav.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Gav.scala @@ -17,6 +17,7 @@ case class GroupId(groupId: Option[String]) { } object GroupId { + /** * Group ids are optional and when specified with just "" then they are to be treated as None. */ @@ -46,14 +47,18 @@ case class Gav(private val groupArtifactIdObj: GroupArtifactId, version: Option[ } object Gav { + /** * Versions are optional and when specified with just "" then they are to be treated as None. */ def apply(groupArtifactIdObj: GroupArtifactId, version: String): Gav = { - Gav(groupArtifactIdObj, Option(version).flatMap({ - case v if v.isEmpty => None - case v => Some(v) - })) + Gav( + groupArtifactIdObj, + Option(version).flatMap({ + case v if v.isEmpty => None + case v => Some(v) + }) + ) } } @@ -67,11 +72,12 @@ class PrettiedGroupArtifactId(ga: GroupArtifactId) { class PrettiedGav(gav: Gav) { def asDoc: Doc = { - dquotes(gav.groupId.getOrElse[String]("")) <+> percent <+> dquotes(gav.artifactId) <> gav.version.map(space <> percent <+> dquotes(_)).getOrElse(emptyDoc) + dquotes(gav.groupId.getOrElse[String]("")) <+> percent <+> dquotes( + gav.artifactId + ) <> gav.version.map(space <> percent <+> dquotes(_)).getOrElse(emptyDoc) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ class ConvertibleMavenGroupArtifactId(mga: (String, String)) { @@ -85,4 +91,4 @@ class ConvertibleMavenGav(mgav: (String, String, String)) { val ga = (mgav._1, mgav._2).asScala Gav(ga, Option(mgav._3)) } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/IssueManagement.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/IssueManagement.scala index 8b61446a..82b11c42 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/IssueManagement.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/IssueManagement.scala @@ -8,15 +8,15 @@ package org.sonatype.maven.polyglot.scala.model class IssueManagement( - val system: Option[String], - val url: Option[String] - ) + val system: Option[String], + val url: Option[String] +) object IssueManagement { def apply( - system: String = null, - url: String = null - ): IssueManagement = + system: String = null, + url: String = null + ): IssueManagement = new IssueManagement( Option(system), Option(url) @@ -34,7 +34,6 @@ class PrettiedIssueManagement(im: IssueManagement) { } } - import org.apache.maven.model.{IssueManagement => MavenIssueManagement} class ConvertibleMavenIssueManagement(mim: MavenIssueManagement) { @@ -53,4 +52,4 @@ class ConvertibleScalaIssueManagement(im: IssueManagement) { mim.setUrl(im.url.orNull) mim } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/License.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/License.scala index 83773c32..0b646ed6 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/License.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/License.scala @@ -8,19 +8,19 @@ package org.sonatype.maven.polyglot.scala.model class License( - val name: Option[String], - val url: Option[String], - val distribution: Option[String], - val comments: Option[String] - ) + val name: Option[String], + val url: Option[String], + val distribution: Option[String], + val comments: Option[String] +) object License { def apply( - name: String = null, - url: String = null, - distribution: String = null, - comments: String = null - ): License = + name: String = null, + url: String = null, + distribution: String = null, + comments: String = null + ): License = new License( Option(name), Option(url), @@ -42,7 +42,6 @@ class PrettiedLicense(im: License) { } } - import org.apache.maven.model.{License => MavenLicense} class ConvertibleMavenLicense(mim: MavenLicense) { @@ -65,4 +64,4 @@ class ConvertibleScalaLicense(im: License) { mim.setComments(im.comments.orNull) mim } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/MailingList.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/MailingList.scala index dcaf9418..1d0c0074 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/MailingList.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/MailingList.scala @@ -10,23 +10,23 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class MailingList( - val name: Option[String], - val subscribe: Option[String], - val unsubscribe: Option[String], - val post: Option[String], - val archive: Option[String], - val otherArchives: immutable.Seq[String] - ) + val name: Option[String], + val subscribe: Option[String], + val unsubscribe: Option[String], + val post: Option[String], + val archive: Option[String], + val otherArchives: immutable.Seq[String] +) object MailingList { def apply( - name: String = null, - subscribe: String = null, - unsubscribe: String = null, - post: String = null, - archive: String = null, - otherArchives: immutable.Seq[String] = Nil - ): MailingList = + name: String = null, + subscribe: String = null, + unsubscribe: String = null, + post: String = null, + archive: String = null, + otherArchives: immutable.Seq[String] = Nil + ): MailingList = new MailingList( Option(name), Option(subscribe), @@ -47,12 +47,13 @@ class PrettiedMailingList(ml: MailingList) { ml.unsubscribe.foreach(args += assignString("unsubscribe", _)) ml.post.foreach(args += assignString("post", _)) ml.archive.foreach(args += assignString("archive", _)) - Some(ml.otherArchives).filterNot(_.isEmpty).foreach(ds => args += assign("otherArchives", seqString(ds))) + Some(ml.otherArchives).filterNot(_.isEmpty).foreach(ds => + args += assign("otherArchives", seqString(ds)) + ) `object`("MailingList", args.toList) } } - import org.apache.maven.model.{MailingList => MavenMailingList} import scala.jdk.CollectionConverters._ @@ -80,4 +81,4 @@ class ConvertibleScalaMailingList(ml: MailingList) { mml.setUnsubscribe(ml.unsubscribe.orNull) mml } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Model.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Model.scala index 21b98833..9566585d 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Model.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Model.scala @@ -10,36 +10,36 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Model( - val gav: Gav, - val build: Option[Build], - val ciManagement: Option[CiManagement], - val contributors: immutable.Seq[Contributor], - dependencyManagement: Option[DependencyManagement], - dependencies: immutable.Seq[Dependency], - val description: Option[String], - val developers: immutable.Seq[Developer], - distributionManagement: Option[DistributionManagement], - val inceptionYear: Option[String], - val issueManagement: Option[IssueManagement], - val licenses: immutable.Seq[License], - val mailingLists: immutable.Seq[MailingList], - val modelEncoding: String, - val modelVersion: Option[String], - modules: immutable.Seq[String], - val name: Option[String], - val organization: Option[Organization], - val packaging: String, - val parent: Option[Parent], - pluginRepositories: immutable.Seq[Repository], - val pomFile: Option[File], - val prerequisites: Option[Prerequisites], - val profiles: immutable.Seq[Profile], - val properties: Map[String, String], - val reporting: Option[Reporting], - repositories: immutable.Seq[Repository], - val scm: Option[Scm], - val url: Option[String]) - extends ModelBase( + val gav: Gav, + val build: Option[Build], + val ciManagement: Option[CiManagement], + val contributors: immutable.Seq[Contributor], + dependencyManagement: Option[DependencyManagement], + dependencies: immutable.Seq[Dependency], + val description: Option[String], + val developers: immutable.Seq[Developer], + distributionManagement: Option[DistributionManagement], + val inceptionYear: Option[String], + val issueManagement: Option[IssueManagement], + val licenses: immutable.Seq[License], + val mailingLists: immutable.Seq[MailingList], + val modelEncoding: String, + val modelVersion: Option[String], + modules: immutable.Seq[String], + val name: Option[String], + val organization: Option[Organization], + val packaging: String, + val parent: Option[Parent], + pluginRepositories: immutable.Seq[Repository], + val pomFile: Option[File], + val prerequisites: Option[Prerequisites], + val profiles: immutable.Seq[Profile], + val properties: Map[String, String], + val reporting: Option[Reporting], + repositories: immutable.Seq[Repository], + val scm: Option[Scm], + val url: Option[String] +) extends ModelBase( dependencyManagement, dependencies, distributionManagement, @@ -83,35 +83,36 @@ class Model( object Model { def apply( - gav: Gav, - build: Build = null, - ciManagement: CiManagement = null, - contributors: immutable.Seq[Contributor] = Nil, - dependencyManagement: DependencyManagement = null, - dependencies: immutable.Seq[Dependency] = Nil, - description: String = null, - developers: immutable.Seq[Developer] = Nil, - distributionManagement: DistributionManagement = null, - inceptionYear: String = null, - issueManagement: IssueManagement = null, - licenses: immutable.Seq[License] = Nil, - mailingLists: immutable.Seq[MailingList] = Nil, - modelEncoding: String = "UTF-8", - modelVersion: String = "4.0.0", - modules: immutable.Seq[String] = Nil, - name: String = null, - organization: Organization = null, - packaging: String = "jar", - parent: Parent = null, - pluginRepositories: immutable.Seq[Repository] = Nil, - pomFile: File = null, - prerequisites: Prerequisites = null, - profiles: immutable.Seq[Profile] = Nil, - properties: Map[String, String] = Map.empty, - reporting: Reporting = null, - repositories: immutable.Seq[Repository] = Nil, - scm: Scm = null, - url: String = null) = + gav: Gav, + build: Build = null, + ciManagement: CiManagement = null, + contributors: immutable.Seq[Contributor] = Nil, + dependencyManagement: DependencyManagement = null, + dependencies: immutable.Seq[Dependency] = Nil, + description: String = null, + developers: immutable.Seq[Developer] = Nil, + distributionManagement: DistributionManagement = null, + inceptionYear: String = null, + issueManagement: IssueManagement = null, + licenses: immutable.Seq[License] = Nil, + mailingLists: immutable.Seq[MailingList] = Nil, + modelEncoding: String = "UTF-8", + modelVersion: String = "4.0.0", + modules: immutable.Seq[String] = Nil, + name: String = null, + organization: Organization = null, + packaging: String = "jar", + parent: Parent = null, + pluginRepositories: immutable.Seq[Repository] = Nil, + pomFile: File = null, + prerequisites: Prerequisites = null, + profiles: immutable.Seq[Profile] = Nil, + properties: Map[String, String] = Map.empty, + reporting: Reporting = null, + repositories: immutable.Seq[Repository] = Nil, + scm: Scm = null, + url: String = null + ) = new Model( gav, Option(build), @@ -158,10 +159,18 @@ class PrettiedModel(m: Model) { m.issueManagement.foreach(im => args += assign("issueManagement", im.asDoc)) m.ciManagement.foreach(ci => args += assign("ciManagement", ci.asDoc)) m.inceptionYear.foreach(args += assignString("inceptionYear", _)) - Some(m.mailingLists).filterNot(_.isEmpty).foreach(ds => args += assign("mailingLists", seq(ds.map(_.asDoc)))) - Some(m.developers).filterNot(_.isEmpty).foreach(ds => args += assign("developers", seq(ds.map(_.asDoc)))) - Some(m.contributors).filterNot(_.isEmpty).foreach(cs => args += assign("contributors", seq(cs.map(_.asDoc)))) - Some(m.licenses).filterNot(_.isEmpty).foreach(ls => args += assign("licenses", seq(ls.map(_.asDoc)))) + Some(m.mailingLists).filterNot(_.isEmpty).foreach(ds => + args += assign("mailingLists", seq(ds.map(_.asDoc))) + ) + Some(m.developers).filterNot(_.isEmpty).foreach(ds => + args += assign("developers", seq(ds.map(_.asDoc))) + ) + Some(m.contributors).filterNot(_.isEmpty).foreach(cs => + args += assign("contributors", seq(cs.map(_.asDoc))) + ) + Some(m.licenses).filterNot(_.isEmpty).foreach(ls => + args += assign("licenses", seq(ls.map(_.asDoc))) + ) m.scm.foreach(ps => args += assign("scm", ps.asDoc)) m.organization.foreach(o => args += assign("organization", o.asDoc)) m.parent.foreach(p => args += assign("parent", p.asDoc)) @@ -169,7 +178,9 @@ class PrettiedModel(m: Model) { Some(m.properties).filterNot(_.isEmpty).foreach(ps => args += assign("properties", ps.asDoc)) m.build.foreach(b => args += assign("build", b.asDoc)) m.reporting.foreach(r => args += assign("reporting", r.asDoc)) - Some(m.profiles).filterNot(_.isEmpty).foreach(ps => args += assign("profiles", seq(ps.map(_.asDoc)))) + Some(m.profiles).filterNot(_.isEmpty).foreach(ps => + args += assign("profiles", seq(ps.map(_.asDoc))) + ) Some(m.modelEncoding).filterNot(_ == "UTF-8").foreach(args += assignString("modelEncoding", _)) m.modelVersion.foreach(args += assignString("modelVersion", _)) `object`("Model", args.toList) @@ -178,7 +189,7 @@ class PrettiedModel(m: Model) { import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ -import org.apache.maven.model.{ Model => MavenModel } +import org.apache.maven.model.{Model => MavenModel} class ConvertibleMavenModel(mm: MavenModel) { def asScala: Model = { @@ -248,9 +259,9 @@ class ConvertibleScalaModel(m: Model) { mm.setPrerequisites(m.prerequisites.map(_.asJava).orNull) mm.setProfiles(m.profiles.map(_.asJava).asJava) mm.setProperties(Option(m.properties).map { m => - val p = new Properties - m.foreach { case (k, v) => p.setProperty(k, v) } - p + val p = new Properties + m.foreach { case (k, v) => p.setProperty(k, v) } + p }.orNull) mm.setReporting(m.reporting.map(_.asJava).orNull) mm.setRepositories(m.repositories.map(_.asJava).asJava) @@ -259,4 +270,4 @@ class ConvertibleScalaModel(m: Model) { mm.setVersion(m.gav.version.orNull) mm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ModelBase.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ModelBase.scala index af3d48e1..a26971bd 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ModelBase.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ModelBase.scala @@ -10,14 +10,13 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable abstract class ModelBase( - val dependencyManagement: Option[DependencyManagement], - val dependencies: immutable.Seq[Dependency], - val distributionManagement: Option[DistributionManagement], - val modules: immutable.Seq[String], - val pluginRepositories: immutable.Seq[Repository], - val repositories: immutable.Seq[Repository] - ) - + val dependencyManagement: Option[DependencyManagement], + val dependencies: immutable.Seq[Dependency], + val distributionManagement: Option[DistributionManagement], + val modules: immutable.Seq[String], + val pluginRepositories: immutable.Seq[Repository], + val repositories: immutable.Seq[Repository] +) import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ @@ -25,9 +24,15 @@ class PrettiedModelBase(m: ModelBase) { def asDocArgs: immutable.Seq[Doc] = { val args = scala.collection.mutable.ListBuffer[Doc]() Some(m.modules).filterNot(_.isEmpty).foreach(m => args += assign("modules", seqString(m))) - Some(m.repositories).filterNot(_.isEmpty).foreach(es => args += assign("repositories", seq(es.map(_.asDoc)))) - Some(m.pluginRepositories).filterNot(_.isEmpty).foreach(es => args += assign("pluginRepositories", seq(es.map(_.asDoc)))) - Some(m.dependencies).filterNot(_.isEmpty).foreach(es => args += assign("dependencies", seq(es.map(_.asDoc)))) + Some(m.repositories).filterNot(_.isEmpty).foreach(es => + args += assign("repositories", seq(es.map(_.asDoc))) + ) + Some(m.pluginRepositories).filterNot(_.isEmpty).foreach(es => + args += assign("pluginRepositories", seq(es.map(_.asDoc))) + ) + Some(m.dependencies).filterNot(_.isEmpty).foreach(es => + args += assign("dependencies", seq(es.map(_.asDoc))) + ) m.dependencyManagement.foreach(dm => args += assign("dependencyManagement", dm.asDoc)) m.distributionManagement.foreach(dm => args += assign("distributionManagement", dm.asDoc)) args.toList diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Notifier.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Notifier.scala index 15ed42e5..2234cbe5 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Notifier.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Notifier.scala @@ -8,25 +8,25 @@ package org.sonatype.maven.polyglot.scala.model class Notifier( - val address: Option[String], - val configuration: Map[String, String], - val sendOnError: Boolean, - val sendOnFailure: Boolean, - val sendOnSuccess: Boolean, - val sendOnWarning: Boolean, - val `type`: String - ) + val address: Option[String], + val configuration: Map[String, String], + val sendOnError: Boolean, + val sendOnFailure: Boolean, + val sendOnSuccess: Boolean, + val sendOnWarning: Boolean, + val `type`: String +) object Notifier { def apply( - address: String = null, - configuration: Map[String, String] = Map.empty, - sendOnError: Boolean = true, - sendOnFailure: Boolean = true, - sendOnSuccess: Boolean = true, - sendOnWarning: Boolean = true, - `type`: String = "mail" - ) = + address: String = null, + configuration: Map[String, String] = Map.empty, + sendOnError: Boolean = true, + sendOnFailure: Boolean = true, + sendOnSuccess: Boolean = true, + sendOnWarning: Boolean = true, + `type`: String = "mail" + ) = new Notifier( Option(address), configuration, @@ -38,24 +38,30 @@ object Notifier { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedNotifier(n: Notifier) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() n.address.foreach(args += assignString("address", _)) - Some(n.configuration).filterNot(_.isEmpty).foreach(c => args += assign("configuration", c.asDoc)) + Some(n.configuration).filterNot(_.isEmpty).foreach(c => + args += assign("configuration", c.asDoc) + ) Some(n.sendOnError).filterNot(_ == true).foreach(e => args += assign("sendOnError", e.toString)) - Some(n.sendOnFailure).filterNot(_ == true).foreach(e => args += assign("sendOnFailure", e.toString)) - Some(n.sendOnSuccess).filterNot(_ == true).foreach(e => args += assign("sendOnSuccess", e.toString)) - Some(n.sendOnWarning).filterNot(_ == true).foreach(e => args += assign("sendOnWarning", e.toString)) + Some(n.sendOnFailure).filterNot(_ == true).foreach(e => + args += assign("sendOnFailure", e.toString) + ) + Some(n.sendOnSuccess).filterNot(_ == true).foreach(e => + args += assign("sendOnSuccess", e.toString) + ) + Some(n.sendOnWarning).filterNot(_ == true).foreach(e => + args += assign("sendOnWarning", e.toString) + ) Some(n.`type`).filterNot(_ == "mail").foreach(args += assignString("`type`", _)) `object`("Notifier", args.toList) } } - import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Notifier => MavenNotifier} @@ -80,9 +86,9 @@ class ConvertibleScalaNotifier(n: Notifier) { val mn = new MavenNotifier mn.setAddress(n.address.orNull) mn.setConfiguration(Option(n.configuration).map { c => - val p = new Properties - c.foreach { case (k, v) => p.setProperty(k, v) } - p + val p = new Properties + c.foreach { case (k, v) => p.setProperty(k, v) } + p }.orNull[Properties]) mn.setSendOnError(n.sendOnError) mn.setSendOnFailure(n.sendOnFailure) @@ -91,4 +97,4 @@ class ConvertibleScalaNotifier(n: Notifier) { mn.setType(n.`type`) mn } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Organization.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Organization.scala index 817f8a50..a5f4a4b0 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Organization.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Organization.scala @@ -8,15 +8,15 @@ package org.sonatype.maven.polyglot.scala.model class Organization( - val name: Option[String], - val url: Option[String] - ) + val name: Option[String], + val url: Option[String] +) object Organization { def apply( - name: String = null, - url: String = null - ): Organization = + name: String = null, + url: String = null + ): Organization = new Organization( Option(name), Option(url) @@ -34,7 +34,6 @@ class PrettiedOrganization(im: Organization) { } } - import org.apache.maven.model.{Organization => MavenOrganization} class ConvertibleMavenOrganization(mo: MavenOrganization) { @@ -53,4 +52,4 @@ class ConvertibleScalaOrganization(o: Organization) { mo.setUrl(o.url.orNull) mo } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Parent.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Parent.scala index 596674c3..ab0c6af3 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Parent.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Parent.scala @@ -8,41 +8,44 @@ package org.sonatype.maven.polyglot.scala.model class Parent( - val gav: Option[Gav], - val relativePath: String - ) + val gav: Option[Gav], + val relativePath: String +) object Parent { def apply( - gav: Gav = null, - relativePath: String = "../pom.xml" - ): Parent = + gav: Gav = null, + relativePath: String = "../pom.xml" + ): Parent = new Parent( Option(gav), relativePath ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedParent(p: Parent) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer[Doc]() p.gav.foreach(gav => args += assign("gav", gav.asDoc)) - Some(p.relativePath).filterNot(_ == "../pom.xml").foreach(args += assignString("relativePath", _)) + Some(p.relativePath).filterNot(_ == "../pom.xml").foreach(args += assignString( + "relativePath", + _ + )) `object`("Parent", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{Parent => MavenParent} class ConvertibleMavenParent(mp: MavenParent) { def asScala: Parent = { Parent( - Option(mp.getArtifactId).map(artifactId => (mp.getGroupId, artifactId, mp.getVersion).asScala).orNull, + Option(mp.getArtifactId).map(artifactId => + (mp.getGroupId, artifactId, mp.getVersion).asScala + ).orNull, mp.getRelativePath ) } @@ -60,4 +63,4 @@ class ConvertibleScalaParent(p: Parent) { mp.setRelativePath(p.relativePath) mp } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Plugin.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Plugin.scala index 530c899a..2d0c32d5 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Plugin.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Plugin.scala @@ -10,23 +10,23 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Plugin( - val gav: Gav, - val extensions: Boolean, - val executions: immutable.Seq[Execution], - val dependencies: immutable.Seq[Dependency], - override val inherited: Boolean, - override val configuration: Option[Config] - ) extends ConfigurationContainer(inherited, configuration) + val gav: Gav, + val extensions: Boolean, + val executions: immutable.Seq[Execution], + val dependencies: immutable.Seq[Dependency], + override val inherited: Boolean, + override val configuration: Option[Config] +) extends ConfigurationContainer(inherited, configuration) object Plugin { def apply( - gav: Gav, - extensions: Boolean = false, - executions: immutable.Seq[Execution] = immutable.Seq.empty, - dependencies: immutable.Seq[Dependency] = immutable.Seq.empty, - inherited: Boolean = true, - configuration: Config = null - ): Plugin = + gav: Gav, + extensions: Boolean = false, + executions: immutable.Seq[Execution] = immutable.Seq.empty, + dependencies: immutable.Seq[Dependency] = immutable.Seq.empty, + inherited: Boolean = true, + configuration: Config = null + ): Plugin = new Plugin( gav, extensions, @@ -37,21 +37,23 @@ object Plugin { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedPlugin(p: Plugin) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer(p.gav.asDoc) Some(p.extensions).filter(_ == true).foreach(e => args += assign("extensions", e.toString)) - Some(p.executions).filterNot(_.isEmpty).foreach(es => args += assign("executions", seq(es.map(_.asDoc)))) - Some(p.dependencies).filterNot(_.isEmpty).foreach(es => args += assign("dependencies", seq(es.map(_.asDoc)))) + Some(p.executions).filterNot(_.isEmpty).foreach(es => + args += assign("executions", seq(es.map(_.asDoc))) + ) + Some(p.dependencies).filterNot(_.isEmpty).foreach(es => + args += assign("dependencies", seq(es.map(_.asDoc))) + ) args ++= p.asDocArgs `object`("Plugin", args.toList) } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ @@ -85,4 +87,4 @@ class ConvertibleScalaPlugin(p: Plugin) { mp.setInherited(p.inherited) mp } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginContainer.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginContainer.scala index da52f849..0a4f05e0 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginContainer.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginContainer.scala @@ -11,13 +11,14 @@ import scala.collection.immutable abstract class PluginContainer(val plugins: immutable.Seq[Plugin]) - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedPluginContainer(pc: PluginContainer) { def asDocArgs: immutable.Seq[Doc] = { val args = scala.collection.mutable.ListBuffer[Doc]() - Some(pc.plugins).filterNot(_.isEmpty).foreach(ps => args += assign("plugins", seq(ps.map(_.asDoc)))) + Some(pc.plugins).filterNot(_.isEmpty).foreach(ps => + args += assign("plugins", seq(ps.map(_.asDoc))) + ) args.toList } } diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginManagement.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginManagement.scala index f7834216..a171b3ce 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginManagement.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/PluginManagement.scala @@ -25,7 +25,6 @@ class PrettiedPluginManagement(p: PluginManagement) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{PluginManagement => MavenPluginManagement} @@ -46,4 +45,4 @@ class ConvertibleScalaPluginManagement(pm: PluginManagement) { mpm.setPlugins(pm.plugins.map(_.asJava).asJava) mpm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Prerequisites.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Prerequisites.scala index f82502fc..f43bb900 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Prerequisites.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Prerequisites.scala @@ -23,7 +23,6 @@ class PrettiedPrerequisites(ps: Prerequisites) { } } - import org.apache.maven.model.{Prerequisites => MavenPrerequisites} class ConvertibleMavenPrerequisites(mps: MavenPrerequisites) { @@ -40,4 +39,4 @@ class ConvertibleScalaPrerequisites(ps: Prerequisites) { mps.setMaven(ps.maven) mps } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Profile.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Profile.scala index 2d495482..3c8fd5ff 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Profile.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Profile.scala @@ -10,38 +10,36 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Profile( - val id: String, - val activation: Option[Activation], - val build: Option[BuildBase], - dependencyManagement: Option[DependencyManagement], - dependencies: immutable.Seq[Dependency], - distributionManagement: Option[DistributionManagement], - modules: immutable.Seq[String], - pluginRepositories: immutable.Seq[Repository], - repositories: immutable.Seq[Repository] - ) - extends - ModelBase( - dependencyManagement, - dependencies, - distributionManagement, - modules, - pluginRepositories, - repositories - ) + val id: String, + val activation: Option[Activation], + val build: Option[BuildBase], + dependencyManagement: Option[DependencyManagement], + dependencies: immutable.Seq[Dependency], + distributionManagement: Option[DistributionManagement], + modules: immutable.Seq[String], + pluginRepositories: immutable.Seq[Repository], + repositories: immutable.Seq[Repository] +) extends ModelBase( + dependencyManagement, + dependencies, + distributionManagement, + modules, + pluginRepositories, + repositories + ) object Profile { def apply( - id: String = "default", - activation: Activation = null, - build: BuildBase = null, - dependencyManagement: DependencyManagement = null, - dependencies: immutable.Seq[Dependency] = Nil, - distributionManagement: DistributionManagement = null, - modules: immutable.Seq[String] = Nil, - pluginRepositories: immutable.Seq[Repository] = Nil, - repositories: immutable.Seq[Repository] = Nil - ): Profile = + id: String = "default", + activation: Activation = null, + build: BuildBase = null, + dependencyManagement: DependencyManagement = null, + dependencies: immutable.Seq[Dependency] = Nil, + distributionManagement: DistributionManagement = null, + modules: immutable.Seq[String] = Nil, + pluginRepositories: immutable.Seq[Repository] = Nil, + repositories: immutable.Seq[Repository] = Nil + ): Profile = new Profile( id, Option(activation), @@ -55,7 +53,6 @@ object Profile { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedProfile(p: Profile) { @@ -69,7 +66,6 @@ class PrettiedProfile(p: Profile) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Profile => MavenProfile} @@ -106,4 +102,4 @@ class ConvertibleScalaProfile(p: Profile) { mp.setRepositories(p.repositories.map(_.asJava).asJava) mp } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Relocation.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Relocation.scala index b70016a5..d626e11f 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Relocation.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Relocation.scala @@ -8,19 +8,19 @@ package org.sonatype.maven.polyglot.scala.model class Relocation( - val groupId: Option[String], - val artifactId: Option[String], - val version: Option[String], - val message: Option[String] - ) + val groupId: Option[String], + val artifactId: Option[String], + val version: Option[String], + val message: Option[String] +) object Relocation { def apply( - groupId: String = null, - artifactId: String = null, - version: String = null, - message: String = null - ): Relocation = + groupId: String = null, + artifactId: String = null, + version: String = null, + message: String = null + ): Relocation = new Relocation( Option(groupId), Option(artifactId), @@ -29,7 +29,6 @@ object Relocation { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedRelocation(r: Relocation) { @@ -43,7 +42,6 @@ class PrettiedRelocation(r: Relocation) { } } - import org.apache.maven.model.{Relocation => MavenRelocation} class ConvertibleMavenRelocation(mr: MavenRelocation) { @@ -66,4 +64,4 @@ class ConvertibleScalaRelocation(r: Relocation) { mr.setMessage(r.message.orNull) mr } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportPlugin.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportPlugin.scala index d591056a..5410791f 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportPlugin.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportPlugin.scala @@ -10,18 +10,19 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class ReportPlugin( - val gav: Gav, - val reportSets: immutable.Seq[ReportSet], - override val inherited: Boolean, - override val configuration: Option[Config]) - extends ConfigurationContainer(inherited, configuration) + val gav: Gav, + val reportSets: immutable.Seq[ReportSet], + override val inherited: Boolean, + override val configuration: Option[Config] +) extends ConfigurationContainer(inherited, configuration) object ReportPlugin { def apply( - gav: Gav, - reportSets: immutable.Seq[ReportSet] = immutable.Seq.empty, - inherited: Boolean = true, - configuration: Config = null) = + gav: Gav, + reportSets: immutable.Seq[ReportSet] = immutable.Seq.empty, + inherited: Boolean = true, + configuration: Config = null + ) = new ReportPlugin( gav = gav, reportSets = reportSets, @@ -35,7 +36,9 @@ import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedReportPlugin(p: ReportPlugin) { def asDoc: Doc = { val args = scala.collection.mutable.ListBuffer(p.gav.asDoc) - Some(p.reportSets).filterNot(_.isEmpty).foreach(rs => args += assign("reportSets", seq(rs.map(_.asDoc)))) + Some(p.reportSets).filterNot(_.isEmpty).foreach(rs => + args += assign("reportSets", seq(rs.map(_.asDoc))) + ) args ++= p.asDocArgs `object`("ReportPlugin", args.toList) @@ -45,7 +48,7 @@ class PrettiedReportPlugin(p: ReportPlugin) { import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ -import org.apache.maven.model.{ ReportPlugin => MavenReportPlugin } +import org.apache.maven.model.{ReportPlugin => MavenReportPlugin} class ConvertibleMavenReportPlugin(mp: MavenReportPlugin) { def asScala: ReportPlugin = { @@ -71,4 +74,4 @@ class ConvertibleScalaReportPlugin(p: ReportPlugin) { mp.setConfiguration(p.configuration.map(_.asJava).orNull) mp } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportSet.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportSet.scala index 0158f8e9..34ac4401 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportSet.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ReportSet.scala @@ -10,18 +10,19 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class ReportSet( - val id: String, - val reports: immutable.Seq[String], - override val inherited: Boolean, - override val configuration: Option[Config]) - extends ConfigurationContainer(inherited, configuration) + val id: String, + val reports: immutable.Seq[String], + override val inherited: Boolean, + override val configuration: Option[Config] +) extends ConfigurationContainer(inherited, configuration) object ReportSet { def apply( - id: String = "default", - reports: immutable.Seq[String] = immutable.Seq.empty, - inherited: Boolean = true, - configuration: Config = null) = + id: String = "default", + reports: immutable.Seq[String] = immutable.Seq.empty, + inherited: Boolean = true, + configuration: Config = null + ) = new ReportSet( id = id, reports = reports, @@ -45,7 +46,7 @@ class PrettiedReportSet(s: ReportSet) { import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ -import org.apache.maven.model.{ ReportSet => MavenReportSet } +import org.apache.maven.model.{ReportSet => MavenReportSet} class ConvertibleMavenReportSet(ms: MavenReportSet) { def asScala: ReportSet = { @@ -70,5 +71,3 @@ class ConvertibleScalaReportSet(s: ReportSet) { ms } } - - diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Reporting.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Reporting.scala index fa237e2c..1623bd86 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Reporting.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Reporting.scala @@ -10,15 +10,17 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Reporting( - val excludeDefaults: Boolean, - val outputDirectory: Option[String], - val plugins: immutable.Seq[ReportPlugin]) + val excludeDefaults: Boolean, + val outputDirectory: Option[String], + val plugins: immutable.Seq[ReportPlugin] +) object Reporting { def apply( - excludeDefaults: Boolean = false, - outputDirectory: String = null, - plugins: immutable.Seq[ReportPlugin] = immutable.Seq.empty) = + excludeDefaults: Boolean = false, + outputDirectory: String = null, + plugins: immutable.Seq[ReportPlugin] = immutable.Seq.empty + ) = new Reporting( excludeDefaults = excludeDefaults, outputDirectory = Option(outputDirectory), @@ -33,14 +35,16 @@ class PrettiedReporting(r: Reporting) { val args = scala.collection.mutable.ListBuffer[Doc]() args += assignString("excludeDefaults", (if (r.excludeDefaults) "true" else "false")) r.outputDirectory.foreach(args += assignString("outputDirectory", _)) - Some(r.plugins).filterNot(_.isEmpty).foreach(ps => args += assign("plugins", seq(ps.map(_.asDoc)))) + Some(r.plugins).filterNot(_.isEmpty).foreach(ps => + args += assign("plugins", seq(ps.map(_.asDoc))) + ) `object`("Reporting", args.toList) } } import org.sonatype.maven.polyglot.scala.MavenConverters._ import scala.jdk.CollectionConverters._ -import org.apache.maven.model.{ Reporting => MavenReporting } +import org.apache.maven.model.{Reporting => MavenReporting} class ConvertibleMavenReporting(mr: MavenReporting) { def asScala: Reporting = { @@ -62,4 +66,4 @@ class ConvertibleScalaReporting(r: Reporting) { mr.setPlugins(r.plugins.map(_.asJava).asJava) mr } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Repository.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Repository.scala index 110fef25..36dcfa9c 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Repository.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Repository.scala @@ -8,23 +8,23 @@ package org.sonatype.maven.polyglot.scala.model class Repository( - val releases: Option[RepositoryPolicy], - val snapshots: Option[RepositoryPolicy], - val id: Option[String], - val name: Option[String], - val url: Option[String], - val layout: String - ) + val releases: Option[RepositoryPolicy], + val snapshots: Option[RepositoryPolicy], + val id: Option[String], + val name: Option[String], + val url: Option[String], + val layout: String +) object Repository { def apply( - releases: RepositoryPolicy = null, - snapshots: RepositoryPolicy = null, - id: String = null, - name: String = null, - url: String = null, - layout: String = "default" - ) = + releases: RepositoryPolicy = null, + snapshots: RepositoryPolicy = null, + id: String = null, + name: String = null, + url: String = null, + layout: String = "default" + ) = new Repository( Option(releases), Option(snapshots), @@ -54,7 +54,6 @@ class PrettiedRepository(r: Repository) { } } - import org.sonatype.maven.polyglot.scala.MavenConverters._ import org.apache.maven.model.{Repository => MavenRepository} @@ -84,4 +83,4 @@ class ConvertibleScalaRepository(r: Repository) { mr.setLayout(r.layout) mr } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/RepositoryPolicy.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/RepositoryPolicy.scala index 870e8fa7..db662586 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/RepositoryPolicy.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/RepositoryPolicy.scala @@ -8,17 +8,17 @@ package org.sonatype.maven.polyglot.scala.model class RepositoryPolicy( - val enabled: Boolean, - val updatePolicy: String, - val checksumPolicy: String - ) + val enabled: Boolean, + val updatePolicy: String, + val checksumPolicy: String +) object RepositoryPolicy { def apply( - enabled: Boolean, - updatePolicy: String = "daily", - checksumPolicy: String = "warn" - ) = + enabled: Boolean, + updatePolicy: String = "daily", + checksumPolicy: String = "warn" + ) = new RepositoryPolicy( enabled, updatePolicy, @@ -38,7 +38,6 @@ class PrettiedRepositoryPolicy(rp: RepositoryPolicy) { } } - import org.apache.maven.model.{RepositoryPolicy => MavenRepositoryPolicy} class ConvertibleMavenRepositoryPolicy(mrp: MavenRepositoryPolicy) { @@ -59,4 +58,4 @@ class ConvertibleScalaRepositoryPolicy(rp: RepositoryPolicy) { mrp.setChecksumPolicy(rp.checksumPolicy) mrp } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Resource.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Resource.scala index 776bf372..9b86754b 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Resource.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Resource.scala @@ -10,21 +10,21 @@ package org.sonatype.maven.polyglot.scala.model import scala.collection.immutable class Resource( - val targetPath: Option[String], - val filtering: Boolean, - val directory: Option[String], - val includes: immutable.Seq[String], - val excludes: immutable.Seq[String] - ) + val targetPath: Option[String], + val filtering: Boolean, + val directory: Option[String], + val includes: immutable.Seq[String], + val excludes: immutable.Seq[String] +) object Resource { def apply( - targetPath: String = null, - filtering: Boolean = false, - directory: String = null, - includes: immutable.Seq[String] = Nil, - excludes: immutable.Seq[String] = Nil - ): Resource = + targetPath: String = null, + filtering: Boolean = false, + directory: String = null, + includes: immutable.Seq[String] = Nil, + excludes: immutable.Seq[String] = Nil + ): Resource = new Resource( Option(targetPath), filtering, @@ -34,7 +34,6 @@ object Resource { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedResource(r: Resource) { @@ -49,7 +48,6 @@ class PrettiedResource(r: Resource) { } } - import scala.jdk.CollectionConverters._ import org.apache.maven.model.{Resource => MavenResource} @@ -75,4 +73,4 @@ class ConvertibleScalaResource(r: Resource) { mr.setIncludes(r.includes.asJava) mr } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaModel.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaModel.scala index 1db19680..63e6bb08 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaModel.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaModel.scala @@ -92,42 +92,43 @@ object ScalaModel { ) def apply( - gav: Gav, - build: Build = null, - ciManagement: CiManagement = null, - contributors: immutable.Seq[Contributor] = Nil, - dependencyManagement: DependencyManagement = null, - dependencies: immutable.Seq[Dependency] = Nil, - description: String = null, - developers: immutable.Seq[Developer] = Nil, - distributionManagement: DistributionManagement = null, - inceptionYear: String = null, - issueManagement: IssueManagement = null, - licenses: immutable.Seq[License] = Nil, - mailingLists: immutable.Seq[MailingList] = Nil, - modelEncoding: String = "UTF-8", - modelVersion: String = "4.0.0", - modules: immutable.Seq[String] = Nil, - name: String = null, - organization: Organization = null, - packaging: String = "jar", - parent: Parent = null, - pluginRepositories: immutable.Seq[Repository] = Nil, - pomFile: File = null, - prerequisites: Prerequisites = null, - profiles: immutable.Seq[Profile] = Nil, - properties: Map[String, String] = Map.empty, - reporting: Reporting = null, - repositories: immutable.Seq[Repository] = Nil, - scm: Scm = null, - url: String = null - )(implicit scalaVersion: ScalaVersion) = { + gav: Gav, + build: Build = null, + ciManagement: CiManagement = null, + contributors: immutable.Seq[Contributor] = Nil, + dependencyManagement: DependencyManagement = null, + dependencies: immutable.Seq[Dependency] = Nil, + description: String = null, + developers: immutable.Seq[Developer] = Nil, + distributionManagement: DistributionManagement = null, + inceptionYear: String = null, + issueManagement: IssueManagement = null, + licenses: immutable.Seq[License] = Nil, + mailingLists: immutable.Seq[MailingList] = Nil, + modelEncoding: String = "UTF-8", + modelVersion: String = "4.0.0", + modules: immutable.Seq[String] = Nil, + name: String = null, + organization: Organization = null, + packaging: String = "jar", + parent: Parent = null, + pluginRepositories: immutable.Seq[Repository] = Nil, + pomFile: File = null, + prerequisites: Prerequisites = null, + profiles: immutable.Seq[Profile] = Nil, + properties: Map[String, String] = Map.empty, + reporting: Reporting = null, + repositories: immutable.Seq[Repository] = Nil, + scm: Scm = null, + url: String = null + )(implicit scalaVersion: ScalaVersion) = { val scalaLang = "org.scala-lang" % "scala-library" % scalaVersion.version val scalaLangIncluded = dependencies.exists { d => d.gav.groupId == scalaLang.groupId && d.gav.artifactId == scalaLang.artifactId } - val targetDependencies = if (scalaLangIncluded) dependencies else dependencies :+ Dependency(scalaLang) + val targetDependencies = + if (scalaLangIncluded) dependencies else dependencies :+ Dependency(scalaLang) val targetBuild = Option(build).map({ b => @@ -141,7 +142,8 @@ object ScalaModel { val pluginManagement = b.pluginManagement.getOrElse(PluginManagement()) val lifeCycleMappingIncluded = pluginManagement.plugins.exists { - p => p.gav.groupId == lifeCycleMapping.gav.groupId && p.gav.artifactId == lifeCycleMapping.gav.artifactId + p => + p.gav.groupId == lifeCycleMapping.gav.groupId && p.gav.artifactId == lifeCycleMapping.gav.artifactId } val targetPluginManagementPlugins = if (lifeCycleMappingIncluded) pluginManagement.plugins @@ -149,13 +151,15 @@ object ScalaModel { val targetPluginManagement = Some(new PluginManagement(targetPluginManagementPlugins)) val mavenCompilerIncluded = b.plugins.exists { - p => p.gav.groupId == mavenCompiler.gav.groupId && p.gav.artifactId == mavenCompiler.gav.artifactId + p => + p.gav.groupId == mavenCompiler.gav.groupId && p.gav.artifactId == mavenCompiler.gav.artifactId } val targetMavenCompiler = if (mavenCompilerIncluded) None else Some(mavenCompiler) val scalaCompilerIncluded = b.plugins.exists { - p => p.gav.groupId == scalaCompiler.gav.groupId && p.gav.artifactId == scalaCompiler.gav.artifactId + p => + p.gav.groupId == scalaCompiler.gav.groupId && p.gav.artifactId == scalaCompiler.gav.artifactId } val targetScalaCompiler = if (scalaCompilerIncluded) None @@ -166,7 +170,11 @@ object ScalaModel { val targetSurefire = if (surefireIncluded) None else Some(surefire) - val targetPlugins = b.plugins ++: immutable.Seq(targetMavenCompiler, targetScalaCompiler, targetSurefire).flatten + val targetPlugins = b.plugins ++: immutable.Seq( + targetMavenCompiler, + targetScalaCompiler, + targetSurefire + ).flatten new Build( targetSourceDirectory, diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaVersion.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaVersion.scala index ebf08e14..2dfe8ffe 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaVersion.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/ScalaVersion.scala @@ -16,4 +16,4 @@ class ScalaVersion(val version: String) { object ScalaVersion { def apply(version: String) = new ScalaVersion(version) -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Scm.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Scm.scala index 8ed90a68..8ca9b1b6 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Scm.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Scm.scala @@ -8,19 +8,19 @@ package org.sonatype.maven.polyglot.scala.model class Scm( - val connection: Option[String], - val developerConnection: Option[String], - val tag: String, - val url: Option[String] - ) + val connection: Option[String], + val developerConnection: Option[String], + val tag: String, + val url: Option[String] +) object Scm { def apply( - connection: String = null, - developerConnection: String = null, - tag: String = "HEAD", - url: String = null - ): Scm = + connection: String = null, + developerConnection: String = null, + tag: String = "HEAD", + url: String = null + ): Scm = new Scm( Option(connection), Option(developerConnection), @@ -42,7 +42,6 @@ class PrettiedScm(scm: Scm) { } } - import org.apache.maven.model.{Scm => MavenScm} class ConvertibleMavenScm(mscm: MavenScm) { @@ -65,4 +64,4 @@ class ConvertibleScalaScm(scm: Scm) { mscm.setUrl(scm.url.orNull) mscm } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Site.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Site.scala index 58aa3ef6..9d2ea573 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Site.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Site.scala @@ -8,17 +8,17 @@ package org.sonatype.maven.polyglot.scala.model class Site( - val id: Option[String], - val name: Option[String], - val url: Option[String] - ) + val id: Option[String], + val name: Option[String], + val url: Option[String] +) object Site { def apply( - id: String = null, - name: String = null, - url: String = null - ): Site = + id: String = null, + name: String = null, + url: String = null + ): Site = new Site( Option(id), Option(name), @@ -26,7 +26,6 @@ object Site { ) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedSite(s: Site) { @@ -39,7 +38,6 @@ class PrettiedSite(s: Site) { } } - import org.apache.maven.model.{Site => MavenSite} class ConvertibleMavenSite(ms: MavenSite) { @@ -60,4 +58,4 @@ class ConvertibleScalaSite(s: Site) { ms.setUrl(s.url.orNull) ms } -} \ No newline at end of file +} diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Task.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Task.scala index bc3d8dcf..c614fca5 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Task.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/Task.scala @@ -9,14 +9,22 @@ package org.sonatype.maven.polyglot.scala.model import org.sonatype.maven.polyglot.execute.ExecuteContext -class Task(val id: String, val phase: String, val profileId: Option[String], val block: ExecuteContext => Unit) +class Task( + val id: String, + val phase: String, + val profileId: Option[String], + val block: ExecuteContext => Unit +) object Task { - def apply(id: String, phase: String, profileId: String = null)(block: ExecuteContext => Unit): Task = + def apply( + id: String, + phase: String, + profileId: String = null + )(block: ExecuteContext => Unit): Task = new Task(id, phase, Option(profileId), block) } - import org.sonatype.maven.polyglot.scala.ScalaPrettyPrinter._ class PrettiedTask(t: Task) { diff --git a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/package.scala b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/package.scala index 10d6fc7c..b01710b9 100644 --- a/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/package.scala +++ b/polyglot-scala/src/main/scala/org/sonatype/maven/polyglot/scala/model/package.scala @@ -32,7 +32,8 @@ package object model { /** * Produce a dependency from a GroupArtifactId when required. */ - implicit def toDependency(groupArtifactId: GroupArtifactId): Dependency = Dependency(Gav(groupArtifactId, None)) + implicit def toDependency(groupArtifactId: GroupArtifactId): Dependency = + Dependency(Gav(groupArtifactId, None)) /** * Produce a Gav where we just have a group and artifact. diff --git a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ConfigSpec.scala b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ConfigSpec.scala index 21890468..4ef48d20 100644 --- a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ConfigSpec.scala +++ b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ConfigSpec.scala @@ -104,7 +104,6 @@ class ConfigSpec extends Specification { e(2)._2.get.asInstanceOf[String] must_== "attrValue4" } - // the attribute marker s"should permit `@` char in element name via dynamic apply" in { Config(`@Key@` = "value").elements.head._1 must_== "@Key$at" diff --git a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelReaderWriterSpec.scala b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelReaderWriterSpec.scala index e049c235..6cea3f6d 100644 --- a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelReaderWriterSpec.scala +++ b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelReaderWriterSpec.scala @@ -22,7 +22,11 @@ import java.util.Collections import org.sonatype.maven.polyglot.execute.{ExecuteContext, ExecuteManager, ExecuteTask} import java.util -import org.sonatype.maven.polyglot.scala.model.{Build => ScalaBuild, Model => ScalaRawModel, Task => ScalaModelTask} +import org.sonatype.maven.polyglot.scala.model.{ + Build => ScalaBuild, + Model => ScalaRawModel, + Task => ScalaModelTask +} import scala.collection.{immutable, mutable} import org.apache.maven.project.MavenProject @@ -41,7 +45,7 @@ class ScalaModelReaderWriterSpec extends Specification with AfterEach { def getLocation: String = evalFile.getCanonicalPath def getLocationURI(): java.net.URI = evalFile.getCanonicalFile().toURI() - + def getRelatedSource(relPath: String): ModelSource2 = ??? // ok for this test case } @@ -50,7 +54,8 @@ class ScalaModelReaderWriterSpec extends Specification with AfterEach { object TestExecuteManager extends ExecuteManager { private val modelTasks = mutable.Map[Model, (Boolean, util.List[ExecuteTask])]() - override def register(model: Model, tasks: util.List[ExecuteTask]): Unit = modelTasks.put(model, (false, tasks)) + override def register(model: Model, tasks: util.List[ExecuteTask]): Unit = + modelTasks.put(model, (false, tasks)) override def getTasks(model: Model): util.List[ExecuteTask] = { val attributedTasks = modelTasks.get(model).get @@ -92,12 +97,13 @@ class ScalaModelReaderWriterSpec extends Specification with AfterEach { sequential - /** all tests which use [[readScalaModel]] method fail currently under Java 11. + /** + * all tests which use [[readScalaModel]] method fail currently under Java 11. * Yet, the plugin still works, so I just disabled these tests and intend to * add some maven-invoker-plugin based tests, to ensure, the built plugin still works. */ def withJava8(f: => org.specs2.execute.Result): Result = { - if(sys.props("java.version").startsWith("1.")) { + if (sys.props("java.version").startsWith("1.")) { f } else { skipped("Test not working with this Java version") diff --git a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelSpec.scala b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelSpec.scala index 0ed6477d..02828ea0 100644 --- a/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelSpec.scala +++ b/polyglot-scala/src/test/scala/org/sonatype/maven/polyglot/scala/ScalaModelSpec.scala @@ -48,7 +48,8 @@ class ScalaModelSpec extends Specification { build = Build( sourceDirectory = "src/main/scala2", testSourceDirectory = "src/test/scala2", - pluginManagement = PluginManagement(immutable.Seq(Plugin("org.eclipse.m2e" % "lifecycle-mapping" % "0"))), + pluginManagement = + PluginManagement(immutable.Seq(Plugin("org.eclipse.m2e" % "lifecycle-mapping" % "0"))), plugins = immutable.Seq( Plugin("org.apache.maven.plugins" % "maven-compiler-plugin" % "0"), Plugin("net.alchim31.maven" % "scala-maven-plugin" % "0"), diff --git a/polyglot-translate-plugin/pom.xml b/polyglot-translate-plugin/pom.xml index 984fbf86..173635b2 100644 --- a/polyglot-translate-plugin/pom.xml +++ b/polyglot-translate-plugin/pom.xml @@ -14,8 +14,8 @@ polyglot-translate-plugin - Polyglot :: Translate Plugin takari-maven-plugin + Polyglot :: Translate Plugin diff --git a/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslateProjectMojo.java b/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslateProjectMojo.java index 4691b3da..d037bf74 100644 --- a/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslateProjectMojo.java +++ b/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslateProjectMojo.java @@ -9,7 +9,6 @@ import java.io.File; import java.io.IOException; - import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -21,32 +20,32 @@ /** * Polgyglot model translator Mojo. - * + * */ @Mojo(name = "translate-project") public class TranslateProjectMojo extends AbstractMojo { - @Component - private TeslaModelTranslator translator; - - @Parameter(required = true, property = "input") - private String input; - - @Parameter(required = true, property = "output") - private String output; - - @Parameter(readonly = true, required = true, defaultValue = "${project}") - private MavenProject mavenProject; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - try { - File inputFile = new File(mavenProject.getBasedir(), input); - File outputFile = new File(mavenProject.getBasedir(), output); - getLog().info(String.format("Translating %s -> %s", inputFile, outputFile)); - translator.translate(inputFile, outputFile); - } catch (IOException e) { - throw new MojoExecutionException(String.format("Error translating %s -> %s", input, output), e); - } - } -} \ No newline at end of file + @Component + private TeslaModelTranslator translator; + + @Parameter(required = true, property = "input") + private String input; + + @Parameter(required = true, property = "output") + private String output; + + @Parameter(readonly = true, required = true, defaultValue = "${project}") + private MavenProject mavenProject; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + try { + File inputFile = new File(mavenProject.getBasedir(), input); + File outputFile = new File(mavenProject.getBasedir(), output); + getLog().info(String.format("Translating %s -> %s", inputFile, outputFile)); + translator.translate(inputFile, outputFile); + } catch (IOException e) { + throw new MojoExecutionException(String.format("Error translating %s -> %s", input, output), e); + } + } +} diff --git a/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslatorMojo.java b/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslatorMojo.java index 08a3a6e3..f66e8d38 100644 --- a/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslatorMojo.java +++ b/polyglot-translate-plugin/src/main/java/io/takari/maven/polyglot/TranslatorMojo.java @@ -9,9 +9,7 @@ import java.io.File; import java.io.IOException; -import java.net.URL; import java.util.List; - import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; @@ -23,35 +21,35 @@ /** * Polgyglot model translator Mojo. - * + * * @author Jason van Zyl */ @Mojo(name = "translate", requiresProject = false, aggregator = true) public class TranslatorMojo extends AbstractMojo { - @Component - private TeslaModelTranslator translator; - - @Parameter(required = true, property = "input") - private String input; - - @Parameter(required = true, property = "output") - private String output; - - @Parameter(readonly = true, required = true, defaultValue = "${reactorProjects}") - protected List reactorProjects; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - try { - for ( MavenProject project : reactorProjects ) { - File inputFile = new File(project.getBasedir(), input); - File outputFile = new File(project.getBasedir(), output); - getLog().info(String.format("Translating %s -> %s", inputFile, outputFile)); - translator.translate(inputFile, outputFile); - } - } catch (IOException e) { - throw new MojoExecutionException(String.format("Error translating %s -> %s", input, output), e); + @Component + private TeslaModelTranslator translator; + + @Parameter(required = true, property = "input") + private String input; + + @Parameter(required = true, property = "output") + private String output; + + @Parameter(readonly = true, required = true, defaultValue = "${reactorProjects}") + protected List reactorProjects; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + try { + for (MavenProject project : reactorProjects) { + File inputFile = new File(project.getBasedir(), input); + File outputFile = new File(project.getBasedir(), output); + getLog().info(String.format("Translating %s -> %s", inputFile, outputFile)); + translator.translate(inputFile, outputFile); + } + } catch (IOException e) { + throw new MojoExecutionException(String.format("Error translating %s -> %s", input, output), e); + } } - } -} \ No newline at end of file +} diff --git a/polyglot-xml/pom.xml b/polyglot-xml/pom.xml index c1908ec4..494f9e8b 100644 --- a/polyglot-xml/pom.xml +++ b/polyglot-xml/pom.xml @@ -5,73 +5,72 @@ and is available at http://www.eclipse.org/legal/epl-v10.html --> - 4.0.0 - - io.takari.polyglot - polyglot - 0.7.2-SNAPSHOT - - polyglot-xml + 4.0.0 + + io.takari.polyglot + polyglot + 0.7.2-SNAPSHOT + + polyglot-xml takari-maven-component - Polyglot :: XML + Polyglot :: XML - - - io.takari.polyglot - polyglot-common - - - com.cedarsoftware - java-util - 1.68.0 - test - - + + + io.takari.polyglot + polyglot-common + + + com.cedarsoftware + java-util + 1.68.0 + test + + - - - - generate-code - - - - org.codehaus.modello - modello-maven-plugin - - - src/main/mdo/maven.mdo - - - - - java-code - - xpp3-writer - xpp3-reader - - - ${project.basedir}/generated-src/java - 4.1.0 - - - - xsd - - xsd - - - 4.1.0 - ${project.basedir}/src/main/resources/xsd - true - - - - - - - - - + + + generate-code + + + + org.codehaus.modello + modello-maven-plugin + + + src/main/mdo/maven.mdo + + + + + java-code + + xpp3-writer + xpp3-reader + + + ${project.basedir}/generated-src/java + 4.1.0 + + + + xsd + + xsd + + + 4.1.0 + ${project.basedir}/src/main/resources/xsd + true + + + + + + + + diff --git a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLMapping.java b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLMapping.java index 59853402..1acf5317 100644 --- a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLMapping.java +++ b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLMapping.java @@ -7,12 +7,10 @@ */ package org.sonatype.maven.polyglot.xml; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.FileInputStream; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.sonatype.maven.polyglot.mapping.MappingSupport; import org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader; @@ -21,53 +19,53 @@ * */ @Singleton -@Named( "xml41" ) +@Named("xml41") public class XMLMapping extends MappingSupport { - - public XMLMapping() { - super("xml41"); - setPomNames("pom.xml41"); - setAcceptLocationExtensions(".xml41", ".xml"); - setAcceptOptionKeys("xml41:4.0.0"); - setPriority(-1); - } - @Override - public boolean accept(Map options) { - if (options != null) { + public XMLMapping() { + super("xml41"); + setPomNames("pom.xml41"); + setAcceptLocationExtensions(".xml41", ".xml"); + setAcceptOptionKeys("xml41:4.0.0"); + setPriority(-1); + } + + @Override + public boolean accept(Map options) { + if (options != null) { - String location = getLocation(options); - if (location != null) { - if (location.endsWith(".xml41")) { - return true; - } else if (location.endsWith(".xml")) { - return canParse(options); - } - } - } + String location = getLocation(options); + if (location != null) { + if (location.endsWith(".xml41")) { + return true; + } else if (location.endsWith(".xml")) { + return canParse(options); + } + } + } - return false; - } + return false; + } - private boolean canParse(Map options) { - boolean canParse = false; - FileInputStream in = null; - try { - in = new FileInputStream(getLocation(options)); - PolyglotMavenXpp3Reader reader = new PolyglotMavenXpp3Reader(); - reader.read(in); - canParse = true; - } catch (Exception ex) { - canParse = false; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e) { - canParse = false; - } - } - return canParse; - } -} \ No newline at end of file + private boolean canParse(Map options) { + boolean canParse = false; + FileInputStream in = null; + try { + in = new FileInputStream(getLocation(options)); + PolyglotMavenXpp3Reader reader = new PolyglotMavenXpp3Reader(); + reader.read(in); + canParse = true; + } catch (Exception ex) { + canParse = false; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e) { + canParse = false; + } + } + return canParse; + } +} diff --git a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelReader.java b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelReader.java index c9baf614..9b6d1e77 100644 --- a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelReader.java +++ b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelReader.java @@ -7,13 +7,11 @@ */ package org.sonatype.maven.polyglot.xml; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Reader; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelParseException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -25,28 +23,28 @@ * */ @Singleton -@Named( "xml41" ) +@Named("xml41") public class XMLModelReader extends ModelReaderSupport { - - PolyglotMavenXpp3Reader reader; - - public XMLModelReader() { - reader = new PolyglotMavenXpp3Reader(); - } - - public Model read(Reader input, Map options) throws IOException, ModelParseException { - if (input == null) { - throw new IllegalArgumentException("XML Reader is null."); - } - - Model model = null; - - try { - model = reader.read(input); - } catch (XmlPullParserException e) { - throw new ModelParseException(e.getMessage(), -1, -1, e); - } - - return model; - } + + PolyglotMavenXpp3Reader reader; + + public XMLModelReader() { + reader = new PolyglotMavenXpp3Reader(); + } + + public Model read(Reader input, Map options) throws IOException, ModelParseException { + if (input == null) { + throw new IllegalArgumentException("XML Reader is null."); + } + + Model model = null; + + try { + model = reader.read(input); + } catch (XmlPullParserException e) { + throw new ModelParseException(e.getMessage(), -1, -1, e); + } + + return model; + } } diff --git a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelWriter.java b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelWriter.java index b2c39b96..512ea81d 100644 --- a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelWriter.java +++ b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/XMLModelWriter.java @@ -7,13 +7,11 @@ */ package org.sonatype.maven.polyglot.xml; -import javax.inject.Named; -import javax.inject.Singleton; - import java.io.IOException; import java.io.Writer; import java.util.Map; - +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.model.Model; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Writer; @@ -23,17 +21,17 @@ * */ @Singleton -@Named( "xml41" ) +@Named("xml41") public class XMLModelWriter extends ModelWriterSupport { - - PolyglotMavenXpp3Writer writer; - - public XMLModelWriter() { - writer = new PolyglotMavenXpp3Writer(); - } - public void write(Writer output, Map o, Model model) throws IOException { + PolyglotMavenXpp3Writer writer; + + public XMLModelWriter() { + writer = new PolyglotMavenXpp3Writer(); + } + + public void write(Writer output, Map o, Model model) throws IOException { - writer.write(output, model); - } + writer.write(output, model); + } } diff --git a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Reader.java b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Reader.java index dcd427f3..370c7fc2 100644 --- a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Reader.java +++ b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Reader.java @@ -1,15 +1,15 @@ /* - =================== DO NOT EDIT THIS FILE ==================== - Generated by Modello 1.5 on 2016-10-03 11:37:27, - any modifications will be overwritten. - ============================================================== - */ +=================== DO NOT EDIT THIS FILE ==================== +Generated by Modello 1.5 on 2016-10-03 11:37:27, +any modifications will be overwritten. +============================================================== +*/ package org.sonatype.maven.polyglot.xml.xpp3; - //---------------------------------/ - //- Imported classes and packages -/ -//---------------------------------/ +// ---------------------------------/ +// - Imported classes and packages -/ +// ---------------------------------/ import java.io.IOException; import java.io.InputStream; @@ -65,15 +65,14 @@ /** * Class MavenXpp3Reader. - * + * * @version $Revision$ $Date$ */ -public class PolyglotMavenXpp3Reader -{ +public class PolyglotMavenXpp3Reader { - //--------------------------/ - //- Class/Member Variables -/ - //--------------------------/ + // --------------------------/ + // - Class/Member Variables -/ + // --------------------------/ /** * If set the parser will be loaded with all single characters @@ -87,14 +86,13 @@ public class PolyglotMavenXpp3Reader */ private boolean addDefaultEntities = true; - - //-----------/ - //- Methods -/ - //-----------/ + // -----------/ + // - Methods -/ + // -----------/ /** * Method checkFieldWithDuplicate. - * + * * @param parser * @param parsed * @param alias @@ -102,23 +100,20 @@ public class PolyglotMavenXpp3Reader * @throws XmlPullParserException * @return boolean */ - private boolean checkFieldWithDuplicate( XmlPullParser parser, String tagName, String alias, java.util.Set parsed ) - throws XmlPullParserException - { - if ( !( parser.getName().equals( tagName ) || parser.getName().equals( alias ) ) ) - { + private boolean checkFieldWithDuplicate(XmlPullParser parser, String tagName, String alias, java.util.Set parsed) + throws XmlPullParserException { + if (!(parser.getName().equals(tagName) || parser.getName().equals(alias))) { return false; } - if ( !parsed.add( tagName ) ) - { - throw new XmlPullParserException( "Duplicated tag: '" + tagName + "'", parser, null ); + if (!parsed.add(tagName)) { + throw new XmlPullParserException("Duplicated tag: '" + tagName + "'", parser, null); } return true; - } //-- boolean checkFieldWithDuplicate( XmlPullParser, String, String, java.util.Set ) + } // -- boolean checkFieldWithDuplicate( XmlPullParser, String, String, java.util.Set ) /** * Method checkUnknownAttribute. - * + * * @param parser * @param strict * @param tagName @@ -126,74 +121,63 @@ private boolean checkFieldWithDuplicate( XmlPullParser parser, String tagName, S * @throws XmlPullParserException * @throws IOException */ - private void checkUnknownAttribute( XmlPullParser parser, String attribute, String tagName, boolean strict ) - throws XmlPullParserException, IOException - { + private void checkUnknownAttribute(XmlPullParser parser, String attribute, String tagName, boolean strict) + throws XmlPullParserException, IOException { // strictXmlAttributes = true for model: if strict == true, not only elements are checked but attributes too - if ( strict ) - { - throw new XmlPullParserException( "Unknown attribute '" + attribute + "' for tag '" + tagName + "'", parser, null ); + if (strict) { + throw new XmlPullParserException( + "Unknown attribute '" + attribute + "' for tag '" + tagName + "'", parser, null); } - } //-- void checkUnknownAttribute( XmlPullParser, String, String, boolean ) + } // -- void checkUnknownAttribute( XmlPullParser, String, String, boolean ) /** * Method checkUnknownElement. - * + * * @param parser * @param strict * @throws XmlPullParserException * @throws IOException */ - private void checkUnknownElement( XmlPullParser parser, boolean strict ) - throws XmlPullParserException, IOException - { - if ( strict ) - { - throw new XmlPullParserException( "Unrecognised tag: '" + parser.getName() + "'", parser, null ); + private void checkUnknownElement(XmlPullParser parser, boolean strict) throws XmlPullParserException, IOException { + if (strict) { + throw new XmlPullParserException("Unrecognised tag: '" + parser.getName() + "'", parser, null); } - for ( int unrecognizedTagCount = 1; unrecognizedTagCount > 0; ) - { + for (int unrecognizedTagCount = 1; unrecognizedTagCount > 0; ) { int eventType = parser.next(); - if ( eventType == XmlPullParser.START_TAG ) - { + if (eventType == XmlPullParser.START_TAG) { unrecognizedTagCount++; - } - else if ( eventType == XmlPullParser.END_TAG ) - { + } else if (eventType == XmlPullParser.END_TAG) { unrecognizedTagCount--; } } - } //-- void checkUnknownElement( XmlPullParser, boolean ) + } // -- void checkUnknownElement( XmlPullParser, boolean ) /** * Returns the state of the "add default entities" flag. - * + * * @return boolean */ - public boolean getAddDefaultEntities() - { + public boolean getAddDefaultEntities() { return addDefaultEntities; - } //-- boolean getAddDefaultEntities() + } // -- boolean getAddDefaultEntities() /** * Method getBooleanValue. - * + * * @param s * @param parser * @param attribute * @throws XmlPullParserException * @return boolean */ - private boolean getBooleanValue( String s, String attribute, XmlPullParser parser ) - throws XmlPullParserException - { - return getBooleanValue( s, attribute, parser, null ); - } //-- boolean getBooleanValue( String, String, XmlPullParser ) + private boolean getBooleanValue(String s, String attribute, XmlPullParser parser) throws XmlPullParserException { + return getBooleanValue(s, attribute, parser, null); + } // -- boolean getBooleanValue( String, String, XmlPullParser ) /** * Method getBooleanValue. - * + * * @param s * @param defaultValue * @param parser @@ -201,23 +185,20 @@ private boolean getBooleanValue( String s, String attribute, XmlPullParser parse * @throws XmlPullParserException * @return boolean */ - private boolean getBooleanValue( String s, String attribute, XmlPullParser parser, String defaultValue ) - throws XmlPullParserException - { - if ( s != null && s.length() != 0 ) - { - return Boolean.valueOf( s ).booleanValue(); + private boolean getBooleanValue(String s, String attribute, XmlPullParser parser, String defaultValue) + throws XmlPullParserException { + if (s != null && s.length() != 0) { + return Boolean.valueOf(s).booleanValue(); } - if ( defaultValue != null ) - { - return Boolean.valueOf( defaultValue ).booleanValue(); + if (defaultValue != null) { + return Boolean.valueOf(defaultValue).booleanValue(); } return false; - } //-- boolean getBooleanValue( String, String, XmlPullParser, String ) + } // -- boolean getBooleanValue( String, String, XmlPullParser, String ) /** * Method getByteValue. - * + * * @param s * @param strict * @param parser @@ -225,63 +206,54 @@ private boolean getBooleanValue( String s, String attribute, XmlPullParser parse * @throws XmlPullParserException * @return byte */ - private byte getByteValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Byte.valueOf( s ).byteValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be a byte", parser, nfe ); + private byte getByteValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Byte.valueOf(s).byteValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be a byte", parser, nfe); } } } return 0; - } //-- byte getByteValue( String, String, XmlPullParser, boolean ) + } // -- byte getByteValue( String, String, XmlPullParser, boolean ) /** * Method getCharacterValue. - * + * * @param s * @param parser * @param attribute * @throws XmlPullParserException * @return char */ - private char getCharacterValue( String s, String attribute, XmlPullParser parser ) - throws XmlPullParserException - { - if ( s != null ) - { - return s.charAt( 0 ); + private char getCharacterValue(String s, String attribute, XmlPullParser parser) throws XmlPullParserException { + if (s != null) { + return s.charAt(0); } return 0; - } //-- char getCharacterValue( String, String, XmlPullParser ) + } // -- char getCharacterValue( String, String, XmlPullParser ) /** * Method getDateValue. - * + * * @param s * @param parser * @param attribute * @throws XmlPullParserException * @return Date */ - private java.util.Date getDateValue( String s, String attribute, XmlPullParser parser ) - throws XmlPullParserException - { - return getDateValue( s, attribute, null, parser ); - } //-- java.util.Date getDateValue( String, String, XmlPullParser ) + private java.util.Date getDateValue(String s, String attribute, XmlPullParser parser) + throws XmlPullParserException { + return getDateValue(s, attribute, null, parser); + } // -- java.util.Date getDateValue( String, String, XmlPullParser ) /** * Method getDateValue. - * + * * @param s * @param parser * @param dateFormat @@ -289,46 +261,34 @@ private java.util.Date getDateValue( String s, String attribute, XmlPullParser p * @throws XmlPullParserException * @return Date */ - private java.util.Date getDateValue( String s, String attribute, String dateFormat, XmlPullParser parser ) - throws XmlPullParserException - { - if ( s != null ) - { + private java.util.Date getDateValue(String s, String attribute, String dateFormat, XmlPullParser parser) + throws XmlPullParserException { + if (s != null) { String effectiveDateFormat = dateFormat; - if ( dateFormat == null ) - { + if (dateFormat == null) { effectiveDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"; } - if ( "long".equals( effectiveDateFormat ) ) - { - try - { - return new java.util.Date( Long.parseLong( s ) ); - } - catch ( NumberFormatException e ) - { - throw new XmlPullParserException( e.getMessage(), parser, e ); - } - } - else - { - try - { - DateFormat dateParser = new java.text.SimpleDateFormat( effectiveDateFormat, java.util.Locale.US ); - return dateParser.parse( s ); + if ("long".equals(effectiveDateFormat)) { + try { + return new java.util.Date(Long.parseLong(s)); + } catch (NumberFormatException e) { + throw new XmlPullParserException(e.getMessage(), parser, e); } - catch ( java.text.ParseException e ) - { - throw new XmlPullParserException( e.getMessage(), parser, e ); + } else { + try { + DateFormat dateParser = new java.text.SimpleDateFormat(effectiveDateFormat, java.util.Locale.US); + return dateParser.parse(s); + } catch (java.text.ParseException e) { + throw new XmlPullParserException(e.getMessage(), parser, e); } } } return null; - } //-- java.util.Date getDateValue( String, String, String, XmlPullParser ) + } // -- java.util.Date getDateValue( String, String, String, XmlPullParser ) /** * Method getDoubleValue. - * + * * @param s * @param strict * @param parser @@ -336,29 +296,26 @@ private java.util.Date getDateValue( String s, String attribute, String dateForm * @throws XmlPullParserException * @return double */ - private double getDoubleValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Double.valueOf( s ).doubleValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be a floating point number", parser, nfe ); + private double getDoubleValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Double.valueOf(s).doubleValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be a floating point number", + parser, + nfe); } } } return 0; - } //-- double getDoubleValue( String, String, XmlPullParser, boolean ) + } // -- double getDoubleValue( String, String, XmlPullParser, boolean ) /** * Method getFloatValue. - * + * * @param s * @param strict * @param parser @@ -366,29 +323,26 @@ private double getDoubleValue( String s, String attribute, XmlPullParser parser, * @throws XmlPullParserException * @return float */ - private float getFloatValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Float.valueOf( s ).floatValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be a floating point number", parser, nfe ); + private float getFloatValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Float.valueOf(s).floatValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be a floating point number", + parser, + nfe); } } } return 0; - } //-- float getFloatValue( String, String, XmlPullParser, boolean ) + } // -- float getFloatValue( String, String, XmlPullParser, boolean ) /** * Method getIntegerValue. - * + * * @param s * @param strict * @param parser @@ -396,29 +350,24 @@ private float getFloatValue( String s, String attribute, XmlPullParser parser, b * @throws XmlPullParserException * @return int */ - private int getIntegerValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Integer.valueOf( s ).intValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be an integer", parser, nfe ); + private int getIntegerValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Integer.valueOf(s).intValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be an integer", parser, nfe); } } } return 0; - } //-- int getIntegerValue( String, String, XmlPullParser, boolean ) + } // -- int getIntegerValue( String, String, XmlPullParser, boolean ) /** * Method getLongValue. - * + * * @param s * @param strict * @param parser @@ -426,29 +375,24 @@ private int getIntegerValue( String s, String attribute, XmlPullParser parser, b * @throws XmlPullParserException * @return long */ - private long getLongValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Long.valueOf( s ).longValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be a long integer", parser, nfe ); + private long getLongValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Long.valueOf(s).longValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be a long integer", parser, nfe); } } } return 0; - } //-- long getLongValue( String, String, XmlPullParser, boolean ) + } // -- long getLongValue( String, String, XmlPullParser, boolean ) /** * Method getRequiredAttributeValue. - * + * * @param s * @param strict * @param parser @@ -456,22 +400,20 @@ private long getLongValue( String s, String attribute, XmlPullParser parser, boo * @throws XmlPullParserException * @return String */ - private String getRequiredAttributeValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s == null ) - { - if ( strict ) - { - throw new XmlPullParserException( "Missing required value for attribute '" + attribute + "'", parser, null ); + private String getRequiredAttributeValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s == null) { + if (strict) { + throw new XmlPullParserException( + "Missing required value for attribute '" + attribute + "'", parser, null); } } return s; - } //-- String getRequiredAttributeValue( String, String, XmlPullParser, boolean ) + } // -- String getRequiredAttributeValue( String, String, XmlPullParser, boolean ) /** * Method getShortValue. - * + * * @param s * @param strict * @param parser @@ -479,3581 +421,2602 @@ private String getRequiredAttributeValue( String s, String attribute, XmlPullPar * @throws XmlPullParserException * @return short */ - private short getShortValue( String s, String attribute, XmlPullParser parser, boolean strict ) - throws XmlPullParserException - { - if ( s != null ) - { - try - { - return Short.valueOf( s ).shortValue(); - } - catch ( NumberFormatException nfe ) - { - if ( strict ) - { - throw new XmlPullParserException( "Unable to parse element '" + attribute + "', must be a short integer", parser, nfe ); + private short getShortValue(String s, String attribute, XmlPullParser parser, boolean strict) + throws XmlPullParserException { + if (s != null) { + try { + return Short.valueOf(s).shortValue(); + } catch (NumberFormatException nfe) { + if (strict) { + throw new XmlPullParserException( + "Unable to parse element '" + attribute + "', must be a short integer", parser, nfe); } } } return 0; - } //-- short getShortValue( String, String, XmlPullParser, boolean ) + } // -- short getShortValue( String, String, XmlPullParser, boolean ) /** * Method getTrimmedValue. - * + * * @param s * @return String */ - private String getTrimmedValue( String s ) - { - if ( s != null ) - { + private String getTrimmedValue(String s) { + if (s != null) { s = s.trim(); } return s; - } //-- String getTrimmedValue( String ) + } // -- String getTrimmedValue( String ) /** * Method initParser. - * + * * @param parser * @throws XmlPullParserException */ - private void initParser( XmlPullParser parser ) - throws XmlPullParserException - { - if ( addDefaultEntities ) - { + private void initParser(XmlPullParser parser) throws XmlPullParserException { + if (addDefaultEntities) { // ---------------------------------------------------------------------- // Latin 1 entities // ---------------------------------------------------------------------- - parser.defineEntityReplacementText( "nbsp", "\u00a0" ); - parser.defineEntityReplacementText( "iexcl", "\u00a1" ); - parser.defineEntityReplacementText( "cent", "\u00a2" ); - parser.defineEntityReplacementText( "pound", "\u00a3" ); - parser.defineEntityReplacementText( "curren", "\u00a4" ); - parser.defineEntityReplacementText( "yen", "\u00a5" ); - parser.defineEntityReplacementText( "brvbar", "\u00a6" ); - parser.defineEntityReplacementText( "sect", "\u00a7" ); - parser.defineEntityReplacementText( "uml", "\u00a8" ); - parser.defineEntityReplacementText( "copy", "\u00a9" ); - parser.defineEntityReplacementText( "ordf", "\u00aa" ); - parser.defineEntityReplacementText( "laquo", "\u00ab" ); - parser.defineEntityReplacementText( "not", "\u00ac" ); - parser.defineEntityReplacementText( "shy", "\u00ad" ); - parser.defineEntityReplacementText( "reg", "\u00ae" ); - parser.defineEntityReplacementText( "macr", "\u00af" ); - parser.defineEntityReplacementText( "deg", "\u00b0" ); - parser.defineEntityReplacementText( "plusmn", "\u00b1" ); - parser.defineEntityReplacementText( "sup2", "\u00b2" ); - parser.defineEntityReplacementText( "sup3", "\u00b3" ); - parser.defineEntityReplacementText( "acute", "\u00b4" ); - parser.defineEntityReplacementText( "micro", "\u00b5" ); - parser.defineEntityReplacementText( "para", "\u00b6" ); - parser.defineEntityReplacementText( "middot", "\u00b7" ); - parser.defineEntityReplacementText( "cedil", "\u00b8" ); - parser.defineEntityReplacementText( "sup1", "\u00b9" ); - parser.defineEntityReplacementText( "ordm", "\u00ba" ); - parser.defineEntityReplacementText( "raquo", "\u00bb" ); - parser.defineEntityReplacementText( "frac14", "\u00bc" ); - parser.defineEntityReplacementText( "frac12", "\u00bd" ); - parser.defineEntityReplacementText( "frac34", "\u00be" ); - parser.defineEntityReplacementText( "iquest", "\u00bf" ); - parser.defineEntityReplacementText( "Agrave", "\u00c0" ); - parser.defineEntityReplacementText( "Aacute", "\u00c1" ); - parser.defineEntityReplacementText( "Acirc", "\u00c2" ); - parser.defineEntityReplacementText( "Atilde", "\u00c3" ); - parser.defineEntityReplacementText( "Auml", "\u00c4" ); - parser.defineEntityReplacementText( "Aring", "\u00c5" ); - parser.defineEntityReplacementText( "AElig", "\u00c6" ); - parser.defineEntityReplacementText( "Ccedil", "\u00c7" ); - parser.defineEntityReplacementText( "Egrave", "\u00c8" ); - parser.defineEntityReplacementText( "Eacute", "\u00c9" ); - parser.defineEntityReplacementText( "Ecirc", "\u00ca" ); - parser.defineEntityReplacementText( "Euml", "\u00cb" ); - parser.defineEntityReplacementText( "Igrave", "\u00cc" ); - parser.defineEntityReplacementText( "Iacute", "\u00cd" ); - parser.defineEntityReplacementText( "Icirc", "\u00ce" ); - parser.defineEntityReplacementText( "Iuml", "\u00cf" ); - parser.defineEntityReplacementText( "ETH", "\u00d0" ); - parser.defineEntityReplacementText( "Ntilde", "\u00d1" ); - parser.defineEntityReplacementText( "Ograve", "\u00d2" ); - parser.defineEntityReplacementText( "Oacute", "\u00d3" ); - parser.defineEntityReplacementText( "Ocirc", "\u00d4" ); - parser.defineEntityReplacementText( "Otilde", "\u00d5" ); - parser.defineEntityReplacementText( "Ouml", "\u00d6" ); - parser.defineEntityReplacementText( "times", "\u00d7" ); - parser.defineEntityReplacementText( "Oslash", "\u00d8" ); - parser.defineEntityReplacementText( "Ugrave", "\u00d9" ); - parser.defineEntityReplacementText( "Uacute", "\u00da" ); - parser.defineEntityReplacementText( "Ucirc", "\u00db" ); - parser.defineEntityReplacementText( "Uuml", "\u00dc" ); - parser.defineEntityReplacementText( "Yacute", "\u00dd" ); - parser.defineEntityReplacementText( "THORN", "\u00de" ); - parser.defineEntityReplacementText( "szlig", "\u00df" ); - parser.defineEntityReplacementText( "agrave", "\u00e0" ); - parser.defineEntityReplacementText( "aacute", "\u00e1" ); - parser.defineEntityReplacementText( "acirc", "\u00e2" ); - parser.defineEntityReplacementText( "atilde", "\u00e3" ); - parser.defineEntityReplacementText( "auml", "\u00e4" ); - parser.defineEntityReplacementText( "aring", "\u00e5" ); - parser.defineEntityReplacementText( "aelig", "\u00e6" ); - parser.defineEntityReplacementText( "ccedil", "\u00e7" ); - parser.defineEntityReplacementText( "egrave", "\u00e8" ); - parser.defineEntityReplacementText( "eacute", "\u00e9" ); - parser.defineEntityReplacementText( "ecirc", "\u00ea" ); - parser.defineEntityReplacementText( "euml", "\u00eb" ); - parser.defineEntityReplacementText( "igrave", "\u00ec" ); - parser.defineEntityReplacementText( "iacute", "\u00ed" ); - parser.defineEntityReplacementText( "icirc", "\u00ee" ); - parser.defineEntityReplacementText( "iuml", "\u00ef" ); - parser.defineEntityReplacementText( "eth", "\u00f0" ); - parser.defineEntityReplacementText( "ntilde", "\u00f1" ); - parser.defineEntityReplacementText( "ograve", "\u00f2" ); - parser.defineEntityReplacementText( "oacute", "\u00f3" ); - parser.defineEntityReplacementText( "ocirc", "\u00f4" ); - parser.defineEntityReplacementText( "otilde", "\u00f5" ); - parser.defineEntityReplacementText( "ouml", "\u00f6" ); - parser.defineEntityReplacementText( "divide", "\u00f7" ); - parser.defineEntityReplacementText( "oslash", "\u00f8" ); - parser.defineEntityReplacementText( "ugrave", "\u00f9" ); - parser.defineEntityReplacementText( "uacute", "\u00fa" ); - parser.defineEntityReplacementText( "ucirc", "\u00fb" ); - parser.defineEntityReplacementText( "uuml", "\u00fc" ); - parser.defineEntityReplacementText( "yacute", "\u00fd" ); - parser.defineEntityReplacementText( "thorn", "\u00fe" ); - parser.defineEntityReplacementText( "yuml", "\u00ff" ); + parser.defineEntityReplacementText("nbsp", "\u00a0"); + parser.defineEntityReplacementText("iexcl", "\u00a1"); + parser.defineEntityReplacementText("cent", "\u00a2"); + parser.defineEntityReplacementText("pound", "\u00a3"); + parser.defineEntityReplacementText("curren", "\u00a4"); + parser.defineEntityReplacementText("yen", "\u00a5"); + parser.defineEntityReplacementText("brvbar", "\u00a6"); + parser.defineEntityReplacementText("sect", "\u00a7"); + parser.defineEntityReplacementText("uml", "\u00a8"); + parser.defineEntityReplacementText("copy", "\u00a9"); + parser.defineEntityReplacementText("ordf", "\u00aa"); + parser.defineEntityReplacementText("laquo", "\u00ab"); + parser.defineEntityReplacementText("not", "\u00ac"); + parser.defineEntityReplacementText("shy", "\u00ad"); + parser.defineEntityReplacementText("reg", "\u00ae"); + parser.defineEntityReplacementText("macr", "\u00af"); + parser.defineEntityReplacementText("deg", "\u00b0"); + parser.defineEntityReplacementText("plusmn", "\u00b1"); + parser.defineEntityReplacementText("sup2", "\u00b2"); + parser.defineEntityReplacementText("sup3", "\u00b3"); + parser.defineEntityReplacementText("acute", "\u00b4"); + parser.defineEntityReplacementText("micro", "\u00b5"); + parser.defineEntityReplacementText("para", "\u00b6"); + parser.defineEntityReplacementText("middot", "\u00b7"); + parser.defineEntityReplacementText("cedil", "\u00b8"); + parser.defineEntityReplacementText("sup1", "\u00b9"); + parser.defineEntityReplacementText("ordm", "\u00ba"); + parser.defineEntityReplacementText("raquo", "\u00bb"); + parser.defineEntityReplacementText("frac14", "\u00bc"); + parser.defineEntityReplacementText("frac12", "\u00bd"); + parser.defineEntityReplacementText("frac34", "\u00be"); + parser.defineEntityReplacementText("iquest", "\u00bf"); + parser.defineEntityReplacementText("Agrave", "\u00c0"); + parser.defineEntityReplacementText("Aacute", "\u00c1"); + parser.defineEntityReplacementText("Acirc", "\u00c2"); + parser.defineEntityReplacementText("Atilde", "\u00c3"); + parser.defineEntityReplacementText("Auml", "\u00c4"); + parser.defineEntityReplacementText("Aring", "\u00c5"); + parser.defineEntityReplacementText("AElig", "\u00c6"); + parser.defineEntityReplacementText("Ccedil", "\u00c7"); + parser.defineEntityReplacementText("Egrave", "\u00c8"); + parser.defineEntityReplacementText("Eacute", "\u00c9"); + parser.defineEntityReplacementText("Ecirc", "\u00ca"); + parser.defineEntityReplacementText("Euml", "\u00cb"); + parser.defineEntityReplacementText("Igrave", "\u00cc"); + parser.defineEntityReplacementText("Iacute", "\u00cd"); + parser.defineEntityReplacementText("Icirc", "\u00ce"); + parser.defineEntityReplacementText("Iuml", "\u00cf"); + parser.defineEntityReplacementText("ETH", "\u00d0"); + parser.defineEntityReplacementText("Ntilde", "\u00d1"); + parser.defineEntityReplacementText("Ograve", "\u00d2"); + parser.defineEntityReplacementText("Oacute", "\u00d3"); + parser.defineEntityReplacementText("Ocirc", "\u00d4"); + parser.defineEntityReplacementText("Otilde", "\u00d5"); + parser.defineEntityReplacementText("Ouml", "\u00d6"); + parser.defineEntityReplacementText("times", "\u00d7"); + parser.defineEntityReplacementText("Oslash", "\u00d8"); + parser.defineEntityReplacementText("Ugrave", "\u00d9"); + parser.defineEntityReplacementText("Uacute", "\u00da"); + parser.defineEntityReplacementText("Ucirc", "\u00db"); + parser.defineEntityReplacementText("Uuml", "\u00dc"); + parser.defineEntityReplacementText("Yacute", "\u00dd"); + parser.defineEntityReplacementText("THORN", "\u00de"); + parser.defineEntityReplacementText("szlig", "\u00df"); + parser.defineEntityReplacementText("agrave", "\u00e0"); + parser.defineEntityReplacementText("aacute", "\u00e1"); + parser.defineEntityReplacementText("acirc", "\u00e2"); + parser.defineEntityReplacementText("atilde", "\u00e3"); + parser.defineEntityReplacementText("auml", "\u00e4"); + parser.defineEntityReplacementText("aring", "\u00e5"); + parser.defineEntityReplacementText("aelig", "\u00e6"); + parser.defineEntityReplacementText("ccedil", "\u00e7"); + parser.defineEntityReplacementText("egrave", "\u00e8"); + parser.defineEntityReplacementText("eacute", "\u00e9"); + parser.defineEntityReplacementText("ecirc", "\u00ea"); + parser.defineEntityReplacementText("euml", "\u00eb"); + parser.defineEntityReplacementText("igrave", "\u00ec"); + parser.defineEntityReplacementText("iacute", "\u00ed"); + parser.defineEntityReplacementText("icirc", "\u00ee"); + parser.defineEntityReplacementText("iuml", "\u00ef"); + parser.defineEntityReplacementText("eth", "\u00f0"); + parser.defineEntityReplacementText("ntilde", "\u00f1"); + parser.defineEntityReplacementText("ograve", "\u00f2"); + parser.defineEntityReplacementText("oacute", "\u00f3"); + parser.defineEntityReplacementText("ocirc", "\u00f4"); + parser.defineEntityReplacementText("otilde", "\u00f5"); + parser.defineEntityReplacementText("ouml", "\u00f6"); + parser.defineEntityReplacementText("divide", "\u00f7"); + parser.defineEntityReplacementText("oslash", "\u00f8"); + parser.defineEntityReplacementText("ugrave", "\u00f9"); + parser.defineEntityReplacementText("uacute", "\u00fa"); + parser.defineEntityReplacementText("ucirc", "\u00fb"); + parser.defineEntityReplacementText("uuml", "\u00fc"); + parser.defineEntityReplacementText("yacute", "\u00fd"); + parser.defineEntityReplacementText("thorn", "\u00fe"); + parser.defineEntityReplacementText("yuml", "\u00ff"); // ---------------------------------------------------------------------- // Special entities // ---------------------------------------------------------------------- - parser.defineEntityReplacementText( "OElig", "\u0152" ); - parser.defineEntityReplacementText( "oelig", "\u0153" ); - parser.defineEntityReplacementText( "Scaron", "\u0160" ); - parser.defineEntityReplacementText( "scaron", "\u0161" ); - parser.defineEntityReplacementText( "Yuml", "\u0178" ); - parser.defineEntityReplacementText( "circ", "\u02c6" ); - parser.defineEntityReplacementText( "tilde", "\u02dc" ); - parser.defineEntityReplacementText( "ensp", "\u2002" ); - parser.defineEntityReplacementText( "emsp", "\u2003" ); - parser.defineEntityReplacementText( "thinsp", "\u2009" ); - parser.defineEntityReplacementText( "zwnj", "\u200c" ); - parser.defineEntityReplacementText( "zwj", "\u200d" ); - parser.defineEntityReplacementText( "lrm", "\u200e" ); - parser.defineEntityReplacementText( "rlm", "\u200f" ); - parser.defineEntityReplacementText( "ndash", "\u2013" ); - parser.defineEntityReplacementText( "mdash", "\u2014" ); - parser.defineEntityReplacementText( "lsquo", "\u2018" ); - parser.defineEntityReplacementText( "rsquo", "\u2019" ); - parser.defineEntityReplacementText( "sbquo", "\u201a" ); - parser.defineEntityReplacementText( "ldquo", "\u201c" ); - parser.defineEntityReplacementText( "rdquo", "\u201d" ); - parser.defineEntityReplacementText( "bdquo", "\u201e" ); - parser.defineEntityReplacementText( "dagger", "\u2020" ); - parser.defineEntityReplacementText( "Dagger", "\u2021" ); - parser.defineEntityReplacementText( "permil", "\u2030" ); - parser.defineEntityReplacementText( "lsaquo", "\u2039" ); - parser.defineEntityReplacementText( "rsaquo", "\u203a" ); - parser.defineEntityReplacementText( "euro", "\u20ac" ); + parser.defineEntityReplacementText("OElig", "\u0152"); + parser.defineEntityReplacementText("oelig", "\u0153"); + parser.defineEntityReplacementText("Scaron", "\u0160"); + parser.defineEntityReplacementText("scaron", "\u0161"); + parser.defineEntityReplacementText("Yuml", "\u0178"); + parser.defineEntityReplacementText("circ", "\u02c6"); + parser.defineEntityReplacementText("tilde", "\u02dc"); + parser.defineEntityReplacementText("ensp", "\u2002"); + parser.defineEntityReplacementText("emsp", "\u2003"); + parser.defineEntityReplacementText("thinsp", "\u2009"); + parser.defineEntityReplacementText("zwnj", "\u200c"); + parser.defineEntityReplacementText("zwj", "\u200d"); + parser.defineEntityReplacementText("lrm", "\u200e"); + parser.defineEntityReplacementText("rlm", "\u200f"); + parser.defineEntityReplacementText("ndash", "\u2013"); + parser.defineEntityReplacementText("mdash", "\u2014"); + parser.defineEntityReplacementText("lsquo", "\u2018"); + parser.defineEntityReplacementText("rsquo", "\u2019"); + parser.defineEntityReplacementText("sbquo", "\u201a"); + parser.defineEntityReplacementText("ldquo", "\u201c"); + parser.defineEntityReplacementText("rdquo", "\u201d"); + parser.defineEntityReplacementText("bdquo", "\u201e"); + parser.defineEntityReplacementText("dagger", "\u2020"); + parser.defineEntityReplacementText("Dagger", "\u2021"); + parser.defineEntityReplacementText("permil", "\u2030"); + parser.defineEntityReplacementText("lsaquo", "\u2039"); + parser.defineEntityReplacementText("rsaquo", "\u203a"); + parser.defineEntityReplacementText("euro", "\u20ac"); // ---------------------------------------------------------------------- // Symbol entities // ---------------------------------------------------------------------- - parser.defineEntityReplacementText( "fnof", "\u0192" ); - parser.defineEntityReplacementText( "Alpha", "\u0391" ); - parser.defineEntityReplacementText( "Beta", "\u0392" ); - parser.defineEntityReplacementText( "Gamma", "\u0393" ); - parser.defineEntityReplacementText( "Delta", "\u0394" ); - parser.defineEntityReplacementText( "Epsilon", "\u0395" ); - parser.defineEntityReplacementText( "Zeta", "\u0396" ); - parser.defineEntityReplacementText( "Eta", "\u0397" ); - parser.defineEntityReplacementText( "Theta", "\u0398" ); - parser.defineEntityReplacementText( "Iota", "\u0399" ); - parser.defineEntityReplacementText( "Kappa", "\u039a" ); - parser.defineEntityReplacementText( "Lambda", "\u039b" ); - parser.defineEntityReplacementText( "Mu", "\u039c" ); - parser.defineEntityReplacementText( "Nu", "\u039d" ); - parser.defineEntityReplacementText( "Xi", "\u039e" ); - parser.defineEntityReplacementText( "Omicron", "\u039f" ); - parser.defineEntityReplacementText( "Pi", "\u03a0" ); - parser.defineEntityReplacementText( "Rho", "\u03a1" ); - parser.defineEntityReplacementText( "Sigma", "\u03a3" ); - parser.defineEntityReplacementText( "Tau", "\u03a4" ); - parser.defineEntityReplacementText( "Upsilon", "\u03a5" ); - parser.defineEntityReplacementText( "Phi", "\u03a6" ); - parser.defineEntityReplacementText( "Chi", "\u03a7" ); - parser.defineEntityReplacementText( "Psi", "\u03a8" ); - parser.defineEntityReplacementText( "Omega", "\u03a9" ); - parser.defineEntityReplacementText( "alpha", "\u03b1" ); - parser.defineEntityReplacementText( "beta", "\u03b2" ); - parser.defineEntityReplacementText( "gamma", "\u03b3" ); - parser.defineEntityReplacementText( "delta", "\u03b4" ); - parser.defineEntityReplacementText( "epsilon", "\u03b5" ); - parser.defineEntityReplacementText( "zeta", "\u03b6" ); - parser.defineEntityReplacementText( "eta", "\u03b7" ); - parser.defineEntityReplacementText( "theta", "\u03b8" ); - parser.defineEntityReplacementText( "iota", "\u03b9" ); - parser.defineEntityReplacementText( "kappa", "\u03ba" ); - parser.defineEntityReplacementText( "lambda", "\u03bb" ); - parser.defineEntityReplacementText( "mu", "\u03bc" ); - parser.defineEntityReplacementText( "nu", "\u03bd" ); - parser.defineEntityReplacementText( "xi", "\u03be" ); - parser.defineEntityReplacementText( "omicron", "\u03bf" ); - parser.defineEntityReplacementText( "pi", "\u03c0" ); - parser.defineEntityReplacementText( "rho", "\u03c1" ); - parser.defineEntityReplacementText( "sigmaf", "\u03c2" ); - parser.defineEntityReplacementText( "sigma", "\u03c3" ); - parser.defineEntityReplacementText( "tau", "\u03c4" ); - parser.defineEntityReplacementText( "upsilon", "\u03c5" ); - parser.defineEntityReplacementText( "phi", "\u03c6" ); - parser.defineEntityReplacementText( "chi", "\u03c7" ); - parser.defineEntityReplacementText( "psi", "\u03c8" ); - parser.defineEntityReplacementText( "omega", "\u03c9" ); - parser.defineEntityReplacementText( "thetasym", "\u03d1" ); - parser.defineEntityReplacementText( "upsih", "\u03d2" ); - parser.defineEntityReplacementText( "piv", "\u03d6" ); - parser.defineEntityReplacementText( "bull", "\u2022" ); - parser.defineEntityReplacementText( "hellip", "\u2026" ); - parser.defineEntityReplacementText( "prime", "\u2032" ); - parser.defineEntityReplacementText( "Prime", "\u2033" ); - parser.defineEntityReplacementText( "oline", "\u203e" ); - parser.defineEntityReplacementText( "frasl", "\u2044" ); - parser.defineEntityReplacementText( "weierp", "\u2118" ); - parser.defineEntityReplacementText( "image", "\u2111" ); - parser.defineEntityReplacementText( "real", "\u211c" ); - parser.defineEntityReplacementText( "trade", "\u2122" ); - parser.defineEntityReplacementText( "alefsym", "\u2135" ); - parser.defineEntityReplacementText( "larr", "\u2190" ); - parser.defineEntityReplacementText( "uarr", "\u2191" ); - parser.defineEntityReplacementText( "rarr", "\u2192" ); - parser.defineEntityReplacementText( "darr", "\u2193" ); - parser.defineEntityReplacementText( "harr", "\u2194" ); - parser.defineEntityReplacementText( "crarr", "\u21b5" ); - parser.defineEntityReplacementText( "lArr", "\u21d0" ); - parser.defineEntityReplacementText( "uArr", "\u21d1" ); - parser.defineEntityReplacementText( "rArr", "\u21d2" ); - parser.defineEntityReplacementText( "dArr", "\u21d3" ); - parser.defineEntityReplacementText( "hArr", "\u21d4" ); - parser.defineEntityReplacementText( "forall", "\u2200" ); - parser.defineEntityReplacementText( "part", "\u2202" ); - parser.defineEntityReplacementText( "exist", "\u2203" ); - parser.defineEntityReplacementText( "empty", "\u2205" ); - parser.defineEntityReplacementText( "nabla", "\u2207" ); - parser.defineEntityReplacementText( "isin", "\u2208" ); - parser.defineEntityReplacementText( "notin", "\u2209" ); - parser.defineEntityReplacementText( "ni", "\u220b" ); - parser.defineEntityReplacementText( "prod", "\u220f" ); - parser.defineEntityReplacementText( "sum", "\u2211" ); - parser.defineEntityReplacementText( "minus", "\u2212" ); - parser.defineEntityReplacementText( "lowast", "\u2217" ); - parser.defineEntityReplacementText( "radic", "\u221a" ); - parser.defineEntityReplacementText( "prop", "\u221d" ); - parser.defineEntityReplacementText( "infin", "\u221e" ); - parser.defineEntityReplacementText( "ang", "\u2220" ); - parser.defineEntityReplacementText( "and", "\u2227" ); - parser.defineEntityReplacementText( "or", "\u2228" ); - parser.defineEntityReplacementText( "cap", "\u2229" ); - parser.defineEntityReplacementText( "cup", "\u222a" ); - parser.defineEntityReplacementText( "int", "\u222b" ); - parser.defineEntityReplacementText( "there4", "\u2234" ); - parser.defineEntityReplacementText( "sim", "\u223c" ); - parser.defineEntityReplacementText( "cong", "\u2245" ); - parser.defineEntityReplacementText( "asymp", "\u2248" ); - parser.defineEntityReplacementText( "ne", "\u2260" ); - parser.defineEntityReplacementText( "equiv", "\u2261" ); - parser.defineEntityReplacementText( "le", "\u2264" ); - parser.defineEntityReplacementText( "ge", "\u2265" ); - parser.defineEntityReplacementText( "sub", "\u2282" ); - parser.defineEntityReplacementText( "sup", "\u2283" ); - parser.defineEntityReplacementText( "nsub", "\u2284" ); - parser.defineEntityReplacementText( "sube", "\u2286" ); - parser.defineEntityReplacementText( "supe", "\u2287" ); - parser.defineEntityReplacementText( "oplus", "\u2295" ); - parser.defineEntityReplacementText( "otimes", "\u2297" ); - parser.defineEntityReplacementText( "perp", "\u22a5" ); - parser.defineEntityReplacementText( "sdot", "\u22c5" ); - parser.defineEntityReplacementText( "lceil", "\u2308" ); - parser.defineEntityReplacementText( "rceil", "\u2309" ); - parser.defineEntityReplacementText( "lfloor", "\u230a" ); - parser.defineEntityReplacementText( "rfloor", "\u230b" ); - parser.defineEntityReplacementText( "lang", "\u2329" ); - parser.defineEntityReplacementText( "rang", "\u232a" ); - parser.defineEntityReplacementText( "loz", "\u25ca" ); - parser.defineEntityReplacementText( "spades", "\u2660" ); - parser.defineEntityReplacementText( "clubs", "\u2663" ); - parser.defineEntityReplacementText( "hearts", "\u2665" ); - parser.defineEntityReplacementText( "diams", "\u2666" ); - - } - } //-- void initParser( XmlPullParser ) + parser.defineEntityReplacementText("fnof", "\u0192"); + parser.defineEntityReplacementText("Alpha", "\u0391"); + parser.defineEntityReplacementText("Beta", "\u0392"); + parser.defineEntityReplacementText("Gamma", "\u0393"); + parser.defineEntityReplacementText("Delta", "\u0394"); + parser.defineEntityReplacementText("Epsilon", "\u0395"); + parser.defineEntityReplacementText("Zeta", "\u0396"); + parser.defineEntityReplacementText("Eta", "\u0397"); + parser.defineEntityReplacementText("Theta", "\u0398"); + parser.defineEntityReplacementText("Iota", "\u0399"); + parser.defineEntityReplacementText("Kappa", "\u039a"); + parser.defineEntityReplacementText("Lambda", "\u039b"); + parser.defineEntityReplacementText("Mu", "\u039c"); + parser.defineEntityReplacementText("Nu", "\u039d"); + parser.defineEntityReplacementText("Xi", "\u039e"); + parser.defineEntityReplacementText("Omicron", "\u039f"); + parser.defineEntityReplacementText("Pi", "\u03a0"); + parser.defineEntityReplacementText("Rho", "\u03a1"); + parser.defineEntityReplacementText("Sigma", "\u03a3"); + parser.defineEntityReplacementText("Tau", "\u03a4"); + parser.defineEntityReplacementText("Upsilon", "\u03a5"); + parser.defineEntityReplacementText("Phi", "\u03a6"); + parser.defineEntityReplacementText("Chi", "\u03a7"); + parser.defineEntityReplacementText("Psi", "\u03a8"); + parser.defineEntityReplacementText("Omega", "\u03a9"); + parser.defineEntityReplacementText("alpha", "\u03b1"); + parser.defineEntityReplacementText("beta", "\u03b2"); + parser.defineEntityReplacementText("gamma", "\u03b3"); + parser.defineEntityReplacementText("delta", "\u03b4"); + parser.defineEntityReplacementText("epsilon", "\u03b5"); + parser.defineEntityReplacementText("zeta", "\u03b6"); + parser.defineEntityReplacementText("eta", "\u03b7"); + parser.defineEntityReplacementText("theta", "\u03b8"); + parser.defineEntityReplacementText("iota", "\u03b9"); + parser.defineEntityReplacementText("kappa", "\u03ba"); + parser.defineEntityReplacementText("lambda", "\u03bb"); + parser.defineEntityReplacementText("mu", "\u03bc"); + parser.defineEntityReplacementText("nu", "\u03bd"); + parser.defineEntityReplacementText("xi", "\u03be"); + parser.defineEntityReplacementText("omicron", "\u03bf"); + parser.defineEntityReplacementText("pi", "\u03c0"); + parser.defineEntityReplacementText("rho", "\u03c1"); + parser.defineEntityReplacementText("sigmaf", "\u03c2"); + parser.defineEntityReplacementText("sigma", "\u03c3"); + parser.defineEntityReplacementText("tau", "\u03c4"); + parser.defineEntityReplacementText("upsilon", "\u03c5"); + parser.defineEntityReplacementText("phi", "\u03c6"); + parser.defineEntityReplacementText("chi", "\u03c7"); + parser.defineEntityReplacementText("psi", "\u03c8"); + parser.defineEntityReplacementText("omega", "\u03c9"); + parser.defineEntityReplacementText("thetasym", "\u03d1"); + parser.defineEntityReplacementText("upsih", "\u03d2"); + parser.defineEntityReplacementText("piv", "\u03d6"); + parser.defineEntityReplacementText("bull", "\u2022"); + parser.defineEntityReplacementText("hellip", "\u2026"); + parser.defineEntityReplacementText("prime", "\u2032"); + parser.defineEntityReplacementText("Prime", "\u2033"); + parser.defineEntityReplacementText("oline", "\u203e"); + parser.defineEntityReplacementText("frasl", "\u2044"); + parser.defineEntityReplacementText("weierp", "\u2118"); + parser.defineEntityReplacementText("image", "\u2111"); + parser.defineEntityReplacementText("real", "\u211c"); + parser.defineEntityReplacementText("trade", "\u2122"); + parser.defineEntityReplacementText("alefsym", "\u2135"); + parser.defineEntityReplacementText("larr", "\u2190"); + parser.defineEntityReplacementText("uarr", "\u2191"); + parser.defineEntityReplacementText("rarr", "\u2192"); + parser.defineEntityReplacementText("darr", "\u2193"); + parser.defineEntityReplacementText("harr", "\u2194"); + parser.defineEntityReplacementText("crarr", "\u21b5"); + parser.defineEntityReplacementText("lArr", "\u21d0"); + parser.defineEntityReplacementText("uArr", "\u21d1"); + parser.defineEntityReplacementText("rArr", "\u21d2"); + parser.defineEntityReplacementText("dArr", "\u21d3"); + parser.defineEntityReplacementText("hArr", "\u21d4"); + parser.defineEntityReplacementText("forall", "\u2200"); + parser.defineEntityReplacementText("part", "\u2202"); + parser.defineEntityReplacementText("exist", "\u2203"); + parser.defineEntityReplacementText("empty", "\u2205"); + parser.defineEntityReplacementText("nabla", "\u2207"); + parser.defineEntityReplacementText("isin", "\u2208"); + parser.defineEntityReplacementText("notin", "\u2209"); + parser.defineEntityReplacementText("ni", "\u220b"); + parser.defineEntityReplacementText("prod", "\u220f"); + parser.defineEntityReplacementText("sum", "\u2211"); + parser.defineEntityReplacementText("minus", "\u2212"); + parser.defineEntityReplacementText("lowast", "\u2217"); + parser.defineEntityReplacementText("radic", "\u221a"); + parser.defineEntityReplacementText("prop", "\u221d"); + parser.defineEntityReplacementText("infin", "\u221e"); + parser.defineEntityReplacementText("ang", "\u2220"); + parser.defineEntityReplacementText("and", "\u2227"); + parser.defineEntityReplacementText("or", "\u2228"); + parser.defineEntityReplacementText("cap", "\u2229"); + parser.defineEntityReplacementText("cup", "\u222a"); + parser.defineEntityReplacementText("int", "\u222b"); + parser.defineEntityReplacementText("there4", "\u2234"); + parser.defineEntityReplacementText("sim", "\u223c"); + parser.defineEntityReplacementText("cong", "\u2245"); + parser.defineEntityReplacementText("asymp", "\u2248"); + parser.defineEntityReplacementText("ne", "\u2260"); + parser.defineEntityReplacementText("equiv", "\u2261"); + parser.defineEntityReplacementText("le", "\u2264"); + parser.defineEntityReplacementText("ge", "\u2265"); + parser.defineEntityReplacementText("sub", "\u2282"); + parser.defineEntityReplacementText("sup", "\u2283"); + parser.defineEntityReplacementText("nsub", "\u2284"); + parser.defineEntityReplacementText("sube", "\u2286"); + parser.defineEntityReplacementText("supe", "\u2287"); + parser.defineEntityReplacementText("oplus", "\u2295"); + parser.defineEntityReplacementText("otimes", "\u2297"); + parser.defineEntityReplacementText("perp", "\u22a5"); + parser.defineEntityReplacementText("sdot", "\u22c5"); + parser.defineEntityReplacementText("lceil", "\u2308"); + parser.defineEntityReplacementText("rceil", "\u2309"); + parser.defineEntityReplacementText("lfloor", "\u230a"); + parser.defineEntityReplacementText("rfloor", "\u230b"); + parser.defineEntityReplacementText("lang", "\u2329"); + parser.defineEntityReplacementText("rang", "\u232a"); + parser.defineEntityReplacementText("loz", "\u25ca"); + parser.defineEntityReplacementText("spades", "\u2660"); + parser.defineEntityReplacementText("clubs", "\u2663"); + parser.defineEntityReplacementText("hearts", "\u2665"); + parser.defineEntityReplacementText("diams", "\u2666"); + } + } // -- void initParser( XmlPullParser ) /** * Method nextTag. - * + * * @param parser * @throws IOException * @throws XmlPullParserException * @return int */ - private int nextTag( XmlPullParser parser ) - throws IOException, XmlPullParserException - { + private int nextTag(XmlPullParser parser) throws IOException, XmlPullParserException { int eventType = parser.next(); - if ( eventType == XmlPullParser.TEXT ) - { + if (eventType == XmlPullParser.TEXT) { eventType = parser.next(); } - if ( eventType != XmlPullParser.START_TAG && eventType != XmlPullParser.END_TAG ) - { - throw new XmlPullParserException( "expected START_TAG or END_TAG not " + XmlPullParser.TYPES[eventType], parser, null ); + if (eventType != XmlPullParser.START_TAG && eventType != XmlPullParser.END_TAG) { + throw new XmlPullParserException( + "expected START_TAG or END_TAG not " + XmlPullParser.TYPES[eventType], parser, null); } return eventType; - } //-- int nextTag( XmlPullParser ) + } // -- int nextTag( XmlPullParser ) /** * Method parseActivation. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Activation */ - private Activation parseActivation( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Activation parseActivation(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Activation activation = new Activation(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "activeByDefault".equals( name ) ) - { - activation.setActiveByDefault( getBooleanValue( getTrimmedValue( value ), "activeByDefault", parser, "false" ) ); - } - else if ( "jdk".equals( name ) ) - { - activation.setJdk( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("activeByDefault".equals(name)) { + activation.setActiveByDefault( + getBooleanValue(getTrimmedValue(value), "activeByDefault", parser, "false")); + } else if ("jdk".equals(name)) { + activation.setJdk(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "os", null, parsed ) ) - { - activation.setOs( parseActivationOS( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "property", null, parsed ) ) - { - activation.setProperty( parseActivationProperty( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "file", null, parsed ) ) - { - activation.setFile( parseActivationFile( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "os", null, parsed)) { + activation.setOs(parseActivationOS(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "property", null, parsed)) { + activation.setProperty(parseActivationProperty(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "file", null, parsed)) { + activation.setFile(parseActivationFile(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return activation; - } //-- Activation parseActivation( XmlPullParser, boolean ) + } // -- Activation parseActivation( XmlPullParser, boolean ) /** * Method parseActivationFile. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ActivationFile */ - private ActivationFile parseActivationFile( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ActivationFile parseActivationFile(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); ActivationFile activationFile = new ActivationFile(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "missing".equals( name ) ) - { - activationFile.setMissing( getTrimmedValue( value ) ); - } - else if ( "exists".equals( name ) ) - { - activationFile.setExists( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("missing".equals(name)) { + activationFile.setMissing(getTrimmedValue(value)); + } else if ("exists".equals(name)) { + activationFile.setExists(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return activationFile; - } //-- ActivationFile parseActivationFile( XmlPullParser, boolean ) + } // -- ActivationFile parseActivationFile( XmlPullParser, boolean ) /** * Method parseActivationOS. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ActivationOS */ - private ActivationOS parseActivationOS( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ActivationOS parseActivationOS(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); ActivationOS activationOS = new ActivationOS(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - activationOS.setName( getTrimmedValue( value ) ); - } - else if ( "family".equals( name ) ) - { - activationOS.setFamily( getTrimmedValue( value ) ); - } - else if ( "arch".equals( name ) ) - { - activationOS.setArch( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - activationOS.setVersion( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + activationOS.setName(getTrimmedValue(value)); + } else if ("family".equals(name)) { + activationOS.setFamily(getTrimmedValue(value)); + } else if ("arch".equals(name)) { + activationOS.setArch(getTrimmedValue(value)); + } else if ("version".equals(name)) { + activationOS.setVersion(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return activationOS; - } //-- ActivationOS parseActivationOS( XmlPullParser, boolean ) + } // -- ActivationOS parseActivationOS( XmlPullParser, boolean ) /** * Method parseActivationProperty. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ActivationProperty */ - private ActivationProperty parseActivationProperty( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ActivationProperty parseActivationProperty(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); ActivationProperty activationProperty = new ActivationProperty(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - activationProperty.setName( getTrimmedValue( value ) ); - } - else if ( "value".equals( name ) ) - { - activationProperty.setValue( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + activationProperty.setName(getTrimmedValue(value)); + } else if ("value".equals(name)) { + activationProperty.setValue(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return activationProperty; - } //-- ActivationProperty parseActivationProperty( XmlPullParser, boolean ) + } // -- ActivationProperty parseActivationProperty( XmlPullParser, boolean ) /** * Method parseBuild. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Build */ - private Build parseBuild( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Build parseBuild(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Build build = new Build(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "sourceDirectory".equals( name ) ) - { - build.setSourceDirectory( getTrimmedValue( value ) ); - } - else if ( "scriptSourceDirectory".equals( name ) ) - { - build.setScriptSourceDirectory( getTrimmedValue( value ) ); - } - else if ( "testSourceDirectory".equals( name ) ) - { - build.setTestSourceDirectory( getTrimmedValue( value ) ); - } - else if ( "outputDirectory".equals( name ) ) - { - build.setOutputDirectory( getTrimmedValue( value ) ); - } - else if ( "testOutputDirectory".equals( name ) ) - { - build.setTestOutputDirectory( getTrimmedValue( value ) ); - } - else if ( "defaultGoal".equals( name ) ) - { - build.setDefaultGoal( getTrimmedValue( value ) ); - } - else if ( "directory".equals( name ) ) - { - build.setDirectory( getTrimmedValue( value ) ); - } - else if ( "finalName".equals( name ) ) - { - build.setFinalName( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("sourceDirectory".equals(name)) { + build.setSourceDirectory(getTrimmedValue(value)); + } else if ("scriptSourceDirectory".equals(name)) { + build.setScriptSourceDirectory(getTrimmedValue(value)); + } else if ("testSourceDirectory".equals(name)) { + build.setTestSourceDirectory(getTrimmedValue(value)); + } else if ("outputDirectory".equals(name)) { + build.setOutputDirectory(getTrimmedValue(value)); + } else if ("testOutputDirectory".equals(name)) { + build.setTestOutputDirectory(getTrimmedValue(value)); + } else if ("defaultGoal".equals(name)) { + build.setDefaultGoal(getTrimmedValue(value)); + } else if ("directory".equals(name)) { + build.setDirectory(getTrimmedValue(value)); + } else if ("finalName".equals(name)) { + build.setFinalName(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "extensions", null, parsed ) ) - { - java.util.List extensions = new java.util.ArrayList/**/(); - build.setExtensions( extensions ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "extension".equals( parser.getName() ) ) - { - extensions.add( parseExtension( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "resources", null, parsed ) ) - { - java.util.List resources = new java.util.ArrayList/**/(); - build.setResources( resources ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "resource".equals( parser.getName() ) ) - { - resources.add( parseResource( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "testResources", null, parsed ) ) - { - java.util.List testResources = new java.util.ArrayList/**/(); - build.setTestResources( testResources ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "testResource".equals( parser.getName() ) ) - { - testResources.add( parseResource( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "filters", null, parsed ) ) - { - java.util.List filters = new java.util.ArrayList/**/(); - build.setFilters( filters ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "filter".equals( parser.getName() ) ) - { - filters.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "pluginManagement", null, parsed ) ) - { - build.setPluginManagement( parsePluginManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - build.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parsePlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "extensions", null, parsed)) { + java.util.List extensions = new java.util.ArrayList /**/(); + build.setExtensions(extensions); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("extension".equals(parser.getName())) { + extensions.add(parseExtension(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "resources", null, parsed)) { + java.util.List resources = new java.util.ArrayList /**/(); + build.setResources(resources); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("resource".equals(parser.getName())) { + resources.add(parseResource(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "testResources", null, parsed)) { + java.util.List testResources = new java.util.ArrayList /**/(); + build.setTestResources(testResources); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("testResource".equals(parser.getName())) { + testResources.add(parseResource(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "filters", null, parsed)) { + java.util.List filters = new java.util.ArrayList /**/(); + build.setFilters(filters); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("filter".equals(parser.getName())) { + filters.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "pluginManagement", null, parsed)) { + build.setPluginManagement(parsePluginManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + build.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parsePlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else { + checkUnknownElement(parser, strict); } } return build; - } //-- Build parseBuild( XmlPullParser, boolean ) + } // -- Build parseBuild( XmlPullParser, boolean ) /** * Method parseBuildBase. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return BuildBase */ - private BuildBase parseBuildBase( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private BuildBase parseBuildBase(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); BuildBase buildBase = new BuildBase(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "defaultGoal".equals( name ) ) - { - buildBase.setDefaultGoal( getTrimmedValue( value ) ); - } - else if ( "directory".equals( name ) ) - { - buildBase.setDirectory( getTrimmedValue( value ) ); - } - else if ( "finalName".equals( name ) ) - { - buildBase.setFinalName( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("defaultGoal".equals(name)) { + buildBase.setDefaultGoal(getTrimmedValue(value)); + } else if ("directory".equals(name)) { + buildBase.setDirectory(getTrimmedValue(value)); + } else if ("finalName".equals(name)) { + buildBase.setFinalName(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "resources", null, parsed ) ) - { - java.util.List resources = new java.util.ArrayList/**/(); - buildBase.setResources( resources ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "resource".equals( parser.getName() ) ) - { - resources.add( parseResource( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "testResources", null, parsed ) ) - { - java.util.List testResources = new java.util.ArrayList/**/(); - buildBase.setTestResources( testResources ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "testResource".equals( parser.getName() ) ) - { - testResources.add( parseResource( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "filters", null, parsed ) ) - { - java.util.List filters = new java.util.ArrayList/**/(); - buildBase.setFilters( filters ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "filter".equals( parser.getName() ) ) - { - filters.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "pluginManagement", null, parsed ) ) - { - buildBase.setPluginManagement( parsePluginManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - buildBase.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parsePlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "resources", null, parsed)) { + java.util.List resources = new java.util.ArrayList /**/(); + buildBase.setResources(resources); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("resource".equals(parser.getName())) { + resources.add(parseResource(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "testResources", null, parsed)) { + java.util.List testResources = new java.util.ArrayList /**/(); + buildBase.setTestResources(testResources); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("testResource".equals(parser.getName())) { + testResources.add(parseResource(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "filters", null, parsed)) { + java.util.List filters = new java.util.ArrayList /**/(); + buildBase.setFilters(filters); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("filter".equals(parser.getName())) { + filters.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "pluginManagement", null, parsed)) { + buildBase.setPluginManagement(parsePluginManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + buildBase.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parsePlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else { + checkUnknownElement(parser, strict); } } return buildBase; - } //-- BuildBase parseBuildBase( XmlPullParser, boolean ) + } // -- BuildBase parseBuildBase( XmlPullParser, boolean ) /** * Method parseCiManagement. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return CiManagement */ - private CiManagement parseCiManagement( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private CiManagement parseCiManagement(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); CiManagement ciManagement = new CiManagement(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "system".equals( name ) ) - { - ciManagement.setSystem( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - ciManagement.setUrl( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("system".equals(name)) { + ciManagement.setSystem(getTrimmedValue(value)); + } else if ("url".equals(name)) { + ciManagement.setUrl(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "notifiers", null, parsed ) ) - { - java.util.List notifiers = new java.util.ArrayList/**/(); - ciManagement.setNotifiers( notifiers ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "notifier".equals( parser.getName() ) ) - { - notifiers.add( parseNotifier( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "notifiers", null, parsed)) { + java.util.List notifiers = new java.util.ArrayList /**/(); + ciManagement.setNotifiers(notifiers); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("notifier".equals(parser.getName())) { + notifiers.add(parseNotifier(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return ciManagement; - } //-- CiManagement parseCiManagement( XmlPullParser, boolean ) + } // -- CiManagement parseCiManagement( XmlPullParser, boolean ) /** * Method parseConfigurationContainer. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ConfigurationContainer */ - private ConfigurationContainer parseConfigurationContainer( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ConfigurationContainer parseConfigurationContainer(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); ConfigurationContainer configurationContainer = new ConfigurationContainer(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "inherited".equals( name ) ) - { - configurationContainer.setInherited( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("inherited".equals(name)) { + configurationContainer.setInherited(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - configurationContainer.setConfiguration( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + configurationContainer.setConfiguration(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else { + checkUnknownElement(parser, strict); } } return configurationContainer; - } //-- ConfigurationContainer parseConfigurationContainer( XmlPullParser, boolean ) + } // -- ConfigurationContainer parseConfigurationContainer( XmlPullParser, boolean ) /** * Method parseContributor. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Contributor */ - private Contributor parseContributor( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Contributor parseContributor(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Contributor contributor = new Contributor(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - contributor.setName( getTrimmedValue( value ) ); - } - else if ( "email".equals( name ) ) - { - contributor.setEmail( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - contributor.setUrl( getTrimmedValue( value ) ); - } - else if ( "organization".equals( name ) ) - { - contributor.setOrganization( getTrimmedValue( value ) ); - } - else if ( "organizationUrl".equals( name ) ) - { - contributor.setOrganizationUrl( getTrimmedValue( value ) ); - } - else if ( "timezone".equals( name ) ) - { - contributor.setTimezone( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + contributor.setName(getTrimmedValue(value)); + } else if ("email".equals(name)) { + contributor.setEmail(getTrimmedValue(value)); + } else if ("url".equals(name)) { + contributor.setUrl(getTrimmedValue(value)); + } else if ("organization".equals(name)) { + contributor.setOrganization(getTrimmedValue(value)); + } else if ("organizationUrl".equals(name)) { + contributor.setOrganizationUrl(getTrimmedValue(value)); + } else if ("timezone".equals(name)) { + contributor.setTimezone(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "roles", null, parsed ) ) - { - java.util.List roles = new java.util.ArrayList/**/(); - contributor.setRoles( roles ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "role".equals( parser.getName() ) ) - { - roles.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "properties", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "roles", null, parsed)) { + java.util.List roles = new java.util.ArrayList /**/(); + contributor.setRoles(roles); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("role".equals(parser.getName())) { + roles.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "properties", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - contributor.addProperty( key, value ); + contributor.addProperty(key, value); } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return contributor; - } //-- Contributor parseContributor( XmlPullParser, boolean ) + } // -- Contributor parseContributor( XmlPullParser, boolean ) /** * Method parseDependency. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Dependency */ - private Dependency parseDependency( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Dependency parseDependency(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Dependency dependency = new Dependency(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - dependency.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - dependency.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - dependency.setVersion( getTrimmedValue( value ) ); - } - else if ( "type".equals( name ) ) - { - dependency.setType( getTrimmedValue( value ) ); - } - else if ( "classifier".equals( name ) ) - { - dependency.setClassifier( getTrimmedValue( value ) ); - } - else if ( "scope".equals( name ) ) - { - dependency.setScope( getTrimmedValue( value ) ); - } - else if ( "systemPath".equals( name ) ) - { - dependency.setSystemPath( getTrimmedValue( value ) ); - } - else if ( "optional".equals( name ) ) - { - dependency.setOptional( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + dependency.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + dependency.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + dependency.setVersion(getTrimmedValue(value)); + } else if ("type".equals(name)) { + dependency.setType(getTrimmedValue(value)); + } else if ("classifier".equals(name)) { + dependency.setClassifier(getTrimmedValue(value)); + } else if ("scope".equals(name)) { + dependency.setScope(getTrimmedValue(value)); + } else if ("systemPath".equals(name)) { + dependency.setSystemPath(getTrimmedValue(value)); + } else if ("optional".equals(name)) { + dependency.setOptional(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "exclusions", null, parsed ) ) - { - java.util.List exclusions = new java.util.ArrayList/**/(); - dependency.setExclusions( exclusions ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "exclusion".equals( parser.getName() ) ) - { - exclusions.add( parseExclusion( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "exclusions", null, parsed)) { + java.util.List exclusions = new java.util.ArrayList /**/(); + dependency.setExclusions(exclusions); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("exclusion".equals(parser.getName())) { + exclusions.add(parseExclusion(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return dependency; - } //-- Dependency parseDependency( XmlPullParser, boolean ) + } // -- Dependency parseDependency( XmlPullParser, boolean ) /** * Method parseDependencyManagement. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return DependencyManagement */ - private DependencyManagement parseDependencyManagement( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private DependencyManagement parseDependencyManagement(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); DependencyManagement dependencyManagement = new DependencyManagement(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "dependencies", null, parsed ) ) - { - java.util.List dependencies = new java.util.ArrayList/**/(); - dependencyManagement.setDependencies( dependencies ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "dependency".equals( parser.getName() ) ) - { - dependencies.add( parseDependency( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "dependencies", null, parsed)) { + java.util.List dependencies = new java.util.ArrayList /**/(); + dependencyManagement.setDependencies(dependencies); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("dependency".equals(parser.getName())) { + dependencies.add(parseDependency(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return dependencyManagement; - } //-- DependencyManagement parseDependencyManagement( XmlPullParser, boolean ) + } // -- DependencyManagement parseDependencyManagement( XmlPullParser, boolean ) /** * Method parseDeploymentRepository. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return DeploymentRepository */ - private DeploymentRepository parseDeploymentRepository( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private DeploymentRepository parseDeploymentRepository(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); DeploymentRepository deploymentRepository = new DeploymentRepository(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "uniqueVersion".equals( name ) ) - { - deploymentRepository.setUniqueVersion( getBooleanValue( getTrimmedValue( value ), "uniqueVersion", parser, "true" ) ); - } - else if ( "id".equals( name ) ) - { - deploymentRepository.setId( getTrimmedValue( value ) ); - } - else if ( "name".equals( name ) ) - { - deploymentRepository.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - deploymentRepository.setUrl( getTrimmedValue( value ) ); - } - else if ( "layout".equals( name ) ) - { - deploymentRepository.setLayout( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("uniqueVersion".equals(name)) { + deploymentRepository.setUniqueVersion( + getBooleanValue(getTrimmedValue(value), "uniqueVersion", parser, "true")); + } else if ("id".equals(name)) { + deploymentRepository.setId(getTrimmedValue(value)); + } else if ("name".equals(name)) { + deploymentRepository.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + deploymentRepository.setUrl(getTrimmedValue(value)); + } else if ("layout".equals(name)) { + deploymentRepository.setLayout(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "releases", null, parsed ) ) - { - deploymentRepository.setReleases( parseRepositoryPolicy( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "snapshots", null, parsed ) ) - { - deploymentRepository.setSnapshots( parseRepositoryPolicy( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "releases", null, parsed)) { + deploymentRepository.setReleases(parseRepositoryPolicy(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "snapshots", null, parsed)) { + deploymentRepository.setSnapshots(parseRepositoryPolicy(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return deploymentRepository; - } //-- DeploymentRepository parseDeploymentRepository( XmlPullParser, boolean ) + } // -- DeploymentRepository parseDeploymentRepository( XmlPullParser, boolean ) /** * Method parseDeveloper. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Developer */ - private Developer parseDeveloper( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Developer parseDeveloper(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Developer developer = new Developer(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - developer.setId( getTrimmedValue( value ) ); - } - else if ( "name".equals( name ) ) - { - developer.setName( getTrimmedValue( value ) ); - } - else if ( "email".equals( name ) ) - { - developer.setEmail( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - developer.setUrl( getTrimmedValue( value ) ); - } - else if ( "organization".equals( name ) ) - { - developer.setOrganization( getTrimmedValue( value ) ); - } - else if ( "organizationUrl".equals( name ) ) - { - developer.setOrganizationUrl( getTrimmedValue( value ) ); - } - else if ( "timezone".equals( name ) ) - { - developer.setTimezone( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + developer.setId(getTrimmedValue(value)); + } else if ("name".equals(name)) { + developer.setName(getTrimmedValue(value)); + } else if ("email".equals(name)) { + developer.setEmail(getTrimmedValue(value)); + } else if ("url".equals(name)) { + developer.setUrl(getTrimmedValue(value)); + } else if ("organization".equals(name)) { + developer.setOrganization(getTrimmedValue(value)); + } else if ("organizationUrl".equals(name)) { + developer.setOrganizationUrl(getTrimmedValue(value)); + } else if ("timezone".equals(name)) { + developer.setTimezone(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "roles", null, parsed ) ) - { - java.util.List roles = new java.util.ArrayList/**/(); - developer.setRoles( roles ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "role".equals( parser.getName() ) ) - { - roles.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "properties", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "roles", null, parsed)) { + java.util.List roles = new java.util.ArrayList /**/(); + developer.setRoles(roles); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("role".equals(parser.getName())) { + roles.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "properties", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - developer.addProperty( key, value ); + developer.addProperty(key, value); } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return developer; - } //-- Developer parseDeveloper( XmlPullParser, boolean ) + } // -- Developer parseDeveloper( XmlPullParser, boolean ) /** * Method parseDistributionManagement. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return DistributionManagement */ - private DistributionManagement parseDistributionManagement( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private DistributionManagement parseDistributionManagement(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); DistributionManagement distributionManagement = new DistributionManagement(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "downloadUrl".equals( name ) ) - { - distributionManagement.setDownloadUrl( getTrimmedValue( value ) ); - } - else if ( "status".equals( name ) ) - { - distributionManagement.setStatus( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("downloadUrl".equals(name)) { + distributionManagement.setDownloadUrl(getTrimmedValue(value)); + } else if ("status".equals(name)) { + distributionManagement.setStatus(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "repository", null, parsed ) ) - { - distributionManagement.setRepository( parseDeploymentRepository( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "snapshotRepository", null, parsed ) ) - { - distributionManagement.setSnapshotRepository( parseDeploymentRepository( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "site", null, parsed ) ) - { - distributionManagement.setSite( parseSite( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "relocation", null, parsed ) ) - { - distributionManagement.setRelocation( parseRelocation( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "repository", null, parsed)) { + distributionManagement.setRepository(parseDeploymentRepository(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "snapshotRepository", null, parsed)) { + distributionManagement.setSnapshotRepository(parseDeploymentRepository(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "site", null, parsed)) { + distributionManagement.setSite(parseSite(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "relocation", null, parsed)) { + distributionManagement.setRelocation(parseRelocation(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return distributionManagement; - } //-- DistributionManagement parseDistributionManagement( XmlPullParser, boolean ) + } // -- DistributionManagement parseDistributionManagement( XmlPullParser, boolean ) /** * Method parseExclusion. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Exclusion */ - private Exclusion parseExclusion( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Exclusion parseExclusion(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Exclusion exclusion = new Exclusion(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "artifactId".equals( name ) ) - { - exclusion.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "groupId".equals( name ) ) - { - exclusion.setGroupId( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("artifactId".equals(name)) { + exclusion.setArtifactId(getTrimmedValue(value)); + } else if ("groupId".equals(name)) { + exclusion.setGroupId(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return exclusion; - } //-- Exclusion parseExclusion( XmlPullParser, boolean ) + } // -- Exclusion parseExclusion( XmlPullParser, boolean ) /** * Method parseExtension. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Extension */ - private Extension parseExtension( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Extension parseExtension(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Extension extension = new Extension(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - extension.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - extension.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - extension.setVersion( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + extension.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + extension.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + extension.setVersion(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return extension; - } //-- Extension parseExtension( XmlPullParser, boolean ) + } // -- Extension parseExtension( XmlPullParser, boolean ) /** * Method parseFileSet. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return FileSet */ - private FileSet parseFileSet( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private FileSet parseFileSet(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); FileSet fileSet = new FileSet(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "directory".equals( name ) ) - { - fileSet.setDirectory( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("directory".equals(name)) { + fileSet.setDirectory(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "includes", null, parsed ) ) - { - java.util.List includes = new java.util.ArrayList/**/(); - fileSet.setIncludes( includes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "include".equals( parser.getName() ) ) - { - includes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "includes", null, parsed)) { + java.util.List includes = new java.util.ArrayList /**/(); + fileSet.setIncludes(includes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("include".equals(parser.getName())) { + includes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "excludes", null, parsed ) ) - { - java.util.List excludes = new java.util.ArrayList/**/(); - fileSet.setExcludes( excludes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "exclude".equals( parser.getName() ) ) - { - excludes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "excludes", null, parsed)) { + java.util.List excludes = new java.util.ArrayList /**/(); + fileSet.setExcludes(excludes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("exclude".equals(parser.getName())) { + excludes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return fileSet; - } //-- FileSet parseFileSet( XmlPullParser, boolean ) + } // -- FileSet parseFileSet( XmlPullParser, boolean ) /** * Method parseIssueManagement. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return IssueManagement */ - private IssueManagement parseIssueManagement( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private IssueManagement parseIssueManagement(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); IssueManagement issueManagement = new IssueManagement(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "system".equals( name ) ) - { - issueManagement.setSystem( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - issueManagement.setUrl( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("system".equals(name)) { + issueManagement.setSystem(getTrimmedValue(value)); + } else if ("url".equals(name)) { + issueManagement.setUrl(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return issueManagement; - } //-- IssueManagement parseIssueManagement( XmlPullParser, boolean ) + } // -- IssueManagement parseIssueManagement( XmlPullParser, boolean ) /** * Method parseLicense. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return License */ - private License parseLicense( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private License parseLicense(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); License license = new License(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - license.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - license.setUrl( getTrimmedValue( value ) ); - } - else if ( "distribution".equals( name ) ) - { - license.setDistribution( getTrimmedValue( value ) ); - } - else if ( "comments".equals( name ) ) - { - license.setComments( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + license.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + license.setUrl(getTrimmedValue(value)); + } else if ("distribution".equals(name)) { + license.setDistribution(getTrimmedValue(value)); + } else if ("comments".equals(name)) { + license.setComments(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return license; - } //-- License parseLicense( XmlPullParser, boolean ) + } // -- License parseLicense( XmlPullParser, boolean ) /** * Method parseMailingList. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return MailingList */ - private MailingList parseMailingList( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private MailingList parseMailingList(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); MailingList mailingList = new MailingList(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - mailingList.setName( getTrimmedValue( value ) ); - } - else if ( "subscribe".equals( name ) ) - { - mailingList.setSubscribe( getTrimmedValue( value ) ); - } - else if ( "unsubscribe".equals( name ) ) - { - mailingList.setUnsubscribe( getTrimmedValue( value ) ); - } - else if ( "post".equals( name ) ) - { - mailingList.setPost( getTrimmedValue( value ) ); - } - else if ( "archive".equals( name ) ) - { - mailingList.setArchive( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + mailingList.setName(getTrimmedValue(value)); + } else if ("subscribe".equals(name)) { + mailingList.setSubscribe(getTrimmedValue(value)); + } else if ("unsubscribe".equals(name)) { + mailingList.setUnsubscribe(getTrimmedValue(value)); + } else if ("post".equals(name)) { + mailingList.setPost(getTrimmedValue(value)); + } else if ("archive".equals(name)) { + mailingList.setArchive(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "otherArchives", null, parsed ) ) - { - java.util.List otherArchives = new java.util.ArrayList/**/(); - mailingList.setOtherArchives( otherArchives ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "otherArchive".equals( parser.getName() ) ) - { - otherArchives.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "otherArchives", null, parsed)) { + java.util.List otherArchives = new java.util.ArrayList /**/(); + mailingList.setOtherArchives(otherArchives); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("otherArchive".equals(parser.getName())) { + otherArchives.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return mailingList; - } //-- MailingList parseMailingList( XmlPullParser, boolean ) + } // -- MailingList parseMailingList( XmlPullParser, boolean ) /** * Method parseModel. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Model */ - private Model parseModel( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Model parseModel(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Model model = new Model(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "xmlns".equals( name ) ) - { + } else if ("xmlns".equals(name)) { // ignore xmlns attribute in root class, which is a reserved attribute name - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "modelVersion", null, parsed ) ) - { - model.setModelVersion( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "parent", null, parsed ) ) - { - model.setParent( parseParent( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "groupId", null, parsed ) ) - { - model.setGroupId( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "artifactId", null, parsed ) ) - { - model.setArtifactId( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "version", null, parsed ) ) - { - model.setVersion( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "packaging", null, parsed ) ) - { - model.setPackaging( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "name", null, parsed ) ) - { - model.setName( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "description", null, parsed ) ) - { - model.setDescription( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "url", null, parsed ) ) - { - model.setUrl( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "inceptionYear", null, parsed ) ) - { - model.setInceptionYear( getTrimmedValue( parser.nextText() ) ); - } - else if ( checkFieldWithDuplicate( parser, "organization", "organisation", parsed ) ) - { - model.setOrganization( parseOrganization( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "licenses", null, parsed ) ) - { - java.util.List licenses = new java.util.ArrayList/**/(); - model.setLicenses( licenses ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "license".equals( parser.getName() ) ) - { - licenses.add( parseLicense( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "developers", null, parsed ) ) - { - java.util.List developers = new java.util.ArrayList/**/(); - model.setDevelopers( developers ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "developer".equals( parser.getName() ) ) - { - developers.add( parseDeveloper( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "contributors", null, parsed ) ) - { - java.util.List contributors = new java.util.ArrayList/**/(); - model.setContributors( contributors ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "contributor".equals( parser.getName() ) ) - { - contributors.add( parseContributor( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "mailingLists", null, parsed ) ) - { - java.util.List mailingLists = new java.util.ArrayList/**/(); - model.setMailingLists( mailingLists ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "mailingList".equals( parser.getName() ) ) - { - mailingLists.add( parseMailingList( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "prerequisites", null, parsed ) ) - { - model.setPrerequisites( parsePrerequisites( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "modules", null, parsed ) ) - { - java.util.List modules = new java.util.ArrayList/**/(); - model.setModules( modules ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "module".equals( parser.getName() ) ) - { - modules.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "scm", null, parsed ) ) - { - model.setScm( parseScm( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "issueManagement", null, parsed ) ) - { - model.setIssueManagement( parseIssueManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "ciManagement", null, parsed ) ) - { - model.setCiManagement( parseCiManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "distributionManagement", null, parsed ) ) - { - model.setDistributionManagement( parseDistributionManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "properties", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "modelVersion", null, parsed)) { + model.setModelVersion(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "parent", null, parsed)) { + model.setParent(parseParent(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "groupId", null, parsed)) { + model.setGroupId(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "artifactId", null, parsed)) { + model.setArtifactId(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "version", null, parsed)) { + model.setVersion(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "packaging", null, parsed)) { + model.setPackaging(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "name", null, parsed)) { + model.setName(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "description", null, parsed)) { + model.setDescription(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "url", null, parsed)) { + model.setUrl(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "inceptionYear", null, parsed)) { + model.setInceptionYear(getTrimmedValue(parser.nextText())); + } else if (checkFieldWithDuplicate(parser, "organization", "organisation", parsed)) { + model.setOrganization(parseOrganization(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "licenses", null, parsed)) { + java.util.List licenses = new java.util.ArrayList /**/(); + model.setLicenses(licenses); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("license".equals(parser.getName())) { + licenses.add(parseLicense(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "developers", null, parsed)) { + java.util.List developers = new java.util.ArrayList /**/(); + model.setDevelopers(developers); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("developer".equals(parser.getName())) { + developers.add(parseDeveloper(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "contributors", null, parsed)) { + java.util.List contributors = new java.util.ArrayList /**/(); + model.setContributors(contributors); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("contributor".equals(parser.getName())) { + contributors.add(parseContributor(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "mailingLists", null, parsed)) { + java.util.List mailingLists = new java.util.ArrayList /**/(); + model.setMailingLists(mailingLists); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("mailingList".equals(parser.getName())) { + mailingLists.add(parseMailingList(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "prerequisites", null, parsed)) { + model.setPrerequisites(parsePrerequisites(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "modules", null, parsed)) { + java.util.List modules = new java.util.ArrayList /**/(); + model.setModules(modules); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("module".equals(parser.getName())) { + modules.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "scm", null, parsed)) { + model.setScm(parseScm(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "issueManagement", null, parsed)) { + model.setIssueManagement(parseIssueManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "ciManagement", null, parsed)) { + model.setCiManagement(parseCiManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "distributionManagement", null, parsed)) { + model.setDistributionManagement(parseDistributionManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "properties", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - model.addProperty( key, value ); - } - } - else if ( checkFieldWithDuplicate( parser, "dependencyManagement", null, parsed ) ) - { - model.setDependencyManagement( parseDependencyManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "dependencies", null, parsed ) ) - { - java.util.List dependencies = new java.util.ArrayList/**/(); - model.setDependencies( dependencies ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "dependency".equals( parser.getName() ) ) - { - dependencies.add( parseDependency( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "repositories", null, parsed ) ) - { - java.util.List repositories = new java.util.ArrayList/**/(); - model.setRepositories( repositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "repository".equals( parser.getName() ) ) - { - repositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "pluginRepositories", null, parsed ) ) - { - java.util.List pluginRepositories = new java.util.ArrayList/**/(); - model.setPluginRepositories( pluginRepositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "pluginRepository".equals( parser.getName() ) ) - { - pluginRepositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "build", null, parsed ) ) - { - model.setBuild( parseBuild( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "reports", null, parsed ) ) - { - model.setReports( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else if ( checkFieldWithDuplicate( parser, "reporting", null, parsed ) ) - { - model.setReporting( parseReporting( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "profiles", null, parsed ) ) - { - java.util.List profiles = new java.util.ArrayList/**/(); - model.setProfiles( profiles ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "profile".equals( parser.getName() ) ) - { - profiles.add( parseProfile( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else - { - checkUnknownElement( parser, strict ); + model.addProperty(key, value); + } + } else if (checkFieldWithDuplicate(parser, "dependencyManagement", null, parsed)) { + model.setDependencyManagement(parseDependencyManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "dependencies", null, parsed)) { + java.util.List dependencies = new java.util.ArrayList /**/(); + model.setDependencies(dependencies); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("dependency".equals(parser.getName())) { + dependencies.add(parseDependency(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "repositories", null, parsed)) { + java.util.List repositories = new java.util.ArrayList /**/(); + model.setRepositories(repositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("repository".equals(parser.getName())) { + repositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "pluginRepositories", null, parsed)) { + java.util.List pluginRepositories = new java.util.ArrayList /**/(); + model.setPluginRepositories(pluginRepositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("pluginRepository".equals(parser.getName())) { + pluginRepositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "build", null, parsed)) { + model.setBuild(parseBuild(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "reports", null, parsed)) { + model.setReports(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else if (checkFieldWithDuplicate(parser, "reporting", null, parsed)) { + model.setReporting(parseReporting(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "profiles", null, parsed)) { + java.util.List profiles = new java.util.ArrayList /**/(); + model.setProfiles(profiles); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("profile".equals(parser.getName())) { + profiles.add(parseProfile(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else { + checkUnknownElement(parser, strict); } } return model; - } //-- Model parseModel( XmlPullParser, boolean ) + } // -- Model parseModel( XmlPullParser, boolean ) /** * Method parseModelBase. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ModelBase */ - private ModelBase parseModelBase( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ModelBase parseModelBase(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); ModelBase modelBase = new ModelBase(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "modules", null, parsed ) ) - { - java.util.List modules = new java.util.ArrayList/**/(); - modelBase.setModules( modules ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "module".equals( parser.getName() ) ) - { - modules.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "distributionManagement", null, parsed ) ) - { - modelBase.setDistributionManagement( parseDistributionManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "properties", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "modules", null, parsed)) { + java.util.List modules = new java.util.ArrayList /**/(); + modelBase.setModules(modules); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("module".equals(parser.getName())) { + modules.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "distributionManagement", null, parsed)) { + modelBase.setDistributionManagement(parseDistributionManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "properties", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - modelBase.addProperty( key, value ); - } - } - else if ( checkFieldWithDuplicate( parser, "dependencyManagement", null, parsed ) ) - { - modelBase.setDependencyManagement( parseDependencyManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "dependencies", null, parsed ) ) - { - java.util.List dependencies = new java.util.ArrayList/**/(); - modelBase.setDependencies( dependencies ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "dependency".equals( parser.getName() ) ) - { - dependencies.add( parseDependency( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "repositories", null, parsed ) ) - { - java.util.List repositories = new java.util.ArrayList/**/(); - modelBase.setRepositories( repositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "repository".equals( parser.getName() ) ) - { - repositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "pluginRepositories", null, parsed ) ) - { - java.util.List pluginRepositories = new java.util.ArrayList/**/(); - modelBase.setPluginRepositories( pluginRepositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "pluginRepository".equals( parser.getName() ) ) - { - pluginRepositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "reports", null, parsed ) ) - { - modelBase.setReports( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else if ( checkFieldWithDuplicate( parser, "reporting", null, parsed ) ) - { - modelBase.setReporting( parseReporting( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + modelBase.addProperty(key, value); + } + } else if (checkFieldWithDuplicate(parser, "dependencyManagement", null, parsed)) { + modelBase.setDependencyManagement(parseDependencyManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "dependencies", null, parsed)) { + java.util.List dependencies = new java.util.ArrayList /**/(); + modelBase.setDependencies(dependencies); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("dependency".equals(parser.getName())) { + dependencies.add(parseDependency(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "repositories", null, parsed)) { + java.util.List repositories = new java.util.ArrayList /**/(); + modelBase.setRepositories(repositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("repository".equals(parser.getName())) { + repositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "pluginRepositories", null, parsed)) { + java.util.List pluginRepositories = new java.util.ArrayList /**/(); + modelBase.setPluginRepositories(pluginRepositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("pluginRepository".equals(parser.getName())) { + pluginRepositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "reports", null, parsed)) { + modelBase.setReports(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else if (checkFieldWithDuplicate(parser, "reporting", null, parsed)) { + modelBase.setReporting(parseReporting(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return modelBase; - } //-- ModelBase parseModelBase( XmlPullParser, boolean ) + } // -- ModelBase parseModelBase( XmlPullParser, boolean ) /** * Method parseNotifier. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Notifier */ - private Notifier parseNotifier( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Notifier parseNotifier(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Notifier notifier = new Notifier(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "type".equals( name ) ) - { - notifier.setType( getTrimmedValue( value ) ); - } - else if ( "sendOnError".equals( name ) ) - { - notifier.setSendOnError( getBooleanValue( getTrimmedValue( value ), "sendOnError", parser, "true" ) ); - } - else if ( "sendOnFailure".equals( name ) ) - { - notifier.setSendOnFailure( getBooleanValue( getTrimmedValue( value ), "sendOnFailure", parser, "true" ) ); - } - else if ( "sendOnSuccess".equals( name ) ) - { - notifier.setSendOnSuccess( getBooleanValue( getTrimmedValue( value ), "sendOnSuccess", parser, "true" ) ); - } - else if ( "sendOnWarning".equals( name ) ) - { - notifier.setSendOnWarning( getBooleanValue( getTrimmedValue( value ), "sendOnWarning", parser, "true" ) ); - } - else if ( "address".equals( name ) ) - { - notifier.setAddress( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("type".equals(name)) { + notifier.setType(getTrimmedValue(value)); + } else if ("sendOnError".equals(name)) { + notifier.setSendOnError(getBooleanValue(getTrimmedValue(value), "sendOnError", parser, "true")); + } else if ("sendOnFailure".equals(name)) { + notifier.setSendOnFailure(getBooleanValue(getTrimmedValue(value), "sendOnFailure", parser, "true")); + } else if ("sendOnSuccess".equals(name)) { + notifier.setSendOnSuccess(getBooleanValue(getTrimmedValue(value), "sendOnSuccess", parser, "true")); + } else if ("sendOnWarning".equals(name)) { + notifier.setSendOnWarning(getBooleanValue(getTrimmedValue(value), "sendOnWarning", parser, "true")); + } else if ("address".equals(name)) { + notifier.setAddress(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - notifier.addConfiguration( key, value ); + notifier.addConfiguration(key, value); } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return notifier; - } //-- Notifier parseNotifier( XmlPullParser, boolean ) + } // -- Notifier parseNotifier( XmlPullParser, boolean ) /** * Method parseOrganization. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Organization */ - private Organization parseOrganization( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Organization parseOrganization(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Organization organization = new Organization(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "name".equals( name ) ) - { - organization.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - organization.setUrl( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("name".equals(name)) { + organization.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + organization.setUrl(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return organization; - } //-- Organization parseOrganization( XmlPullParser, boolean ) + } // -- Organization parseOrganization( XmlPullParser, boolean ) /** * Method parseParent. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Parent */ - private Parent parseParent( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Parent parseParent(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Parent parent = new Parent(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - parent.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - parent.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - parent.setVersion( getTrimmedValue( value ) ); - } - else if ( "relativePath".equals( name ) ) - { - parent.setRelativePath( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + parent.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + parent.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + parent.setVersion(getTrimmedValue(value)); + } else if ("relativePath".equals(name)) { + parent.setRelativePath(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return parent; - } //-- Parent parseParent( XmlPullParser, boolean ) + } // -- Parent parseParent( XmlPullParser, boolean ) /** * Method parsePatternSet. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return PatternSet */ - private PatternSet parsePatternSet( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private PatternSet parsePatternSet(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); PatternSet patternSet = new PatternSet(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "includes", null, parsed ) ) - { - java.util.List includes = new java.util.ArrayList/**/(); - patternSet.setIncludes( includes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "include".equals( parser.getName() ) ) - { - includes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "includes", null, parsed)) { + java.util.List includes = new java.util.ArrayList /**/(); + patternSet.setIncludes(includes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("include".equals(parser.getName())) { + includes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "excludes", null, parsed ) ) - { - java.util.List excludes = new java.util.ArrayList/**/(); - patternSet.setExcludes( excludes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "exclude".equals( parser.getName() ) ) - { - excludes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "excludes", null, parsed)) { + java.util.List excludes = new java.util.ArrayList /**/(); + patternSet.setExcludes(excludes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("exclude".equals(parser.getName())) { + excludes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return patternSet; - } //-- PatternSet parsePatternSet( XmlPullParser, boolean ) + } // -- PatternSet parsePatternSet( XmlPullParser, boolean ) /** * Method parsePlugin. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Plugin */ - private Plugin parsePlugin( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Plugin parsePlugin(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Plugin plugin = new Plugin(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - plugin.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - plugin.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - plugin.setVersion( getTrimmedValue( value ) ); - } - else if ( "extensions".equals( name ) ) - { - plugin.setExtensions( getTrimmedValue( value ) ); - } - else if ( "inherited".equals( name ) ) - { - plugin.setInherited( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + plugin.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + plugin.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + plugin.setVersion(getTrimmedValue(value)); + } else if ("extensions".equals(name)) { + plugin.setExtensions(getTrimmedValue(value)); + } else if ("inherited".equals(name)) { + plugin.setInherited(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "executions", null, parsed ) ) - { - java.util.List executions = new java.util.ArrayList/**/(); - plugin.setExecutions( executions ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "execution".equals( parser.getName() ) ) - { - executions.add( parsePluginExecution( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "dependencies", null, parsed ) ) - { - java.util.List dependencies = new java.util.ArrayList/**/(); - plugin.setDependencies( dependencies ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "dependency".equals( parser.getName() ) ) - { - dependencies.add( parseDependency( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "goals", null, parsed ) ) - { - plugin.setGoals( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - plugin.setConfiguration( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "executions", null, parsed)) { + java.util.List executions = new java.util.ArrayList /**/(); + plugin.setExecutions(executions); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("execution".equals(parser.getName())) { + executions.add(parsePluginExecution(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "dependencies", null, parsed)) { + java.util.List dependencies = new java.util.ArrayList /**/(); + plugin.setDependencies(dependencies); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("dependency".equals(parser.getName())) { + dependencies.add(parseDependency(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "goals", null, parsed)) { + plugin.setGoals(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + plugin.setConfiguration(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else { + checkUnknownElement(parser, strict); } } return plugin; - } //-- Plugin parsePlugin( XmlPullParser, boolean ) + } // -- Plugin parsePlugin( XmlPullParser, boolean ) /** * Method parsePluginConfiguration. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return PluginConfiguration */ - private PluginConfiguration parsePluginConfiguration( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private PluginConfiguration parsePluginConfiguration(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); PluginConfiguration pluginConfiguration = new PluginConfiguration(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "pluginManagement", null, parsed ) ) - { - pluginConfiguration.setPluginManagement( parsePluginManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - pluginConfiguration.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parsePlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "pluginManagement", null, parsed)) { + pluginConfiguration.setPluginManagement(parsePluginManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + pluginConfiguration.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parsePlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return pluginConfiguration; - } //-- PluginConfiguration parsePluginConfiguration( XmlPullParser, boolean ) + } // -- PluginConfiguration parsePluginConfiguration( XmlPullParser, boolean ) /** * Method parsePluginContainer. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return PluginContainer */ - private PluginContainer parsePluginContainer( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private PluginContainer parsePluginContainer(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); PluginContainer pluginContainer = new PluginContainer(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - pluginContainer.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parsePlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + pluginContainer.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parsePlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return pluginContainer; - } //-- PluginContainer parsePluginContainer( XmlPullParser, boolean ) + } // -- PluginContainer parsePluginContainer( XmlPullParser, boolean ) /** * Method parsePluginExecution. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return PluginExecution */ - private PluginExecution parsePluginExecution( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private PluginExecution parsePluginExecution(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); PluginExecution pluginExecution = new PluginExecution(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - pluginExecution.setId( getTrimmedValue( value ) ); - } - else if ( "phase".equals( name ) ) - { - pluginExecution.setPhase( getTrimmedValue( value ) ); - } - else if ( "inherited".equals( name ) ) - { - pluginExecution.setInherited( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + pluginExecution.setId(getTrimmedValue(value)); + } else if ("phase".equals(name)) { + pluginExecution.setPhase(getTrimmedValue(value)); + } else if ("inherited".equals(name)) { + pluginExecution.setInherited(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "goals", null, parsed ) ) - { - java.util.List goals = new java.util.ArrayList/**/(); - pluginExecution.setGoals( goals ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "goal".equals( parser.getName() ) ) - { - goals.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "goals", null, parsed)) { + java.util.List goals = new java.util.ArrayList /**/(); + pluginExecution.setGoals(goals); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("goal".equals(parser.getName())) { + goals.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - pluginExecution.setConfiguration( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + pluginExecution.setConfiguration(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else { + checkUnknownElement(parser, strict); } } return pluginExecution; - } //-- PluginExecution parsePluginExecution( XmlPullParser, boolean ) + } // -- PluginExecution parsePluginExecution( XmlPullParser, boolean ) /** * Method parsePluginManagement. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return PluginManagement */ - private PluginManagement parsePluginManagement( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private PluginManagement parsePluginManagement(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); PluginManagement pluginManagement = new PluginManagement(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - pluginManagement.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parsePlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + pluginManagement.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parsePlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return pluginManagement; - } //-- PluginManagement parsePluginManagement( XmlPullParser, boolean ) + } // -- PluginManagement parsePluginManagement( XmlPullParser, boolean ) /** * Method parsePrerequisites. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Prerequisites */ - private Prerequisites parsePrerequisites( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Prerequisites parsePrerequisites(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Prerequisites prerequisites = new Prerequisites(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "maven".equals( name ) ) - { - prerequisites.setMaven( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("maven".equals(name)) { + prerequisites.setMaven(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return prerequisites; - } //-- Prerequisites parsePrerequisites( XmlPullParser, boolean ) + } // -- Prerequisites parsePrerequisites( XmlPullParser, boolean ) /** * Method parseProfile. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Profile */ - private Profile parseProfile( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Profile parseProfile(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Profile profile = new Profile(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - profile.setId( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + profile.setId(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "activation", null, parsed ) ) - { - profile.setActivation( parseActivation( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "build", null, parsed ) ) - { - profile.setBuild( parseBuildBase( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "modules", null, parsed ) ) - { - java.util.List modules = new java.util.ArrayList/**/(); - profile.setModules( modules ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "module".equals( parser.getName() ) ) - { - modules.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "distributionManagement", null, parsed ) ) - { - profile.setDistributionManagement( parseDistributionManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "properties", null, parsed ) ) - { - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "activation", null, parsed)) { + profile.setActivation(parseActivation(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "build", null, parsed)) { + profile.setBuild(parseBuildBase(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "modules", null, parsed)) { + java.util.List modules = new java.util.ArrayList /**/(); + profile.setModules(modules); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("module".equals(parser.getName())) { + modules.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "distributionManagement", null, parsed)) { + profile.setDistributionManagement(parseDistributionManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "properties", null, parsed)) { + while (parser.nextTag() == XmlPullParser.START_TAG) { String key = parser.getName(); String value = parser.nextText().trim(); - profile.addProperty( key, value ); - } - } - else if ( checkFieldWithDuplicate( parser, "dependencyManagement", null, parsed ) ) - { - profile.setDependencyManagement( parseDependencyManagement( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "dependencies", null, parsed ) ) - { - java.util.List dependencies = new java.util.ArrayList/**/(); - profile.setDependencies( dependencies ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "dependency".equals( parser.getName() ) ) - { - dependencies.add( parseDependency( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "repositories", null, parsed ) ) - { - java.util.List repositories = new java.util.ArrayList/**/(); - profile.setRepositories( repositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "repository".equals( parser.getName() ) ) - { - repositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "pluginRepositories", null, parsed ) ) - { - java.util.List pluginRepositories = new java.util.ArrayList/**/(); - profile.setPluginRepositories( pluginRepositories ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "pluginRepository".equals( parser.getName() ) ) - { - pluginRepositories.add( parseRepository( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); - } - } - } - else if ( checkFieldWithDuplicate( parser, "reports", null, parsed ) ) - { - profile.setReports( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else if ( checkFieldWithDuplicate( parser, "reporting", null, parsed ) ) - { - profile.setReporting( parseReporting( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + profile.addProperty(key, value); + } + } else if (checkFieldWithDuplicate(parser, "dependencyManagement", null, parsed)) { + profile.setDependencyManagement(parseDependencyManagement(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "dependencies", null, parsed)) { + java.util.List dependencies = new java.util.ArrayList /**/(); + profile.setDependencies(dependencies); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("dependency".equals(parser.getName())) { + dependencies.add(parseDependency(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "repositories", null, parsed)) { + java.util.List repositories = new java.util.ArrayList /**/(); + profile.setRepositories(repositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("repository".equals(parser.getName())) { + repositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "pluginRepositories", null, parsed)) { + java.util.List pluginRepositories = new java.util.ArrayList /**/(); + profile.setPluginRepositories(pluginRepositories); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("pluginRepository".equals(parser.getName())) { + pluginRepositories.add(parseRepository(parser, strict)); + } else { + checkUnknownElement(parser, strict); + } + } + } else if (checkFieldWithDuplicate(parser, "reports", null, parsed)) { + profile.setReports(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else if (checkFieldWithDuplicate(parser, "reporting", null, parsed)) { + profile.setReporting(parseReporting(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return profile; - } //-- Profile parseProfile( XmlPullParser, boolean ) + } // -- Profile parseProfile( XmlPullParser, boolean ) /** * Method parseRelocation. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Relocation */ - private Relocation parseRelocation( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Relocation parseRelocation(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Relocation relocation = new Relocation(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - relocation.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - relocation.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - relocation.setVersion( getTrimmedValue( value ) ); - } - else if ( "message".equals( name ) ) - { - relocation.setMessage( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + relocation.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + relocation.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + relocation.setVersion(getTrimmedValue(value)); + } else if ("message".equals(name)) { + relocation.setMessage(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return relocation; - } //-- Relocation parseRelocation( XmlPullParser, boolean ) + } // -- Relocation parseRelocation( XmlPullParser, boolean ) /** * Method parseReportPlugin. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ReportPlugin */ - private ReportPlugin parseReportPlugin( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ReportPlugin parseReportPlugin(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); ReportPlugin reportPlugin = new ReportPlugin(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "groupId".equals( name ) ) - { - reportPlugin.setGroupId( getTrimmedValue( value ) ); - } - else if ( "artifactId".equals( name ) ) - { - reportPlugin.setArtifactId( getTrimmedValue( value ) ); - } - else if ( "version".equals( name ) ) - { - reportPlugin.setVersion( getTrimmedValue( value ) ); - } - else if ( "inherited".equals( name ) ) - { - reportPlugin.setInherited( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("groupId".equals(name)) { + reportPlugin.setGroupId(getTrimmedValue(value)); + } else if ("artifactId".equals(name)) { + reportPlugin.setArtifactId(getTrimmedValue(value)); + } else if ("version".equals(name)) { + reportPlugin.setVersion(getTrimmedValue(value)); + } else if ("inherited".equals(name)) { + reportPlugin.setInherited(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "reportSets", null, parsed ) ) - { - java.util.List reportSets = new java.util.ArrayList/**/(); - reportPlugin.setReportSets( reportSets ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "reportSet".equals( parser.getName() ) ) - { - reportSets.add( parseReportSet( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "reportSets", null, parsed)) { + java.util.List reportSets = new java.util.ArrayList /**/(); + reportPlugin.setReportSets(reportSets); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("reportSet".equals(parser.getName())) { + reportSets.add(parseReportSet(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - reportPlugin.setConfiguration( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + reportPlugin.setConfiguration(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else { + checkUnknownElement(parser, strict); } } return reportPlugin; - } //-- ReportPlugin parseReportPlugin( XmlPullParser, boolean ) + } // -- ReportPlugin parseReportPlugin( XmlPullParser, boolean ) /** * Method parseReportSet. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return ReportSet */ - private ReportSet parseReportSet( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private ReportSet parseReportSet(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); ReportSet reportSet = new ReportSet(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - reportSet.setId( getTrimmedValue( value ) ); - } - else if ( "inherited".equals( name ) ) - { - reportSet.setInherited( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + reportSet.setId(getTrimmedValue(value)); + } else if ("inherited".equals(name)) { + reportSet.setInherited(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "reports", null, parsed ) ) - { - java.util.List reports = new java.util.ArrayList/**/(); - reportSet.setReports( reports ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "report".equals( parser.getName() ) ) - { - reports.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "reports", null, parsed)) { + java.util.List reports = new java.util.ArrayList /**/(); + reportSet.setReports(reports); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("report".equals(parser.getName())) { + reports.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "configuration", null, parsed ) ) - { - reportSet.setConfiguration( org.codehaus.plexus.util.xml.Xpp3DomBuilder.build( parser ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "configuration", null, parsed)) { + reportSet.setConfiguration(org.codehaus.plexus.util.xml.Xpp3DomBuilder.build(parser)); + } else { + checkUnknownElement(parser, strict); } } return reportSet; - } //-- ReportSet parseReportSet( XmlPullParser, boolean ) + } // -- ReportSet parseReportSet( XmlPullParser, boolean ) /** * Method parseReporting. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Reporting */ - private Reporting parseReporting( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Reporting parseReporting(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Reporting reporting = new Reporting(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "excludeDefaults".equals( name ) ) - { - reporting.setExcludeDefaults( getTrimmedValue( value ) ); - } - else if ( "outputDirectory".equals( name ) ) - { - reporting.setOutputDirectory( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("excludeDefaults".equals(name)) { + reporting.setExcludeDefaults(getTrimmedValue(value)); + } else if ("outputDirectory".equals(name)) { + reporting.setOutputDirectory(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "plugins", null, parsed ) ) - { - java.util.List plugins = new java.util.ArrayList/**/(); - reporting.setPlugins( plugins ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "plugin".equals( parser.getName() ) ) - { - plugins.add( parseReportPlugin( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "plugins", null, parsed)) { + java.util.List plugins = new java.util.ArrayList /**/(); + reporting.setPlugins(plugins); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("plugin".equals(parser.getName())) { + plugins.add(parseReportPlugin(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return reporting; - } //-- Reporting parseReporting( XmlPullParser, boolean ) + } // -- Reporting parseReporting( XmlPullParser, boolean ) /** * Method parseRepository. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Repository */ - private Repository parseRepository( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Repository parseRepository(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); Repository repository = new Repository(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - repository.setId( getTrimmedValue( value ) ); - } - else if ( "name".equals( name ) ) - { - repository.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - repository.setUrl( getTrimmedValue( value ) ); - } - else if ( "layout".equals( name ) ) - { - repository.setLayout( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + repository.setId(getTrimmedValue(value)); + } else if ("name".equals(name)) { + repository.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + repository.setUrl(getTrimmedValue(value)); + } else if ("layout".equals(name)) { + repository.setLayout(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "releases", null, parsed ) ) - { - repository.setReleases( parseRepositoryPolicy( parser, strict ) ); - } - else if ( checkFieldWithDuplicate( parser, "snapshots", null, parsed ) ) - { - repository.setSnapshots( parseRepositoryPolicy( parser, strict ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "releases", null, parsed)) { + repository.setReleases(parseRepositoryPolicy(parser, strict)); + } else if (checkFieldWithDuplicate(parser, "snapshots", null, parsed)) { + repository.setSnapshots(parseRepositoryPolicy(parser, strict)); + } else { + checkUnknownElement(parser, strict); } } return repository; - } //-- Repository parseRepository( XmlPullParser, boolean ) + } // -- Repository parseRepository( XmlPullParser, boolean ) /** * Method parseRepositoryBase. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return RepositoryBase */ - private RepositoryBase parseRepositoryBase( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private RepositoryBase parseRepositoryBase(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); RepositoryBase repositoryBase = new RepositoryBase(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - repositoryBase.setId( getTrimmedValue( value ) ); - } - else if ( "name".equals( name ) ) - { - repositoryBase.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - repositoryBase.setUrl( getTrimmedValue( value ) ); - } - else if ( "layout".equals( name ) ) - { - repositoryBase.setLayout( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + repositoryBase.setId(getTrimmedValue(value)); + } else if ("name".equals(name)) { + repositoryBase.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + repositoryBase.setUrl(getTrimmedValue(value)); + } else if ("layout".equals(name)) { + repositoryBase.setLayout(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return repositoryBase; - } //-- RepositoryBase parseRepositoryBase( XmlPullParser, boolean ) + } // -- RepositoryBase parseRepositoryBase( XmlPullParser, boolean ) /** * Method parseRepositoryPolicy. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return RepositoryPolicy */ - private RepositoryPolicy parseRepositoryPolicy( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private RepositoryPolicy parseRepositoryPolicy(XmlPullParser parser, boolean strict) + throws IOException, XmlPullParserException { String tagName = parser.getName(); RepositoryPolicy repositoryPolicy = new RepositoryPolicy(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "enabled".equals( name ) ) - { - repositoryPolicy.setEnabled( getTrimmedValue( value ) ); - } - else if ( "updatePolicy".equals( name ) ) - { - repositoryPolicy.setUpdatePolicy( getTrimmedValue( value ) ); - } - else if ( "checksumPolicy".equals( name ) ) - { - repositoryPolicy.setChecksumPolicy( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("enabled".equals(name)) { + repositoryPolicy.setEnabled(getTrimmedValue(value)); + } else if ("updatePolicy".equals(name)) { + repositoryPolicy.setUpdatePolicy(getTrimmedValue(value)); + } else if ("checksumPolicy".equals(name)) { + repositoryPolicy.setChecksumPolicy(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return repositoryPolicy; - } //-- RepositoryPolicy parseRepositoryPolicy( XmlPullParser, boolean ) + } // -- RepositoryPolicy parseRepositoryPolicy( XmlPullParser, boolean ) /** * Method parseResource. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Resource */ - private Resource parseResource( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Resource parseResource(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Resource resource = new Resource(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "targetPath".equals( name ) ) - { - resource.setTargetPath( getTrimmedValue( value ) ); - } - else if ( "filtering".equals( name ) ) - { - resource.setFiltering( getTrimmedValue( value ) ); - } - else if ( "directory".equals( name ) ) - { - resource.setDirectory( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("targetPath".equals(name)) { + resource.setTargetPath(getTrimmedValue(value)); + } else if ("filtering".equals(name)) { + resource.setFiltering(getTrimmedValue(value)); + } else if ("directory".equals(name)) { + resource.setDirectory(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - if ( checkFieldWithDuplicate( parser, "includes", null, parsed ) ) - { - java.util.List includes = new java.util.ArrayList/**/(); - resource.setIncludes( includes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "include".equals( parser.getName() ) ) - { - includes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + if (checkFieldWithDuplicate(parser, "includes", null, parsed)) { + java.util.List includes = new java.util.ArrayList /**/(); + resource.setIncludes(includes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("include".equals(parser.getName())) { + includes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else if ( checkFieldWithDuplicate( parser, "excludes", null, parsed ) ) - { - java.util.List excludes = new java.util.ArrayList/**/(); - resource.setExcludes( excludes ); - while ( parser.nextTag() == XmlPullParser.START_TAG ) - { - if ( "exclude".equals( parser.getName() ) ) - { - excludes.add( getTrimmedValue( parser.nextText() ) ); - } - else - { - checkUnknownElement( parser, strict ); + } else if (checkFieldWithDuplicate(parser, "excludes", null, parsed)) { + java.util.List excludes = new java.util.ArrayList /**/(); + resource.setExcludes(excludes); + while (parser.nextTag() == XmlPullParser.START_TAG) { + if ("exclude".equals(parser.getName())) { + excludes.add(getTrimmedValue(parser.nextText())); + } else { + checkUnknownElement(parser, strict); } } - } - else - { - checkUnknownElement( parser, strict ); + } else { + checkUnknownElement(parser, strict); } } return resource; - } //-- Resource parseResource( XmlPullParser, boolean ) + } // -- Resource parseResource( XmlPullParser, boolean ) /** * Method parseScm. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Scm */ - private Scm parseScm( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Scm parseScm(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Scm scm = new Scm(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "connection".equals( name ) ) - { - scm.setConnection( getTrimmedValue( value ) ); - } - else if ( "developerConnection".equals( name ) ) - { - scm.setDeveloperConnection( getTrimmedValue( value ) ); - } - else if ( "tag".equals( name ) ) - { - scm.setTag( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - scm.setUrl( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("connection".equals(name)) { + scm.setConnection(getTrimmedValue(value)); + } else if ("developerConnection".equals(name)) { + scm.setDeveloperConnection(getTrimmedValue(value)); + } else if ("tag".equals(name)) { + scm.setTag(getTrimmedValue(value)); + } else if ("url".equals(name)) { + scm.setUrl(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return scm; - } //-- Scm parseScm( XmlPullParser, boolean ) + } // -- Scm parseScm( XmlPullParser, boolean ) /** * Method parseSite. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Site */ - private Site parseSite( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Site parseSite(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { String tagName = parser.getName(); Site site = new Site(); - for ( int i = parser.getAttributeCount() - 1; i >= 0; i-- ) - { - String name = parser.getAttributeName( i ); - String value = parser.getAttributeValue( i ); + for (int i = parser.getAttributeCount() - 1; i >= 0; i--) { + String name = parser.getAttributeName(i); + String value = parser.getAttributeValue(i); - if ( name.indexOf( ':' ) >= 0 ) - { + if (name.indexOf(':') >= 0) { // just ignore attributes with non-default namespace (for example: xmlns:xsi) - } - else if ( "id".equals( name ) ) - { - site.setId( getTrimmedValue( value ) ); - } - else if ( "name".equals( name ) ) - { - site.setName( getTrimmedValue( value ) ); - } - else if ( "url".equals( name ) ) - { - site.setUrl( getTrimmedValue( value ) ); - } - else - { - checkUnknownAttribute( parser, name, tagName, strict ); + } else if ("id".equals(name)) { + site.setId(getTrimmedValue(value)); + } else if ("name".equals(name)) { + site.setName(getTrimmedValue(value)); + } else if ("url".equals(name)) { + site.setUrl(getTrimmedValue(value)); + } else { + checkUnknownAttribute(parser, name, tagName, strict); } } java.util.Set parsed = new java.util.HashSet(); - while ( ( strict ? parser.nextTag() : nextTag( parser ) ) == XmlPullParser.START_TAG ) - { - checkUnknownElement( parser, strict ); + while ((strict ? parser.nextTag() : nextTag(parser)) == XmlPullParser.START_TAG) { + checkUnknownElement(parser, strict); } return site; - } //-- Site parseSite( XmlPullParser, boolean ) + } // -- Site parseSite( XmlPullParser, boolean ) /** * @see ReaderFactory#newXmlReader - * + * * @param reader * @param strict * @throws IOException * @throws XmlPullParserException * @return Model */ - public Model read( Reader reader, boolean strict ) - throws IOException, XmlPullParserException - { + public Model read(Reader reader, boolean strict) throws IOException, XmlPullParserException { XmlPullParser parser = new MXParser(); - parser.setInput( reader ); + parser.setInput(reader); - initParser( parser ); + initParser(parser); - return read( parser, strict ); - } //-- Model read( Reader, boolean ) + return read(parser, strict); + } // -- Model read( Reader, boolean ) /** * @see ReaderFactory#newXmlReader - * + * * @param reader * @throws IOException * @throws XmlPullParserException * @return Model */ - public Model read( Reader reader ) - throws IOException, XmlPullParserException - { - return read( reader, true ); - } //-- Model read( Reader ) + public Model read(Reader reader) throws IOException, XmlPullParserException { + return read(reader, true); + } // -- Model read( Reader ) /** * Method read. - * + * * @param in * @param strict * @throws IOException * @throws XmlPullParserException * @return Model */ - public Model read( InputStream in, boolean strict ) - throws IOException, XmlPullParserException - { - return read( ReaderFactory.newXmlReader( in ), strict ); - } //-- Model read( InputStream, boolean ) + public Model read(InputStream in, boolean strict) throws IOException, XmlPullParserException { + return read(ReaderFactory.newXmlReader(in), strict); + } // -- Model read( InputStream, boolean ) /** * Method read. - * + * * @param in * @throws IOException * @throws XmlPullParserException * @return Model */ - public Model read( InputStream in ) - throws IOException, XmlPullParserException - { - return read( ReaderFactory.newXmlReader( in ) ); - } //-- Model read( InputStream ) + public Model read(InputStream in) throws IOException, XmlPullParserException { + return read(ReaderFactory.newXmlReader(in)); + } // -- Model read( InputStream ) /** * Method read. - * + * * @param parser * @param strict * @throws IOException * @throws XmlPullParserException * @return Model */ - private Model read( XmlPullParser parser, boolean strict ) - throws IOException, XmlPullParserException - { + private Model read(XmlPullParser parser, boolean strict) throws IOException, XmlPullParserException { int eventType = parser.getEventType(); - while ( eventType != XmlPullParser.END_DOCUMENT ) - { - if ( eventType == XmlPullParser.START_TAG ) - { - if ( strict && ! "project".equals( parser.getName() ) ) - { - throw new XmlPullParserException( "Expected root element 'project' but found '" + parser.getName() + "'", parser, null ); - } - Model model = parseModel( parser, strict ); - model.setModelEncoding( parser.getInputEncoding() ); + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + if (strict && !"project".equals(parser.getName())) { + throw new XmlPullParserException( + "Expected root element 'project' but found '" + parser.getName() + "'", parser, null); + } + Model model = parseModel(parser, strict); + model.setModelEncoding(parser.getInputEncoding()); return model; } eventType = parser.next(); } - throw new XmlPullParserException( "Expected root element 'project' but found no element at all: invalid XML document", parser, null ); - } //-- Model read( XmlPullParser, boolean ) + throw new XmlPullParserException( + "Expected root element 'project' but found no element at all: invalid XML document", parser, null); + } // -- Model read( XmlPullParser, boolean ) /** * Sets the state of the "add default entities" flag. - * + * * @param addDefaultEntities */ - public void setAddDefaultEntities( boolean addDefaultEntities ) - { + public void setAddDefaultEntities(boolean addDefaultEntities) { this.addDefaultEntities = addDefaultEntities; - } //-- void setAddDefaultEntities( boolean ) - + } // -- void setAddDefaultEntities( boolean ) } diff --git a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Writer.java b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Writer.java index a676b30c..dd423b2c 100644 --- a/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Writer.java +++ b/polyglot-xml/src/main/java/org/sonatype/maven/polyglot/xml/xpp3/PolyglotMavenXpp3Writer.java @@ -1,15 +1,15 @@ /* - =================== DO NOT EDIT THIS FILE ==================== - Generated by Modello 1.5 on 2016-10-03 11:37:27, - any modifications will be overwritten. - ============================================================== - */ +=================== DO NOT EDIT THIS FILE ==================== +Generated by Modello 1.5 on 2016-10-03 11:37:27, +any modifications will be overwritten. +============================================================== +*/ package org.sonatype.maven.polyglot.xml.xpp3; - //---------------------------------/ - //- Imported classes and packages -/ -//---------------------------------/ +// ---------------------------------/ +// - Imported classes and packages -/ +// ---------------------------------/ import java.io.OutputStream; import java.io.Writer; @@ -63,1942 +63,1657 @@ /** * Class MavenXpp3Writer. - * + * * @version $Revision$ $Date$ */ -public class PolyglotMavenXpp3Writer -{ +public class PolyglotMavenXpp3Writer { - //--------------------------/ - //- Class/Member Variables -/ - //--------------------------/ + // --------------------------/ + // - Class/Member Variables -/ + // --------------------------/ /** * Field NAMESPACE. */ private static final String NAMESPACE = null; - - //-----------/ - //- Methods -/ - //-----------/ + // -----------/ + // - Methods -/ + // -----------/ /** * Method write. - * + * * @param writer * @param model * @throws java.io.IOException */ - public void write( Writer writer, Model model ) - throws java.io.IOException - { + public void write(Writer writer, Model model) throws java.io.IOException { XmlSerializer serializer = new MXSerializer(); - serializer.setProperty( "http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " " ); - serializer.setProperty( "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n" ); - serializer.setOutput( writer ); - serializer.startDocument( model.getModelEncoding(), null ); - writeModel( model, "project", serializer ); + serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " "); + serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n"); + serializer.setOutput(writer); + serializer.startDocument(model.getModelEncoding(), null); + writeModel(model, "project", serializer); serializer.endDocument(); - } //-- void write( Writer, Model ) + } // -- void write( Writer, Model ) /** * Method write. - * + * * @param stream * @param model * @throws java.io.IOException */ - public void write( OutputStream stream, Model model ) - throws java.io.IOException - { + public void write(OutputStream stream, Model model) throws java.io.IOException { XmlSerializer serializer = new MXSerializer(); - serializer.setProperty( "http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " " ); - serializer.setProperty( "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n" ); - serializer.setOutput( stream, model.getModelEncoding() ); - serializer.startDocument( model.getModelEncoding(), null ); - writeModel( model, "project", serializer ); + serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " "); + serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n"); + serializer.setOutput(stream, model.getModelEncoding()); + serializer.startDocument(model.getModelEncoding(), null); + writeModel(model, "project", serializer); serializer.endDocument(); - } //-- void write( OutputStream, Model ) + } // -- void write( OutputStream, Model ) /** * Method writeActivation. - * + * * @param activation * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeActivation( Activation activation, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( activation.isActiveByDefault() != false ) - { - serializer.attribute( NAMESPACE, "activeByDefault", String.valueOf( activation.isActiveByDefault() ) ); - } - if ( activation.getJdk() != null ) - { - serializer.attribute( NAMESPACE, "jdk", activation.getJdk() ); - } - if ( activation.getOs() != null ) - { - writeActivationOS( (ActivationOS) activation.getOs(), "os", serializer ); - } - if ( activation.getProperty() != null ) - { - writeActivationProperty( (ActivationProperty) activation.getProperty(), "property", serializer ); - } - if ( activation.getFile() != null ) - { - writeActivationFile( (ActivationFile) activation.getFile(), "file", serializer ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeActivation( Activation, String, XmlSerializer ) + private void writeActivation(Activation activation, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (activation.isActiveByDefault() != false) { + serializer.attribute(NAMESPACE, "activeByDefault", String.valueOf(activation.isActiveByDefault())); + } + if (activation.getJdk() != null) { + serializer.attribute(NAMESPACE, "jdk", activation.getJdk()); + } + if (activation.getOs() != null) { + writeActivationOS((ActivationOS) activation.getOs(), "os", serializer); + } + if (activation.getProperty() != null) { + writeActivationProperty((ActivationProperty) activation.getProperty(), "property", serializer); + } + if (activation.getFile() != null) { + writeActivationFile((ActivationFile) activation.getFile(), "file", serializer); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeActivation( Activation, String, XmlSerializer ) /** * Method writeActivationFile. - * + * * @param activationFile * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeActivationFile( ActivationFile activationFile, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( activationFile.getMissing() != null ) - { - serializer.attribute( NAMESPACE, "missing", activationFile.getMissing() ); - } - if ( activationFile.getExists() != null ) - { - serializer.attribute( NAMESPACE, "exists", activationFile.getExists() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeActivationFile( ActivationFile, String, XmlSerializer ) + private void writeActivationFile(ActivationFile activationFile, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (activationFile.getMissing() != null) { + serializer.attribute(NAMESPACE, "missing", activationFile.getMissing()); + } + if (activationFile.getExists() != null) { + serializer.attribute(NAMESPACE, "exists", activationFile.getExists()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeActivationFile( ActivationFile, String, XmlSerializer ) /** * Method writeActivationOS. - * + * * @param activationOS * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeActivationOS( ActivationOS activationOS, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( activationOS.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", activationOS.getName() ); - } - if ( activationOS.getFamily() != null ) - { - serializer.attribute( NAMESPACE, "family", activationOS.getFamily() ); - } - if ( activationOS.getArch() != null ) - { - serializer.attribute( NAMESPACE, "arch", activationOS.getArch() ); - } - if ( activationOS.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", activationOS.getVersion() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeActivationOS( ActivationOS, String, XmlSerializer ) + private void writeActivationOS(ActivationOS activationOS, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (activationOS.getName() != null) { + serializer.attribute(NAMESPACE, "name", activationOS.getName()); + } + if (activationOS.getFamily() != null) { + serializer.attribute(NAMESPACE, "family", activationOS.getFamily()); + } + if (activationOS.getArch() != null) { + serializer.attribute(NAMESPACE, "arch", activationOS.getArch()); + } + if (activationOS.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", activationOS.getVersion()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeActivationOS( ActivationOS, String, XmlSerializer ) /** * Method writeActivationProperty. - * + * * @param activationProperty * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeActivationProperty( ActivationProperty activationProperty, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( activationProperty.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", activationProperty.getName() ); - } - if ( activationProperty.getValue() != null ) - { - serializer.attribute( NAMESPACE, "value", activationProperty.getValue() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeActivationProperty( ActivationProperty, String, XmlSerializer ) + private void writeActivationProperty( + ActivationProperty activationProperty, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (activationProperty.getName() != null) { + serializer.attribute(NAMESPACE, "name", activationProperty.getName()); + } + if (activationProperty.getValue() != null) { + serializer.attribute(NAMESPACE, "value", activationProperty.getValue()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeActivationProperty( ActivationProperty, String, XmlSerializer ) /** * Method writeBuild. - * + * * @param build * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeBuild( Build build, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( build.getSourceDirectory() != null ) - { - serializer.attribute( NAMESPACE, "sourceDirectory", build.getSourceDirectory() ); - } - if ( build.getScriptSourceDirectory() != null ) - { - serializer.attribute( NAMESPACE, "scriptSourceDirectory", build.getScriptSourceDirectory() ); - } - if ( build.getTestSourceDirectory() != null ) - { - serializer.attribute( NAMESPACE, "testSourceDirectory", build.getTestSourceDirectory() ); - } - if ( build.getOutputDirectory() != null ) - { - serializer.attribute( NAMESPACE, "outputDirectory", build.getOutputDirectory() ); - } - if ( build.getTestOutputDirectory() != null ) - { - serializer.attribute( NAMESPACE, "testOutputDirectory", build.getTestOutputDirectory() ); - } - if ( build.getDefaultGoal() != null ) - { - serializer.attribute( NAMESPACE, "defaultGoal", build.getDefaultGoal() ); - } - if ( build.getDirectory() != null ) - { - serializer.attribute( NAMESPACE, "directory", build.getDirectory() ); - } - if ( build.getFinalName() != null ) - { - serializer.attribute( NAMESPACE, "finalName", build.getFinalName() ); - } - if ( ( build.getExtensions() != null ) && ( build.getExtensions().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "extensions" ); - for ( Iterator iter = build.getExtensions().iterator(); iter.hasNext(); ) - { + private void writeBuild(Build build, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (build.getSourceDirectory() != null) { + serializer.attribute(NAMESPACE, "sourceDirectory", build.getSourceDirectory()); + } + if (build.getScriptSourceDirectory() != null) { + serializer.attribute(NAMESPACE, "scriptSourceDirectory", build.getScriptSourceDirectory()); + } + if (build.getTestSourceDirectory() != null) { + serializer.attribute(NAMESPACE, "testSourceDirectory", build.getTestSourceDirectory()); + } + if (build.getOutputDirectory() != null) { + serializer.attribute(NAMESPACE, "outputDirectory", build.getOutputDirectory()); + } + if (build.getTestOutputDirectory() != null) { + serializer.attribute(NAMESPACE, "testOutputDirectory", build.getTestOutputDirectory()); + } + if (build.getDefaultGoal() != null) { + serializer.attribute(NAMESPACE, "defaultGoal", build.getDefaultGoal()); + } + if (build.getDirectory() != null) { + serializer.attribute(NAMESPACE, "directory", build.getDirectory()); + } + if (build.getFinalName() != null) { + serializer.attribute(NAMESPACE, "finalName", build.getFinalName()); + } + if ((build.getExtensions() != null) && (build.getExtensions().size() > 0)) { + serializer.startTag(NAMESPACE, "extensions"); + for (Iterator iter = build.getExtensions().iterator(); iter.hasNext(); ) { Extension o = (Extension) iter.next(); - writeExtension( o, "extension", serializer ); + writeExtension(o, "extension", serializer); } - serializer.endTag( NAMESPACE, "extensions" ); + serializer.endTag(NAMESPACE, "extensions"); } - if ( ( build.getResources() != null ) && ( build.getResources().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "resources" ); - for ( Iterator iter = build.getResources().iterator(); iter.hasNext(); ) - { + if ((build.getResources() != null) && (build.getResources().size() > 0)) { + serializer.startTag(NAMESPACE, "resources"); + for (Iterator iter = build.getResources().iterator(); iter.hasNext(); ) { Resource o = (Resource) iter.next(); - writeResource( o, "resource", serializer ); + writeResource(o, "resource", serializer); } - serializer.endTag( NAMESPACE, "resources" ); + serializer.endTag(NAMESPACE, "resources"); } - if ( ( build.getTestResources() != null ) && ( build.getTestResources().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "testResources" ); - for ( Iterator iter = build.getTestResources().iterator(); iter.hasNext(); ) - { + if ((build.getTestResources() != null) && (build.getTestResources().size() > 0)) { + serializer.startTag(NAMESPACE, "testResources"); + for (Iterator iter = build.getTestResources().iterator(); iter.hasNext(); ) { Resource o = (Resource) iter.next(); - writeResource( o, "testResource", serializer ); + writeResource(o, "testResource", serializer); } - serializer.endTag( NAMESPACE, "testResources" ); + serializer.endTag(NAMESPACE, "testResources"); } - if ( ( build.getFilters() != null ) && ( build.getFilters().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "filters" ); - for ( Iterator iter = build.getFilters().iterator(); iter.hasNext(); ) - { + if ((build.getFilters() != null) && (build.getFilters().size() > 0)) { + serializer.startTag(NAMESPACE, "filters"); + for (Iterator iter = build.getFilters().iterator(); iter.hasNext(); ) { String filter = (String) iter.next(); - serializer.startTag( NAMESPACE, "filter" ).text( filter ).endTag( NAMESPACE, "filter" ); + serializer.startTag(NAMESPACE, "filter").text(filter).endTag(NAMESPACE, "filter"); } - serializer.endTag( NAMESPACE, "filters" ); + serializer.endTag(NAMESPACE, "filters"); } - if ( build.getPluginManagement() != null ) - { - writePluginManagement( (PluginManagement) build.getPluginManagement(), "pluginManagement", serializer ); + if (build.getPluginManagement() != null) { + writePluginManagement((PluginManagement) build.getPluginManagement(), "pluginManagement", serializer); } - if ( ( build.getPlugins() != null ) && ( build.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = build.getPlugins().iterator(); iter.hasNext(); ) - { + if ((build.getPlugins() != null) && (build.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = build.getPlugins().iterator(); iter.hasNext(); ) { Plugin o = (Plugin) iter.next(); - writePlugin( o, "plugin", serializer ); + writePlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeBuild( Build, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeBuild( Build, String, XmlSerializer ) /** * Method writeBuildBase. - * + * * @param buildBase * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeBuildBase( BuildBase buildBase, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( buildBase.getDefaultGoal() != null ) - { - serializer.attribute( NAMESPACE, "defaultGoal", buildBase.getDefaultGoal() ); - } - if ( buildBase.getDirectory() != null ) - { - serializer.attribute( NAMESPACE, "directory", buildBase.getDirectory() ); - } - if ( buildBase.getFinalName() != null ) - { - serializer.attribute( NAMESPACE, "finalName", buildBase.getFinalName() ); - } - if ( ( buildBase.getResources() != null ) && ( buildBase.getResources().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "resources" ); - for ( Iterator iter = buildBase.getResources().iterator(); iter.hasNext(); ) - { + private void writeBuildBase(BuildBase buildBase, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (buildBase.getDefaultGoal() != null) { + serializer.attribute(NAMESPACE, "defaultGoal", buildBase.getDefaultGoal()); + } + if (buildBase.getDirectory() != null) { + serializer.attribute(NAMESPACE, "directory", buildBase.getDirectory()); + } + if (buildBase.getFinalName() != null) { + serializer.attribute(NAMESPACE, "finalName", buildBase.getFinalName()); + } + if ((buildBase.getResources() != null) && (buildBase.getResources().size() > 0)) { + serializer.startTag(NAMESPACE, "resources"); + for (Iterator iter = buildBase.getResources().iterator(); iter.hasNext(); ) { Resource o = (Resource) iter.next(); - writeResource( o, "resource", serializer ); + writeResource(o, "resource", serializer); } - serializer.endTag( NAMESPACE, "resources" ); + serializer.endTag(NAMESPACE, "resources"); } - if ( ( buildBase.getTestResources() != null ) && ( buildBase.getTestResources().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "testResources" ); - for ( Iterator iter = buildBase.getTestResources().iterator(); iter.hasNext(); ) - { + if ((buildBase.getTestResources() != null) + && (buildBase.getTestResources().size() > 0)) { + serializer.startTag(NAMESPACE, "testResources"); + for (Iterator iter = buildBase.getTestResources().iterator(); iter.hasNext(); ) { Resource o = (Resource) iter.next(); - writeResource( o, "testResource", serializer ); + writeResource(o, "testResource", serializer); } - serializer.endTag( NAMESPACE, "testResources" ); + serializer.endTag(NAMESPACE, "testResources"); } - if ( ( buildBase.getFilters() != null ) && ( buildBase.getFilters().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "filters" ); - for ( Iterator iter = buildBase.getFilters().iterator(); iter.hasNext(); ) - { + if ((buildBase.getFilters() != null) && (buildBase.getFilters().size() > 0)) { + serializer.startTag(NAMESPACE, "filters"); + for (Iterator iter = buildBase.getFilters().iterator(); iter.hasNext(); ) { String filter = (String) iter.next(); - serializer.startTag( NAMESPACE, "filter" ).text( filter ).endTag( NAMESPACE, "filter" ); + serializer.startTag(NAMESPACE, "filter").text(filter).endTag(NAMESPACE, "filter"); } - serializer.endTag( NAMESPACE, "filters" ); + serializer.endTag(NAMESPACE, "filters"); } - if ( buildBase.getPluginManagement() != null ) - { - writePluginManagement( (PluginManagement) buildBase.getPluginManagement(), "pluginManagement", serializer ); + if (buildBase.getPluginManagement() != null) { + writePluginManagement((PluginManagement) buildBase.getPluginManagement(), "pluginManagement", serializer); } - if ( ( buildBase.getPlugins() != null ) && ( buildBase.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = buildBase.getPlugins().iterator(); iter.hasNext(); ) - { + if ((buildBase.getPlugins() != null) && (buildBase.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = buildBase.getPlugins().iterator(); iter.hasNext(); ) { Plugin o = (Plugin) iter.next(); - writePlugin( o, "plugin", serializer ); + writePlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeBuildBase( BuildBase, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeBuildBase( BuildBase, String, XmlSerializer ) /** * Method writeCiManagement. - * + * * @param ciManagement * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeCiManagement( CiManagement ciManagement, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ciManagement.getSystem() != null ) - { - serializer.attribute( NAMESPACE, "system", ciManagement.getSystem() ); - } - if ( ciManagement.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", ciManagement.getUrl() ); - } - if ( ( ciManagement.getNotifiers() != null ) && ( ciManagement.getNotifiers().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "notifiers" ); - for ( Iterator iter = ciManagement.getNotifiers().iterator(); iter.hasNext(); ) - { + private void writeCiManagement(CiManagement ciManagement, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (ciManagement.getSystem() != null) { + serializer.attribute(NAMESPACE, "system", ciManagement.getSystem()); + } + if (ciManagement.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", ciManagement.getUrl()); + } + if ((ciManagement.getNotifiers() != null) + && (ciManagement.getNotifiers().size() > 0)) { + serializer.startTag(NAMESPACE, "notifiers"); + for (Iterator iter = ciManagement.getNotifiers().iterator(); iter.hasNext(); ) { Notifier o = (Notifier) iter.next(); - writeNotifier( o, "notifier", serializer ); + writeNotifier(o, "notifier", serializer); } - serializer.endTag( NAMESPACE, "notifiers" ); + serializer.endTag(NAMESPACE, "notifiers"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeCiManagement( CiManagement, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeCiManagement( CiManagement, String, XmlSerializer ) /** * Method writeConfigurationContainer. - * + * * @param configurationContainer * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeConfigurationContainer( ConfigurationContainer configurationContainer, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( configurationContainer.getInherited() != null ) - { - serializer.attribute( NAMESPACE, "inherited", configurationContainer.getInherited() ); - } - if ( configurationContainer.getConfiguration() != null ) - { - ((Xpp3Dom) configurationContainer.getConfiguration()).writeToSerializer( NAMESPACE, serializer ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeConfigurationContainer( ConfigurationContainer, String, XmlSerializer ) + private void writeConfigurationContainer( + ConfigurationContainer configurationContainer, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (configurationContainer.getInherited() != null) { + serializer.attribute(NAMESPACE, "inherited", configurationContainer.getInherited()); + } + if (configurationContainer.getConfiguration() != null) { + ((Xpp3Dom) configurationContainer.getConfiguration()).writeToSerializer(NAMESPACE, serializer); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeConfigurationContainer( ConfigurationContainer, String, XmlSerializer ) /** * Method writeContributor. - * + * * @param contributor * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeContributor( Contributor contributor, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( contributor.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", contributor.getName() ); - } - if ( contributor.getEmail() != null ) - { - serializer.attribute( NAMESPACE, "email", contributor.getEmail() ); - } - if ( contributor.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", contributor.getUrl() ); - } - if ( contributor.getOrganization() != null ) - { - serializer.attribute( NAMESPACE, "organization", contributor.getOrganization() ); - } - if ( contributor.getOrganizationUrl() != null ) - { - serializer.attribute( NAMESPACE, "organizationUrl", contributor.getOrganizationUrl() ); - } - if ( contributor.getTimezone() != null ) - { - serializer.attribute( NAMESPACE, "timezone", contributor.getTimezone() ); - } - if ( ( contributor.getRoles() != null ) && ( contributor.getRoles().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "roles" ); - for ( Iterator iter = contributor.getRoles().iterator(); iter.hasNext(); ) - { + private void writeContributor(Contributor contributor, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (contributor.getName() != null) { + serializer.attribute(NAMESPACE, "name", contributor.getName()); + } + if (contributor.getEmail() != null) { + serializer.attribute(NAMESPACE, "email", contributor.getEmail()); + } + if (contributor.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", contributor.getUrl()); + } + if (contributor.getOrganization() != null) { + serializer.attribute(NAMESPACE, "organization", contributor.getOrganization()); + } + if (contributor.getOrganizationUrl() != null) { + serializer.attribute(NAMESPACE, "organizationUrl", contributor.getOrganizationUrl()); + } + if (contributor.getTimezone() != null) { + serializer.attribute(NAMESPACE, "timezone", contributor.getTimezone()); + } + if ((contributor.getRoles() != null) && (contributor.getRoles().size() > 0)) { + serializer.startTag(NAMESPACE, "roles"); + for (Iterator iter = contributor.getRoles().iterator(); iter.hasNext(); ) { String role = (String) iter.next(); - serializer.startTag( NAMESPACE, "role" ).text( role ).endTag( NAMESPACE, "role" ); + serializer.startTag(NAMESPACE, "role").text(role).endTag(NAMESPACE, "role"); } - serializer.endTag( NAMESPACE, "roles" ); + serializer.endTag(NAMESPACE, "roles"); } - if ( ( contributor.getProperties() != null ) && ( contributor.getProperties().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "properties" ); - for ( Iterator iter = contributor.getProperties().keySet().iterator(); iter.hasNext(); ) - { + if ((contributor.getProperties() != null) + && (contributor.getProperties().size() > 0)) { + serializer.startTag(NAMESPACE, "properties"); + for (Iterator iter = contributor.getProperties().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) contributor.getProperties().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) contributor.getProperties().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "properties" ); + serializer.endTag(NAMESPACE, "properties"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeContributor( Contributor, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeContributor( Contributor, String, XmlSerializer ) /** * Method writeDependency. - * + * * @param dependency * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeDependency( Dependency dependency, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( dependency.getGroupId() != null ) - { - serializer.attribute( NAMESPACE, "groupId", dependency.getGroupId() ); - } - if ( dependency.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", dependency.getArtifactId() ); - } - if ( dependency.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", dependency.getVersion() ); - } - if ( ( dependency.getType() != null ) && !dependency.getType().equals( "jar" ) ) - { - serializer.attribute( NAMESPACE, "type", dependency.getType() ); - } - if ( dependency.getClassifier() != null ) - { - serializer.attribute( NAMESPACE, "classifier", dependency.getClassifier() ); - } - if ( dependency.getScope() != null ) - { - serializer.attribute( NAMESPACE, "scope", dependency.getScope() ); - } - if ( dependency.getSystemPath() != null ) - { - serializer.attribute( NAMESPACE, "systemPath", dependency.getSystemPath() ); - } - if ( ( dependency.getOptional() != null ) && !dependency.getOptional().equals( "false" ) ) - { - serializer.attribute( NAMESPACE, "optional", dependency.getOptional() ); - } - if ( ( dependency.getExclusions() != null ) && ( dependency.getExclusions().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "exclusions" ); - for ( Iterator iter = dependency.getExclusions().iterator(); iter.hasNext(); ) - { + private void writeDependency(Dependency dependency, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (dependency.getGroupId() != null) { + serializer.attribute(NAMESPACE, "groupId", dependency.getGroupId()); + } + if (dependency.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", dependency.getArtifactId()); + } + if (dependency.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", dependency.getVersion()); + } + if ((dependency.getType() != null) && !dependency.getType().equals("jar")) { + serializer.attribute(NAMESPACE, "type", dependency.getType()); + } + if (dependency.getClassifier() != null) { + serializer.attribute(NAMESPACE, "classifier", dependency.getClassifier()); + } + if (dependency.getScope() != null) { + serializer.attribute(NAMESPACE, "scope", dependency.getScope()); + } + if (dependency.getSystemPath() != null) { + serializer.attribute(NAMESPACE, "systemPath", dependency.getSystemPath()); + } + if ((dependency.getOptional() != null) && !dependency.getOptional().equals("false")) { + serializer.attribute(NAMESPACE, "optional", dependency.getOptional()); + } + if ((dependency.getExclusions() != null) && (dependency.getExclusions().size() > 0)) { + serializer.startTag(NAMESPACE, "exclusions"); + for (Iterator iter = dependency.getExclusions().iterator(); iter.hasNext(); ) { Exclusion o = (Exclusion) iter.next(); - writeExclusion( o, "exclusion", serializer ); + writeExclusion(o, "exclusion", serializer); } - serializer.endTag( NAMESPACE, "exclusions" ); + serializer.endTag(NAMESPACE, "exclusions"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeDependency( Dependency, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeDependency( Dependency, String, XmlSerializer ) /** * Method writeDependencyManagement. - * + * * @param dependencyManagement * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeDependencyManagement( DependencyManagement dependencyManagement, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( dependencyManagement.getDependencies() != null ) && ( dependencyManagement.getDependencies().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "dependencies" ); - for ( Iterator iter = dependencyManagement.getDependencies().iterator(); iter.hasNext(); ) - { + private void writeDependencyManagement( + DependencyManagement dependencyManagement, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((dependencyManagement.getDependencies() != null) + && (dependencyManagement.getDependencies().size() > 0)) { + serializer.startTag(NAMESPACE, "dependencies"); + for (Iterator iter = dependencyManagement.getDependencies().iterator(); iter.hasNext(); ) { Dependency o = (Dependency) iter.next(); - writeDependency( o, "dependency", serializer ); + writeDependency(o, "dependency", serializer); } - serializer.endTag( NAMESPACE, "dependencies" ); + serializer.endTag(NAMESPACE, "dependencies"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeDependencyManagement( DependencyManagement, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeDependencyManagement( DependencyManagement, String, XmlSerializer ) /** * Method writeDeploymentRepository. - * + * * @param deploymentRepository * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeDeploymentRepository( DeploymentRepository deploymentRepository, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( deploymentRepository.isUniqueVersion() != true ) - { - serializer.attribute( NAMESPACE, "uniqueVersion", String.valueOf( deploymentRepository.isUniqueVersion() ) ); - } - if ( deploymentRepository.getId() != null ) - { - serializer.attribute( NAMESPACE, "id", deploymentRepository.getId() ); - } - if ( deploymentRepository.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", deploymentRepository.getName() ); - } - if ( deploymentRepository.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", deploymentRepository.getUrl() ); - } - if ( ( deploymentRepository.getLayout() != null ) && !deploymentRepository.getLayout().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "layout", deploymentRepository.getLayout() ); - } - if ( deploymentRepository.getReleases() != null ) - { - writeRepositoryPolicy( (RepositoryPolicy) deploymentRepository.getReleases(), "releases", serializer ); - } - if ( deploymentRepository.getSnapshots() != null ) - { - writeRepositoryPolicy( (RepositoryPolicy) deploymentRepository.getSnapshots(), "snapshots", serializer ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeDeploymentRepository( DeploymentRepository, String, XmlSerializer ) + private void writeDeploymentRepository( + DeploymentRepository deploymentRepository, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (deploymentRepository.isUniqueVersion() != true) { + serializer.attribute(NAMESPACE, "uniqueVersion", String.valueOf(deploymentRepository.isUniqueVersion())); + } + if (deploymentRepository.getId() != null) { + serializer.attribute(NAMESPACE, "id", deploymentRepository.getId()); + } + if (deploymentRepository.getName() != null) { + serializer.attribute(NAMESPACE, "name", deploymentRepository.getName()); + } + if (deploymentRepository.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", deploymentRepository.getUrl()); + } + if ((deploymentRepository.getLayout() != null) + && !deploymentRepository.getLayout().equals("default")) { + serializer.attribute(NAMESPACE, "layout", deploymentRepository.getLayout()); + } + if (deploymentRepository.getReleases() != null) { + writeRepositoryPolicy((RepositoryPolicy) deploymentRepository.getReleases(), "releases", serializer); + } + if (deploymentRepository.getSnapshots() != null) { + writeRepositoryPolicy((RepositoryPolicy) deploymentRepository.getSnapshots(), "snapshots", serializer); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeDeploymentRepository( DeploymentRepository, String, XmlSerializer ) /** * Method writeDeveloper. - * + * * @param developer * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeDeveloper( Developer developer, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( developer.getId() != null ) - { - serializer.attribute( NAMESPACE, "id", developer.getId() ); - } - if ( developer.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", developer.getName() ); - } - if ( developer.getEmail() != null ) - { - serializer.attribute( NAMESPACE, "email", developer.getEmail() ); - } - if ( developer.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", developer.getUrl() ); - } - if ( developer.getOrganization() != null ) - { - serializer.attribute( NAMESPACE, "organization", developer.getOrganization() ); - } - if ( developer.getOrganizationUrl() != null ) - { - serializer.attribute( NAMESPACE, "organizationUrl", developer.getOrganizationUrl() ); - } - if ( developer.getTimezone() != null ) - { - serializer.attribute( NAMESPACE, "timezone", developer.getTimezone() ); - } - if ( ( developer.getRoles() != null ) && ( developer.getRoles().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "roles" ); - for ( Iterator iter = developer.getRoles().iterator(); iter.hasNext(); ) - { + private void writeDeveloper(Developer developer, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (developer.getId() != null) { + serializer.attribute(NAMESPACE, "id", developer.getId()); + } + if (developer.getName() != null) { + serializer.attribute(NAMESPACE, "name", developer.getName()); + } + if (developer.getEmail() != null) { + serializer.attribute(NAMESPACE, "email", developer.getEmail()); + } + if (developer.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", developer.getUrl()); + } + if (developer.getOrganization() != null) { + serializer.attribute(NAMESPACE, "organization", developer.getOrganization()); + } + if (developer.getOrganizationUrl() != null) { + serializer.attribute(NAMESPACE, "organizationUrl", developer.getOrganizationUrl()); + } + if (developer.getTimezone() != null) { + serializer.attribute(NAMESPACE, "timezone", developer.getTimezone()); + } + if ((developer.getRoles() != null) && (developer.getRoles().size() > 0)) { + serializer.startTag(NAMESPACE, "roles"); + for (Iterator iter = developer.getRoles().iterator(); iter.hasNext(); ) { String role = (String) iter.next(); - serializer.startTag( NAMESPACE, "role" ).text( role ).endTag( NAMESPACE, "role" ); + serializer.startTag(NAMESPACE, "role").text(role).endTag(NAMESPACE, "role"); } - serializer.endTag( NAMESPACE, "roles" ); + serializer.endTag(NAMESPACE, "roles"); } - if ( ( developer.getProperties() != null ) && ( developer.getProperties().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "properties" ); - for ( Iterator iter = developer.getProperties().keySet().iterator(); iter.hasNext(); ) - { + if ((developer.getProperties() != null) && (developer.getProperties().size() > 0)) { + serializer.startTag(NAMESPACE, "properties"); + for (Iterator iter = developer.getProperties().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) developer.getProperties().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) developer.getProperties().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "properties" ); + serializer.endTag(NAMESPACE, "properties"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeDeveloper( Developer, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeDeveloper( Developer, String, XmlSerializer ) /** * Method writeDistributionManagement. - * + * * @param distributionManagement * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeDistributionManagement( DistributionManagement distributionManagement, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( distributionManagement.getDownloadUrl() != null ) - { - serializer.attribute( NAMESPACE, "downloadUrl", distributionManagement.getDownloadUrl() ); - } - if ( distributionManagement.getStatus() != null ) - { - serializer.attribute( NAMESPACE, "status", distributionManagement.getStatus() ); - } - if ( distributionManagement.getRepository() != null ) - { - writeDeploymentRepository( (DeploymentRepository) distributionManagement.getRepository(), "repository", serializer ); - } - if ( distributionManagement.getSnapshotRepository() != null ) - { - writeDeploymentRepository( (DeploymentRepository) distributionManagement.getSnapshotRepository(), "snapshotRepository", serializer ); - } - if ( distributionManagement.getSite() != null ) - { - writeSite( (Site) distributionManagement.getSite(), "site", serializer ); - } - if ( distributionManagement.getRelocation() != null ) - { - writeRelocation( (Relocation) distributionManagement.getRelocation(), "relocation", serializer ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeDistributionManagement( DistributionManagement, String, XmlSerializer ) + private void writeDistributionManagement( + DistributionManagement distributionManagement, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (distributionManagement.getDownloadUrl() != null) { + serializer.attribute(NAMESPACE, "downloadUrl", distributionManagement.getDownloadUrl()); + } + if (distributionManagement.getStatus() != null) { + serializer.attribute(NAMESPACE, "status", distributionManagement.getStatus()); + } + if (distributionManagement.getRepository() != null) { + writeDeploymentRepository( + (DeploymentRepository) distributionManagement.getRepository(), "repository", serializer); + } + if (distributionManagement.getSnapshotRepository() != null) { + writeDeploymentRepository( + (DeploymentRepository) distributionManagement.getSnapshotRepository(), + "snapshotRepository", + serializer); + } + if (distributionManagement.getSite() != null) { + writeSite((Site) distributionManagement.getSite(), "site", serializer); + } + if (distributionManagement.getRelocation() != null) { + writeRelocation((Relocation) distributionManagement.getRelocation(), "relocation", serializer); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeDistributionManagement( DistributionManagement, String, XmlSerializer ) /** * Method writeExclusion. - * + * * @param exclusion * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeExclusion( Exclusion exclusion, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( exclusion.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", exclusion.getArtifactId() ); - } - if ( exclusion.getGroupId() != null ) - { - serializer.attribute( NAMESPACE, "groupId", exclusion.getGroupId() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeExclusion( Exclusion, String, XmlSerializer ) + private void writeExclusion(Exclusion exclusion, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (exclusion.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", exclusion.getArtifactId()); + } + if (exclusion.getGroupId() != null) { + serializer.attribute(NAMESPACE, "groupId", exclusion.getGroupId()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeExclusion( Exclusion, String, XmlSerializer ) /** * Method writeExtension. - * + * * @param extension * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeExtension( Extension extension, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( extension.getGroupId() != null ) - { - serializer.attribute( NAMESPACE, "groupId", extension.getGroupId() ); - } - if ( extension.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", extension.getArtifactId() ); - } - if ( extension.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", extension.getVersion() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeExtension( Extension, String, XmlSerializer ) + private void writeExtension(Extension extension, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (extension.getGroupId() != null) { + serializer.attribute(NAMESPACE, "groupId", extension.getGroupId()); + } + if (extension.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", extension.getArtifactId()); + } + if (extension.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", extension.getVersion()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeExtension( Extension, String, XmlSerializer ) /** * Method writeFileSet. - * + * * @param fileSet * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeFileSet( FileSet fileSet, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( fileSet.getDirectory() != null ) - { - serializer.attribute( NAMESPACE, "directory", fileSet.getDirectory() ); - } - if ( ( fileSet.getIncludes() != null ) && ( fileSet.getIncludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "includes" ); - for ( Iterator iter = fileSet.getIncludes().iterator(); iter.hasNext(); ) - { + private void writeFileSet(FileSet fileSet, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (fileSet.getDirectory() != null) { + serializer.attribute(NAMESPACE, "directory", fileSet.getDirectory()); + } + if ((fileSet.getIncludes() != null) && (fileSet.getIncludes().size() > 0)) { + serializer.startTag(NAMESPACE, "includes"); + for (Iterator iter = fileSet.getIncludes().iterator(); iter.hasNext(); ) { String include = (String) iter.next(); - serializer.startTag( NAMESPACE, "include" ).text( include ).endTag( NAMESPACE, "include" ); + serializer.startTag(NAMESPACE, "include").text(include).endTag(NAMESPACE, "include"); } - serializer.endTag( NAMESPACE, "includes" ); + serializer.endTag(NAMESPACE, "includes"); } - if ( ( fileSet.getExcludes() != null ) && ( fileSet.getExcludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "excludes" ); - for ( Iterator iter = fileSet.getExcludes().iterator(); iter.hasNext(); ) - { + if ((fileSet.getExcludes() != null) && (fileSet.getExcludes().size() > 0)) { + serializer.startTag(NAMESPACE, "excludes"); + for (Iterator iter = fileSet.getExcludes().iterator(); iter.hasNext(); ) { String exclude = (String) iter.next(); - serializer.startTag( NAMESPACE, "exclude" ).text( exclude ).endTag( NAMESPACE, "exclude" ); + serializer.startTag(NAMESPACE, "exclude").text(exclude).endTag(NAMESPACE, "exclude"); } - serializer.endTag( NAMESPACE, "excludes" ); + serializer.endTag(NAMESPACE, "excludes"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeFileSet( FileSet, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeFileSet( FileSet, String, XmlSerializer ) /** * Method writeIssueManagement. - * + * * @param issueManagement * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeIssueManagement( IssueManagement issueManagement, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( issueManagement.getSystem() != null ) - { - serializer.attribute( NAMESPACE, "system", issueManagement.getSystem() ); - } - if ( issueManagement.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", issueManagement.getUrl() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeIssueManagement( IssueManagement, String, XmlSerializer ) + private void writeIssueManagement(IssueManagement issueManagement, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (issueManagement.getSystem() != null) { + serializer.attribute(NAMESPACE, "system", issueManagement.getSystem()); + } + if (issueManagement.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", issueManagement.getUrl()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeIssueManagement( IssueManagement, String, XmlSerializer ) /** * Method writeLicense. - * + * * @param license * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeLicense( License license, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( license.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", license.getName() ); - } - if ( license.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", license.getUrl() ); - } - if ( license.getDistribution() != null ) - { - serializer.attribute( NAMESPACE, "distribution", license.getDistribution() ); - } - if ( license.getComments() != null ) - { - serializer.attribute( NAMESPACE, "comments", license.getComments() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeLicense( License, String, XmlSerializer ) + private void writeLicense(License license, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (license.getName() != null) { + serializer.attribute(NAMESPACE, "name", license.getName()); + } + if (license.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", license.getUrl()); + } + if (license.getDistribution() != null) { + serializer.attribute(NAMESPACE, "distribution", license.getDistribution()); + } + if (license.getComments() != null) { + serializer.attribute(NAMESPACE, "comments", license.getComments()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeLicense( License, String, XmlSerializer ) /** * Method writeMailingList. - * + * * @param mailingList * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeMailingList( MailingList mailingList, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( mailingList.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", mailingList.getName() ); - } - if ( mailingList.getSubscribe() != null ) - { - serializer.attribute( NAMESPACE, "subscribe", mailingList.getSubscribe() ); - } - if ( mailingList.getUnsubscribe() != null ) - { - serializer.attribute( NAMESPACE, "unsubscribe", mailingList.getUnsubscribe() ); - } - if ( mailingList.getPost() != null ) - { - serializer.attribute( NAMESPACE, "post", mailingList.getPost() ); - } - if ( mailingList.getArchive() != null ) - { - serializer.attribute( NAMESPACE, "archive", mailingList.getArchive() ); - } - if ( ( mailingList.getOtherArchives() != null ) && ( mailingList.getOtherArchives().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "otherArchives" ); - for ( Iterator iter = mailingList.getOtherArchives().iterator(); iter.hasNext(); ) - { + private void writeMailingList(MailingList mailingList, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (mailingList.getName() != null) { + serializer.attribute(NAMESPACE, "name", mailingList.getName()); + } + if (mailingList.getSubscribe() != null) { + serializer.attribute(NAMESPACE, "subscribe", mailingList.getSubscribe()); + } + if (mailingList.getUnsubscribe() != null) { + serializer.attribute(NAMESPACE, "unsubscribe", mailingList.getUnsubscribe()); + } + if (mailingList.getPost() != null) { + serializer.attribute(NAMESPACE, "post", mailingList.getPost()); + } + if (mailingList.getArchive() != null) { + serializer.attribute(NAMESPACE, "archive", mailingList.getArchive()); + } + if ((mailingList.getOtherArchives() != null) + && (mailingList.getOtherArchives().size() > 0)) { + serializer.startTag(NAMESPACE, "otherArchives"); + for (Iterator iter = mailingList.getOtherArchives().iterator(); iter.hasNext(); ) { String otherArchive = (String) iter.next(); - serializer.startTag( NAMESPACE, "otherArchive" ).text( otherArchive ).endTag( NAMESPACE, "otherArchive" ); + serializer + .startTag(NAMESPACE, "otherArchive") + .text(otherArchive) + .endTag(NAMESPACE, "otherArchive"); } - serializer.endTag( NAMESPACE, "otherArchives" ); + serializer.endTag(NAMESPACE, "otherArchives"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeMailingList( MailingList, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeMailingList( MailingList, String, XmlSerializer ) /** * Method writeModel. - * + * * @param model * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeModel( Model model, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.setPrefix( "", "http://maven.apache.org/POM/4.1.0" ); - serializer.setPrefix( "xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - serializer.startTag( NAMESPACE, tagName ); - serializer.attribute( "", "xsi:schemaLocation", "http://maven.apache.org/POM/4.1.0 http://maven.apache.org/xsd/maven-4.1.0.xsd" ); - if ( model.getModelVersion() != null ) - { - serializer.startTag( NAMESPACE, "modelVersion" ).text( model.getModelVersion() ).endTag( NAMESPACE, "modelVersion" ); - } - if ( model.getParent() != null ) - { - writeParent( (Parent) model.getParent(), "parent", serializer ); - } - if ( model.getGroupId() != null ) - { - serializer.startTag( NAMESPACE, "groupId" ).text( model.getGroupId() ).endTag( NAMESPACE, "groupId" ); - } - if ( model.getArtifactId() != null ) - { - serializer.startTag( NAMESPACE, "artifactId" ).text( model.getArtifactId() ).endTag( NAMESPACE, "artifactId" ); - } - if ( model.getVersion() != null ) - { - serializer.startTag( NAMESPACE, "version" ).text( model.getVersion() ).endTag( NAMESPACE, "version" ); - } - if ( ( model.getPackaging() != null ) && !model.getPackaging().equals( "jar" ) ) - { - serializer.startTag( NAMESPACE, "packaging" ).text( model.getPackaging() ).endTag( NAMESPACE, "packaging" ); - } - if ( model.getName() != null ) - { - serializer.startTag( NAMESPACE, "name" ).text( model.getName() ).endTag( NAMESPACE, "name" ); - } - if ( model.getDescription() != null ) - { - serializer.startTag( NAMESPACE, "description" ).text( model.getDescription() ).endTag( NAMESPACE, "description" ); - } - if ( model.getUrl() != null ) - { - serializer.startTag( NAMESPACE, "url" ).text( model.getUrl() ).endTag( NAMESPACE, "url" ); - } - if ( model.getInceptionYear() != null ) - { - serializer.startTag( NAMESPACE, "inceptionYear" ).text( model.getInceptionYear() ).endTag( NAMESPACE, "inceptionYear" ); - } - if ( model.getOrganization() != null ) - { - writeOrganization( (Organization) model.getOrganization(), "organization", serializer ); - } - if ( ( model.getLicenses() != null ) && ( model.getLicenses().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "licenses" ); - for ( Iterator iter = model.getLicenses().iterator(); iter.hasNext(); ) - { + private void writeModel(Model model, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.setPrefix("", "http://maven.apache.org/POM/4.1.0"); + serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + serializer.startTag(NAMESPACE, tagName); + serializer.attribute( + "", + "xsi:schemaLocation", + "http://maven.apache.org/POM/4.1.0 http://maven.apache.org/xsd/maven-4.1.0.xsd"); + if (model.getModelVersion() != null) { + serializer + .startTag(NAMESPACE, "modelVersion") + .text(model.getModelVersion()) + .endTag(NAMESPACE, "modelVersion"); + } + if (model.getParent() != null) { + writeParent((Parent) model.getParent(), "parent", serializer); + } + if (model.getGroupId() != null) { + serializer.startTag(NAMESPACE, "groupId").text(model.getGroupId()).endTag(NAMESPACE, "groupId"); + } + if (model.getArtifactId() != null) { + serializer + .startTag(NAMESPACE, "artifactId") + .text(model.getArtifactId()) + .endTag(NAMESPACE, "artifactId"); + } + if (model.getVersion() != null) { + serializer.startTag(NAMESPACE, "version").text(model.getVersion()).endTag(NAMESPACE, "version"); + } + if ((model.getPackaging() != null) && !model.getPackaging().equals("jar")) { + serializer + .startTag(NAMESPACE, "packaging") + .text(model.getPackaging()) + .endTag(NAMESPACE, "packaging"); + } + if (model.getName() != null) { + serializer.startTag(NAMESPACE, "name").text(model.getName()).endTag(NAMESPACE, "name"); + } + if (model.getDescription() != null) { + serializer + .startTag(NAMESPACE, "description") + .text(model.getDescription()) + .endTag(NAMESPACE, "description"); + } + if (model.getUrl() != null) { + serializer.startTag(NAMESPACE, "url").text(model.getUrl()).endTag(NAMESPACE, "url"); + } + if (model.getInceptionYear() != null) { + serializer + .startTag(NAMESPACE, "inceptionYear") + .text(model.getInceptionYear()) + .endTag(NAMESPACE, "inceptionYear"); + } + if (model.getOrganization() != null) { + writeOrganization((Organization) model.getOrganization(), "organization", serializer); + } + if ((model.getLicenses() != null) && (model.getLicenses().size() > 0)) { + serializer.startTag(NAMESPACE, "licenses"); + for (Iterator iter = model.getLicenses().iterator(); iter.hasNext(); ) { License o = (License) iter.next(); - writeLicense( o, "license", serializer ); + writeLicense(o, "license", serializer); } - serializer.endTag( NAMESPACE, "licenses" ); + serializer.endTag(NAMESPACE, "licenses"); } - if ( ( model.getDevelopers() != null ) && ( model.getDevelopers().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "developers" ); - for ( Iterator iter = model.getDevelopers().iterator(); iter.hasNext(); ) - { + if ((model.getDevelopers() != null) && (model.getDevelopers().size() > 0)) { + serializer.startTag(NAMESPACE, "developers"); + for (Iterator iter = model.getDevelopers().iterator(); iter.hasNext(); ) { Developer o = (Developer) iter.next(); - writeDeveloper( o, "developer", serializer ); + writeDeveloper(o, "developer", serializer); } - serializer.endTag( NAMESPACE, "developers" ); + serializer.endTag(NAMESPACE, "developers"); } - if ( ( model.getContributors() != null ) && ( model.getContributors().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "contributors" ); - for ( Iterator iter = model.getContributors().iterator(); iter.hasNext(); ) - { + if ((model.getContributors() != null) && (model.getContributors().size() > 0)) { + serializer.startTag(NAMESPACE, "contributors"); + for (Iterator iter = model.getContributors().iterator(); iter.hasNext(); ) { Contributor o = (Contributor) iter.next(); - writeContributor( o, "contributor", serializer ); + writeContributor(o, "contributor", serializer); } - serializer.endTag( NAMESPACE, "contributors" ); + serializer.endTag(NAMESPACE, "contributors"); } - if ( ( model.getMailingLists() != null ) && ( model.getMailingLists().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "mailingLists" ); - for ( Iterator iter = model.getMailingLists().iterator(); iter.hasNext(); ) - { + if ((model.getMailingLists() != null) && (model.getMailingLists().size() > 0)) { + serializer.startTag(NAMESPACE, "mailingLists"); + for (Iterator iter = model.getMailingLists().iterator(); iter.hasNext(); ) { MailingList o = (MailingList) iter.next(); - writeMailingList( o, "mailingList", serializer ); + writeMailingList(o, "mailingList", serializer); } - serializer.endTag( NAMESPACE, "mailingLists" ); + serializer.endTag(NAMESPACE, "mailingLists"); } - if ( model.getPrerequisites() != null ) - { - writePrerequisites( (Prerequisites) model.getPrerequisites(), "prerequisites", serializer ); + if (model.getPrerequisites() != null) { + writePrerequisites((Prerequisites) model.getPrerequisites(), "prerequisites", serializer); } - if ( ( model.getModules() != null ) && ( model.getModules().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "modules" ); - for ( Iterator iter = model.getModules().iterator(); iter.hasNext(); ) - { + if ((model.getModules() != null) && (model.getModules().size() > 0)) { + serializer.startTag(NAMESPACE, "modules"); + for (Iterator iter = model.getModules().iterator(); iter.hasNext(); ) { String module = (String) iter.next(); - serializer.startTag( NAMESPACE, "module" ).text( module ).endTag( NAMESPACE, "module" ); + serializer.startTag(NAMESPACE, "module").text(module).endTag(NAMESPACE, "module"); } - serializer.endTag( NAMESPACE, "modules" ); + serializer.endTag(NAMESPACE, "modules"); } - if ( model.getScm() != null ) - { - writeScm( (Scm) model.getScm(), "scm", serializer ); + if (model.getScm() != null) { + writeScm((Scm) model.getScm(), "scm", serializer); } - if ( model.getIssueManagement() != null ) - { - writeIssueManagement( (IssueManagement) model.getIssueManagement(), "issueManagement", serializer ); + if (model.getIssueManagement() != null) { + writeIssueManagement((IssueManagement) model.getIssueManagement(), "issueManagement", serializer); } - if ( model.getCiManagement() != null ) - { - writeCiManagement( (CiManagement) model.getCiManagement(), "ciManagement", serializer ); + if (model.getCiManagement() != null) { + writeCiManagement((CiManagement) model.getCiManagement(), "ciManagement", serializer); } - if ( model.getDistributionManagement() != null ) - { - writeDistributionManagement( (DistributionManagement) model.getDistributionManagement(), "distributionManagement", serializer ); + if (model.getDistributionManagement() != null) { + writeDistributionManagement( + (DistributionManagement) model.getDistributionManagement(), "distributionManagement", serializer); } - if ( ( model.getProperties() != null ) && ( model.getProperties().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "properties" ); - for ( Iterator iter = model.getProperties().keySet().iterator(); iter.hasNext(); ) - { + if ((model.getProperties() != null) && (model.getProperties().size() > 0)) { + serializer.startTag(NAMESPACE, "properties"); + for (Iterator iter = model.getProperties().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) model.getProperties().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) model.getProperties().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "properties" ); + serializer.endTag(NAMESPACE, "properties"); } - if ( model.getDependencyManagement() != null ) - { - writeDependencyManagement( (DependencyManagement) model.getDependencyManagement(), "dependencyManagement", serializer ); + if (model.getDependencyManagement() != null) { + writeDependencyManagement( + (DependencyManagement) model.getDependencyManagement(), "dependencyManagement", serializer); } - if ( ( model.getDependencies() != null ) && ( model.getDependencies().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "dependencies" ); - for ( Iterator iter = model.getDependencies().iterator(); iter.hasNext(); ) - { + if ((model.getDependencies() != null) && (model.getDependencies().size() > 0)) { + serializer.startTag(NAMESPACE, "dependencies"); + for (Iterator iter = model.getDependencies().iterator(); iter.hasNext(); ) { Dependency o = (Dependency) iter.next(); - writeDependency( o, "dependency", serializer ); + writeDependency(o, "dependency", serializer); } - serializer.endTag( NAMESPACE, "dependencies" ); + serializer.endTag(NAMESPACE, "dependencies"); } - if ( ( model.getRepositories() != null ) && ( model.getRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "repositories" ); - for ( Iterator iter = model.getRepositories().iterator(); iter.hasNext(); ) - { + if ((model.getRepositories() != null) && (model.getRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "repositories"); + for (Iterator iter = model.getRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "repository", serializer ); + writeRepository(o, "repository", serializer); } - serializer.endTag( NAMESPACE, "repositories" ); + serializer.endTag(NAMESPACE, "repositories"); } - if ( ( model.getPluginRepositories() != null ) && ( model.getPluginRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "pluginRepositories" ); - for ( Iterator iter = model.getPluginRepositories().iterator(); iter.hasNext(); ) - { + if ((model.getPluginRepositories() != null) + && (model.getPluginRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "pluginRepositories"); + for (Iterator iter = model.getPluginRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "pluginRepository", serializer ); + writeRepository(o, "pluginRepository", serializer); } - serializer.endTag( NAMESPACE, "pluginRepositories" ); + serializer.endTag(NAMESPACE, "pluginRepositories"); } - if ( model.getBuild() != null ) - { - writeBuild( (Build) model.getBuild(), "build", serializer ); + if (model.getBuild() != null) { + writeBuild((Build) model.getBuild(), "build", serializer); } - if ( model.getReports() != null ) - { - ((Xpp3Dom) model.getReports()).writeToSerializer( NAMESPACE, serializer ); + if (model.getReports() != null) { + ((Xpp3Dom) model.getReports()).writeToSerializer(NAMESPACE, serializer); } - if ( model.getReporting() != null ) - { - writeReporting( (Reporting) model.getReporting(), "reporting", serializer ); + if (model.getReporting() != null) { + writeReporting((Reporting) model.getReporting(), "reporting", serializer); } - if ( ( model.getProfiles() != null ) && ( model.getProfiles().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "profiles" ); - for ( Iterator iter = model.getProfiles().iterator(); iter.hasNext(); ) - { + if ((model.getProfiles() != null) && (model.getProfiles().size() > 0)) { + serializer.startTag(NAMESPACE, "profiles"); + for (Iterator iter = model.getProfiles().iterator(); iter.hasNext(); ) { Profile o = (Profile) iter.next(); - writeProfile( o, "profile", serializer ); + writeProfile(o, "profile", serializer); } - serializer.endTag( NAMESPACE, "profiles" ); + serializer.endTag(NAMESPACE, "profiles"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeModel( Model, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeModel( Model, String, XmlSerializer ) /** * Method writeModelBase. - * + * * @param modelBase * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeModelBase( ModelBase modelBase, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( modelBase.getModules() != null ) && ( modelBase.getModules().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "modules" ); - for ( Iterator iter = modelBase.getModules().iterator(); iter.hasNext(); ) - { + private void writeModelBase(ModelBase modelBase, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((modelBase.getModules() != null) && (modelBase.getModules().size() > 0)) { + serializer.startTag(NAMESPACE, "modules"); + for (Iterator iter = modelBase.getModules().iterator(); iter.hasNext(); ) { String module = (String) iter.next(); - serializer.startTag( NAMESPACE, "module" ).text( module ).endTag( NAMESPACE, "module" ); + serializer.startTag(NAMESPACE, "module").text(module).endTag(NAMESPACE, "module"); } - serializer.endTag( NAMESPACE, "modules" ); + serializer.endTag(NAMESPACE, "modules"); } - if ( modelBase.getDistributionManagement() != null ) - { - writeDistributionManagement( (DistributionManagement) modelBase.getDistributionManagement(), "distributionManagement", serializer ); + if (modelBase.getDistributionManagement() != null) { + writeDistributionManagement( + (DistributionManagement) modelBase.getDistributionManagement(), + "distributionManagement", + serializer); } - if ( ( modelBase.getProperties() != null ) && ( modelBase.getProperties().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "properties" ); - for ( Iterator iter = modelBase.getProperties().keySet().iterator(); iter.hasNext(); ) - { + if ((modelBase.getProperties() != null) && (modelBase.getProperties().size() > 0)) { + serializer.startTag(NAMESPACE, "properties"); + for (Iterator iter = modelBase.getProperties().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) modelBase.getProperties().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) modelBase.getProperties().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "properties" ); + serializer.endTag(NAMESPACE, "properties"); } - if ( modelBase.getDependencyManagement() != null ) - { - writeDependencyManagement( (DependencyManagement) modelBase.getDependencyManagement(), "dependencyManagement", serializer ); + if (modelBase.getDependencyManagement() != null) { + writeDependencyManagement( + (DependencyManagement) modelBase.getDependencyManagement(), "dependencyManagement", serializer); } - if ( ( modelBase.getDependencies() != null ) && ( modelBase.getDependencies().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "dependencies" ); - for ( Iterator iter = modelBase.getDependencies().iterator(); iter.hasNext(); ) - { + if ((modelBase.getDependencies() != null) + && (modelBase.getDependencies().size() > 0)) { + serializer.startTag(NAMESPACE, "dependencies"); + for (Iterator iter = modelBase.getDependencies().iterator(); iter.hasNext(); ) { Dependency o = (Dependency) iter.next(); - writeDependency( o, "dependency", serializer ); + writeDependency(o, "dependency", serializer); } - serializer.endTag( NAMESPACE, "dependencies" ); + serializer.endTag(NAMESPACE, "dependencies"); } - if ( ( modelBase.getRepositories() != null ) && ( modelBase.getRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "repositories" ); - for ( Iterator iter = modelBase.getRepositories().iterator(); iter.hasNext(); ) - { + if ((modelBase.getRepositories() != null) + && (modelBase.getRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "repositories"); + for (Iterator iter = modelBase.getRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "repository", serializer ); + writeRepository(o, "repository", serializer); } - serializer.endTag( NAMESPACE, "repositories" ); + serializer.endTag(NAMESPACE, "repositories"); } - if ( ( modelBase.getPluginRepositories() != null ) && ( modelBase.getPluginRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "pluginRepositories" ); - for ( Iterator iter = modelBase.getPluginRepositories().iterator(); iter.hasNext(); ) - { + if ((modelBase.getPluginRepositories() != null) + && (modelBase.getPluginRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "pluginRepositories"); + for (Iterator iter = modelBase.getPluginRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "pluginRepository", serializer ); + writeRepository(o, "pluginRepository", serializer); } - serializer.endTag( NAMESPACE, "pluginRepositories" ); + serializer.endTag(NAMESPACE, "pluginRepositories"); } - if ( modelBase.getReports() != null ) - { - ((Xpp3Dom) modelBase.getReports()).writeToSerializer( NAMESPACE, serializer ); + if (modelBase.getReports() != null) { + ((Xpp3Dom) modelBase.getReports()).writeToSerializer(NAMESPACE, serializer); } - if ( modelBase.getReporting() != null ) - { - writeReporting( (Reporting) modelBase.getReporting(), "reporting", serializer ); + if (modelBase.getReporting() != null) { + writeReporting((Reporting) modelBase.getReporting(), "reporting", serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeModelBase( ModelBase, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeModelBase( ModelBase, String, XmlSerializer ) /** * Method writeNotifier. - * + * * @param notifier * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeNotifier( Notifier notifier, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( notifier.getType() != null ) && !notifier.getType().equals( "mail" ) ) - { - serializer.attribute( NAMESPACE, "type", notifier.getType() ); - } - if ( notifier.isSendOnError() != true ) - { - serializer.attribute( NAMESPACE, "sendOnError", String.valueOf( notifier.isSendOnError() ) ); - } - if ( notifier.isSendOnFailure() != true ) - { - serializer.attribute( NAMESPACE, "sendOnFailure", String.valueOf( notifier.isSendOnFailure() ) ); - } - if ( notifier.isSendOnSuccess() != true ) - { - serializer.attribute( NAMESPACE, "sendOnSuccess", String.valueOf( notifier.isSendOnSuccess() ) ); - } - if ( notifier.isSendOnWarning() != true ) - { - serializer.attribute( NAMESPACE, "sendOnWarning", String.valueOf( notifier.isSendOnWarning() ) ); - } - if ( notifier.getAddress() != null ) - { - serializer.attribute( NAMESPACE, "address", notifier.getAddress() ); - } - if ( ( notifier.getConfiguration() != null ) && ( notifier.getConfiguration().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "configuration" ); - for ( Iterator iter = notifier.getConfiguration().keySet().iterator(); iter.hasNext(); ) - { + private void writeNotifier(Notifier notifier, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((notifier.getType() != null) && !notifier.getType().equals("mail")) { + serializer.attribute(NAMESPACE, "type", notifier.getType()); + } + if (notifier.isSendOnError() != true) { + serializer.attribute(NAMESPACE, "sendOnError", String.valueOf(notifier.isSendOnError())); + } + if (notifier.isSendOnFailure() != true) { + serializer.attribute(NAMESPACE, "sendOnFailure", String.valueOf(notifier.isSendOnFailure())); + } + if (notifier.isSendOnSuccess() != true) { + serializer.attribute(NAMESPACE, "sendOnSuccess", String.valueOf(notifier.isSendOnSuccess())); + } + if (notifier.isSendOnWarning() != true) { + serializer.attribute(NAMESPACE, "sendOnWarning", String.valueOf(notifier.isSendOnWarning())); + } + if (notifier.getAddress() != null) { + serializer.attribute(NAMESPACE, "address", notifier.getAddress()); + } + if ((notifier.getConfiguration() != null) + && (notifier.getConfiguration().size() > 0)) { + serializer.startTag(NAMESPACE, "configuration"); + for (Iterator iter = notifier.getConfiguration().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) notifier.getConfiguration().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) notifier.getConfiguration().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "configuration" ); + serializer.endTag(NAMESPACE, "configuration"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeNotifier( Notifier, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeNotifier( Notifier, String, XmlSerializer ) /** * Method writeOrganization. - * + * * @param organization * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeOrganization( Organization organization, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( organization.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", organization.getName() ); - } - if ( organization.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", organization.getUrl() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeOrganization( Organization, String, XmlSerializer ) + private void writeOrganization(Organization organization, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (organization.getName() != null) { + serializer.attribute(NAMESPACE, "name", organization.getName()); + } + if (organization.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", organization.getUrl()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeOrganization( Organization, String, XmlSerializer ) /** * Method writeParent. - * + * * @param parent * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeParent( Parent parent, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( parent.getGroupId() != null ) - { - serializer.attribute( NAMESPACE, "groupId", parent.getGroupId() ); - } - if ( parent.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", parent.getArtifactId() ); - } - if ( parent.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", parent.getVersion() ); - } - if ( ( parent.getRelativePath() != null ) && !parent.getRelativePath().equals( "../pom.xml" ) ) - { - serializer.attribute( NAMESPACE, "relativePath", parent.getRelativePath() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeParent( Parent, String, XmlSerializer ) + private void writeParent(Parent parent, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (parent.getGroupId() != null) { + serializer.attribute(NAMESPACE, "groupId", parent.getGroupId()); + } + if (parent.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", parent.getArtifactId()); + } + if (parent.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", parent.getVersion()); + } + if ((parent.getRelativePath() != null) && !parent.getRelativePath().equals("../pom.xml")) { + serializer.attribute(NAMESPACE, "relativePath", parent.getRelativePath()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeParent( Parent, String, XmlSerializer ) /** * Method writePatternSet. - * + * * @param patternSet * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePatternSet( PatternSet patternSet, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( patternSet.getIncludes() != null ) && ( patternSet.getIncludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "includes" ); - for ( Iterator iter = patternSet.getIncludes().iterator(); iter.hasNext(); ) - { + private void writePatternSet(PatternSet patternSet, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((patternSet.getIncludes() != null) && (patternSet.getIncludes().size() > 0)) { + serializer.startTag(NAMESPACE, "includes"); + for (Iterator iter = patternSet.getIncludes().iterator(); iter.hasNext(); ) { String include = (String) iter.next(); - serializer.startTag( NAMESPACE, "include" ).text( include ).endTag( NAMESPACE, "include" ); + serializer.startTag(NAMESPACE, "include").text(include).endTag(NAMESPACE, "include"); } - serializer.endTag( NAMESPACE, "includes" ); + serializer.endTag(NAMESPACE, "includes"); } - if ( ( patternSet.getExcludes() != null ) && ( patternSet.getExcludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "excludes" ); - for ( Iterator iter = patternSet.getExcludes().iterator(); iter.hasNext(); ) - { + if ((patternSet.getExcludes() != null) && (patternSet.getExcludes().size() > 0)) { + serializer.startTag(NAMESPACE, "excludes"); + for (Iterator iter = patternSet.getExcludes().iterator(); iter.hasNext(); ) { String exclude = (String) iter.next(); - serializer.startTag( NAMESPACE, "exclude" ).text( exclude ).endTag( NAMESPACE, "exclude" ); + serializer.startTag(NAMESPACE, "exclude").text(exclude).endTag(NAMESPACE, "exclude"); } - serializer.endTag( NAMESPACE, "excludes" ); + serializer.endTag(NAMESPACE, "excludes"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePatternSet( PatternSet, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePatternSet( PatternSet, String, XmlSerializer ) /** * Method writePlugin. - * + * * @param plugin * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePlugin( Plugin plugin, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( plugin.getGroupId() != null ) && !plugin.getGroupId().equals( "org.apache.maven.plugins" ) ) - { - serializer.attribute( NAMESPACE, "groupId", plugin.getGroupId() ); - } - if ( plugin.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", plugin.getArtifactId() ); - } - if ( plugin.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", plugin.getVersion() ); - } - if ( ( plugin.getExtensions() != null ) && !plugin.getExtensions().equals( "false" ) ) - { - serializer.attribute( NAMESPACE, "extensions", plugin.getExtensions() ); - } - if ( plugin.getInherited() != null ) - { - serializer.attribute( NAMESPACE, "inherited", plugin.getInherited() ); - } - if ( ( plugin.getExecutions() != null ) && ( plugin.getExecutions().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "executions" ); - for ( Iterator iter = plugin.getExecutions().iterator(); iter.hasNext(); ) - { + private void writePlugin(Plugin plugin, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((plugin.getGroupId() != null) && !plugin.getGroupId().equals("org.apache.maven.plugins")) { + serializer.attribute(NAMESPACE, "groupId", plugin.getGroupId()); + } + if (plugin.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", plugin.getArtifactId()); + } + if (plugin.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", plugin.getVersion()); + } + if ((plugin.getExtensions() != null) && !plugin.getExtensions().equals("false")) { + serializer.attribute(NAMESPACE, "extensions", plugin.getExtensions()); + } + if (plugin.getInherited() != null) { + serializer.attribute(NAMESPACE, "inherited", plugin.getInherited()); + } + if ((plugin.getExecutions() != null) && (plugin.getExecutions().size() > 0)) { + serializer.startTag(NAMESPACE, "executions"); + for (Iterator iter = plugin.getExecutions().iterator(); iter.hasNext(); ) { PluginExecution o = (PluginExecution) iter.next(); - writePluginExecution( o, "execution", serializer ); + writePluginExecution(o, "execution", serializer); } - serializer.endTag( NAMESPACE, "executions" ); + serializer.endTag(NAMESPACE, "executions"); } - if ( ( plugin.getDependencies() != null ) && ( plugin.getDependencies().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "dependencies" ); - for ( Iterator iter = plugin.getDependencies().iterator(); iter.hasNext(); ) - { + if ((plugin.getDependencies() != null) && (plugin.getDependencies().size() > 0)) { + serializer.startTag(NAMESPACE, "dependencies"); + for (Iterator iter = plugin.getDependencies().iterator(); iter.hasNext(); ) { Dependency o = (Dependency) iter.next(); - writeDependency( o, "dependency", serializer ); + writeDependency(o, "dependency", serializer); } - serializer.endTag( NAMESPACE, "dependencies" ); + serializer.endTag(NAMESPACE, "dependencies"); } - if ( plugin.getGoals() != null ) - { - ((Xpp3Dom) plugin.getGoals()).writeToSerializer( NAMESPACE, serializer ); + if (plugin.getGoals() != null) { + ((Xpp3Dom) plugin.getGoals()).writeToSerializer(NAMESPACE, serializer); } - if ( plugin.getConfiguration() != null ) - { - ((Xpp3Dom) plugin.getConfiguration()).writeToSerializer( NAMESPACE, serializer ); + if (plugin.getConfiguration() != null) { + ((Xpp3Dom) plugin.getConfiguration()).writeToSerializer(NAMESPACE, serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePlugin( Plugin, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePlugin( Plugin, String, XmlSerializer ) /** * Method writePluginConfiguration. - * + * * @param pluginConfiguration * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePluginConfiguration( PluginConfiguration pluginConfiguration, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( pluginConfiguration.getPluginManagement() != null ) - { - writePluginManagement( (PluginManagement) pluginConfiguration.getPluginManagement(), "pluginManagement", serializer ); - } - if ( ( pluginConfiguration.getPlugins() != null ) && ( pluginConfiguration.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = pluginConfiguration.getPlugins().iterator(); iter.hasNext(); ) - { + private void writePluginConfiguration( + PluginConfiguration pluginConfiguration, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (pluginConfiguration.getPluginManagement() != null) { + writePluginManagement( + (PluginManagement) pluginConfiguration.getPluginManagement(), "pluginManagement", serializer); + } + if ((pluginConfiguration.getPlugins() != null) + && (pluginConfiguration.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = pluginConfiguration.getPlugins().iterator(); iter.hasNext(); ) { Plugin o = (Plugin) iter.next(); - writePlugin( o, "plugin", serializer ); + writePlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePluginConfiguration( PluginConfiguration, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePluginConfiguration( PluginConfiguration, String, XmlSerializer ) /** * Method writePluginContainer. - * + * * @param pluginContainer * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePluginContainer( PluginContainer pluginContainer, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( pluginContainer.getPlugins() != null ) && ( pluginContainer.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = pluginContainer.getPlugins().iterator(); iter.hasNext(); ) - { + private void writePluginContainer(PluginContainer pluginContainer, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((pluginContainer.getPlugins() != null) + && (pluginContainer.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = pluginContainer.getPlugins().iterator(); iter.hasNext(); ) { Plugin o = (Plugin) iter.next(); - writePlugin( o, "plugin", serializer ); + writePlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePluginContainer( PluginContainer, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePluginContainer( PluginContainer, String, XmlSerializer ) /** * Method writePluginExecution. - * + * * @param pluginExecution * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePluginExecution( PluginExecution pluginExecution, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( pluginExecution.getId() != null ) && !pluginExecution.getId().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "id", pluginExecution.getId() ); - } - if ( pluginExecution.getPhase() != null ) - { - serializer.attribute( NAMESPACE, "phase", pluginExecution.getPhase() ); - } - if ( pluginExecution.getInherited() != null ) - { - serializer.attribute( NAMESPACE, "inherited", pluginExecution.getInherited() ); - } - if ( ( pluginExecution.getGoals() != null ) && ( pluginExecution.getGoals().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "goals" ); - for ( Iterator iter = pluginExecution.getGoals().iterator(); iter.hasNext(); ) - { + private void writePluginExecution(PluginExecution pluginExecution, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((pluginExecution.getId() != null) && !pluginExecution.getId().equals("default")) { + serializer.attribute(NAMESPACE, "id", pluginExecution.getId()); + } + if (pluginExecution.getPhase() != null) { + serializer.attribute(NAMESPACE, "phase", pluginExecution.getPhase()); + } + if (pluginExecution.getInherited() != null) { + serializer.attribute(NAMESPACE, "inherited", pluginExecution.getInherited()); + } + if ((pluginExecution.getGoals() != null) && (pluginExecution.getGoals().size() > 0)) { + serializer.startTag(NAMESPACE, "goals"); + for (Iterator iter = pluginExecution.getGoals().iterator(); iter.hasNext(); ) { String goal = (String) iter.next(); - serializer.startTag( NAMESPACE, "goal" ).text( goal ).endTag( NAMESPACE, "goal" ); + serializer.startTag(NAMESPACE, "goal").text(goal).endTag(NAMESPACE, "goal"); } - serializer.endTag( NAMESPACE, "goals" ); + serializer.endTag(NAMESPACE, "goals"); } - if ( pluginExecution.getConfiguration() != null ) - { - ((Xpp3Dom) pluginExecution.getConfiguration()).writeToSerializer( NAMESPACE, serializer ); + if (pluginExecution.getConfiguration() != null) { + ((Xpp3Dom) pluginExecution.getConfiguration()).writeToSerializer(NAMESPACE, serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePluginExecution( PluginExecution, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePluginExecution( PluginExecution, String, XmlSerializer ) /** * Method writePluginManagement. - * + * * @param pluginManagement * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePluginManagement( PluginManagement pluginManagement, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( pluginManagement.getPlugins() != null ) && ( pluginManagement.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = pluginManagement.getPlugins().iterator(); iter.hasNext(); ) - { + private void writePluginManagement(PluginManagement pluginManagement, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((pluginManagement.getPlugins() != null) + && (pluginManagement.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = pluginManagement.getPlugins().iterator(); iter.hasNext(); ) { Plugin o = (Plugin) iter.next(); - writePlugin( o, "plugin", serializer ); + writePlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePluginManagement( PluginManagement, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writePluginManagement( PluginManagement, String, XmlSerializer ) /** * Method writePrerequisites. - * + * * @param prerequisites * @param serializer * @param tagName * @throws java.io.IOException */ - private void writePrerequisites( Prerequisites prerequisites, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( prerequisites.getMaven() != null ) && !prerequisites.getMaven().equals( "2.0" ) ) - { - serializer.attribute( NAMESPACE, "maven", prerequisites.getMaven() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writePrerequisites( Prerequisites, String, XmlSerializer ) + private void writePrerequisites(Prerequisites prerequisites, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((prerequisites.getMaven() != null) && !prerequisites.getMaven().equals("2.0")) { + serializer.attribute(NAMESPACE, "maven", prerequisites.getMaven()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writePrerequisites( Prerequisites, String, XmlSerializer ) /** * Method writeProfile. - * + * * @param profile * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeProfile( Profile profile, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( profile.getId() != null ) && !profile.getId().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "id", profile.getId() ); - } - if ( profile.getActivation() != null ) - { - writeActivation( (Activation) profile.getActivation(), "activation", serializer ); - } - if ( profile.getBuild() != null ) - { - writeBuildBase( (BuildBase) profile.getBuild(), "build", serializer ); - } - if ( ( profile.getModules() != null ) && ( profile.getModules().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "modules" ); - for ( Iterator iter = profile.getModules().iterator(); iter.hasNext(); ) - { + private void writeProfile(Profile profile, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((profile.getId() != null) && !profile.getId().equals("default")) { + serializer.attribute(NAMESPACE, "id", profile.getId()); + } + if (profile.getActivation() != null) { + writeActivation((Activation) profile.getActivation(), "activation", serializer); + } + if (profile.getBuild() != null) { + writeBuildBase((BuildBase) profile.getBuild(), "build", serializer); + } + if ((profile.getModules() != null) && (profile.getModules().size() > 0)) { + serializer.startTag(NAMESPACE, "modules"); + for (Iterator iter = profile.getModules().iterator(); iter.hasNext(); ) { String module = (String) iter.next(); - serializer.startTag( NAMESPACE, "module" ).text( module ).endTag( NAMESPACE, "module" ); + serializer.startTag(NAMESPACE, "module").text(module).endTag(NAMESPACE, "module"); } - serializer.endTag( NAMESPACE, "modules" ); + serializer.endTag(NAMESPACE, "modules"); } - if ( profile.getDistributionManagement() != null ) - { - writeDistributionManagement( (DistributionManagement) profile.getDistributionManagement(), "distributionManagement", serializer ); + if (profile.getDistributionManagement() != null) { + writeDistributionManagement( + (DistributionManagement) profile.getDistributionManagement(), "distributionManagement", serializer); } - if ( ( profile.getProperties() != null ) && ( profile.getProperties().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "properties" ); - for ( Iterator iter = profile.getProperties().keySet().iterator(); iter.hasNext(); ) - { + if ((profile.getProperties() != null) && (profile.getProperties().size() > 0)) { + serializer.startTag(NAMESPACE, "properties"); + for (Iterator iter = profile.getProperties().keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); - String value = (String) profile.getProperties().get( key ); - serializer.startTag( NAMESPACE, "" + key + "" ).text( value ).endTag( NAMESPACE, "" + key + "" ); + String value = (String) profile.getProperties().get(key); + serializer.startTag(NAMESPACE, "" + key + "").text(value).endTag(NAMESPACE, "" + key + ""); } - serializer.endTag( NAMESPACE, "properties" ); + serializer.endTag(NAMESPACE, "properties"); } - if ( profile.getDependencyManagement() != null ) - { - writeDependencyManagement( (DependencyManagement) profile.getDependencyManagement(), "dependencyManagement", serializer ); + if (profile.getDependencyManagement() != null) { + writeDependencyManagement( + (DependencyManagement) profile.getDependencyManagement(), "dependencyManagement", serializer); } - if ( ( profile.getDependencies() != null ) && ( profile.getDependencies().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "dependencies" ); - for ( Iterator iter = profile.getDependencies().iterator(); iter.hasNext(); ) - { + if ((profile.getDependencies() != null) && (profile.getDependencies().size() > 0)) { + serializer.startTag(NAMESPACE, "dependencies"); + for (Iterator iter = profile.getDependencies().iterator(); iter.hasNext(); ) { Dependency o = (Dependency) iter.next(); - writeDependency( o, "dependency", serializer ); + writeDependency(o, "dependency", serializer); } - serializer.endTag( NAMESPACE, "dependencies" ); + serializer.endTag(NAMESPACE, "dependencies"); } - if ( ( profile.getRepositories() != null ) && ( profile.getRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "repositories" ); - for ( Iterator iter = profile.getRepositories().iterator(); iter.hasNext(); ) - { + if ((profile.getRepositories() != null) && (profile.getRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "repositories"); + for (Iterator iter = profile.getRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "repository", serializer ); + writeRepository(o, "repository", serializer); } - serializer.endTag( NAMESPACE, "repositories" ); + serializer.endTag(NAMESPACE, "repositories"); } - if ( ( profile.getPluginRepositories() != null ) && ( profile.getPluginRepositories().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "pluginRepositories" ); - for ( Iterator iter = profile.getPluginRepositories().iterator(); iter.hasNext(); ) - { + if ((profile.getPluginRepositories() != null) + && (profile.getPluginRepositories().size() > 0)) { + serializer.startTag(NAMESPACE, "pluginRepositories"); + for (Iterator iter = profile.getPluginRepositories().iterator(); iter.hasNext(); ) { Repository o = (Repository) iter.next(); - writeRepository( o, "pluginRepository", serializer ); + writeRepository(o, "pluginRepository", serializer); } - serializer.endTag( NAMESPACE, "pluginRepositories" ); + serializer.endTag(NAMESPACE, "pluginRepositories"); } - if ( profile.getReports() != null ) - { - ((Xpp3Dom) profile.getReports()).writeToSerializer( NAMESPACE, serializer ); + if (profile.getReports() != null) { + ((Xpp3Dom) profile.getReports()).writeToSerializer(NAMESPACE, serializer); } - if ( profile.getReporting() != null ) - { - writeReporting( (Reporting) profile.getReporting(), "reporting", serializer ); + if (profile.getReporting() != null) { + writeReporting((Reporting) profile.getReporting(), "reporting", serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeProfile( Profile, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeProfile( Profile, String, XmlSerializer ) /** * Method writeRelocation. - * + * * @param relocation * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeRelocation( Relocation relocation, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( relocation.getGroupId() != null ) - { - serializer.attribute( NAMESPACE, "groupId", relocation.getGroupId() ); - } - if ( relocation.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", relocation.getArtifactId() ); - } - if ( relocation.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", relocation.getVersion() ); - } - if ( relocation.getMessage() != null ) - { - serializer.attribute( NAMESPACE, "message", relocation.getMessage() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeRelocation( Relocation, String, XmlSerializer ) + private void writeRelocation(Relocation relocation, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (relocation.getGroupId() != null) { + serializer.attribute(NAMESPACE, "groupId", relocation.getGroupId()); + } + if (relocation.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", relocation.getArtifactId()); + } + if (relocation.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", relocation.getVersion()); + } + if (relocation.getMessage() != null) { + serializer.attribute(NAMESPACE, "message", relocation.getMessage()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeRelocation( Relocation, String, XmlSerializer ) /** * Method writeReportPlugin. - * + * * @param reportPlugin * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeReportPlugin( ReportPlugin reportPlugin, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( reportPlugin.getGroupId() != null ) && !reportPlugin.getGroupId().equals( "org.apache.maven.plugins" ) ) - { - serializer.attribute( NAMESPACE, "groupId", reportPlugin.getGroupId() ); - } - if ( reportPlugin.getArtifactId() != null ) - { - serializer.attribute( NAMESPACE, "artifactId", reportPlugin.getArtifactId() ); - } - if ( reportPlugin.getVersion() != null ) - { - serializer.attribute( NAMESPACE, "version", reportPlugin.getVersion() ); - } - if ( reportPlugin.getInherited() != null ) - { - serializer.attribute( NAMESPACE, "inherited", reportPlugin.getInherited() ); - } - if ( ( reportPlugin.getReportSets() != null ) && ( reportPlugin.getReportSets().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "reportSets" ); - for ( Iterator iter = reportPlugin.getReportSets().iterator(); iter.hasNext(); ) - { + private void writeReportPlugin(ReportPlugin reportPlugin, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((reportPlugin.getGroupId() != null) && !reportPlugin.getGroupId().equals("org.apache.maven.plugins")) { + serializer.attribute(NAMESPACE, "groupId", reportPlugin.getGroupId()); + } + if (reportPlugin.getArtifactId() != null) { + serializer.attribute(NAMESPACE, "artifactId", reportPlugin.getArtifactId()); + } + if (reportPlugin.getVersion() != null) { + serializer.attribute(NAMESPACE, "version", reportPlugin.getVersion()); + } + if (reportPlugin.getInherited() != null) { + serializer.attribute(NAMESPACE, "inherited", reportPlugin.getInherited()); + } + if ((reportPlugin.getReportSets() != null) + && (reportPlugin.getReportSets().size() > 0)) { + serializer.startTag(NAMESPACE, "reportSets"); + for (Iterator iter = reportPlugin.getReportSets().iterator(); iter.hasNext(); ) { ReportSet o = (ReportSet) iter.next(); - writeReportSet( o, "reportSet", serializer ); + writeReportSet(o, "reportSet", serializer); } - serializer.endTag( NAMESPACE, "reportSets" ); + serializer.endTag(NAMESPACE, "reportSets"); } - if ( reportPlugin.getConfiguration() != null ) - { - ((Xpp3Dom) reportPlugin.getConfiguration()).writeToSerializer( NAMESPACE, serializer ); + if (reportPlugin.getConfiguration() != null) { + ((Xpp3Dom) reportPlugin.getConfiguration()).writeToSerializer(NAMESPACE, serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeReportPlugin( ReportPlugin, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeReportPlugin( ReportPlugin, String, XmlSerializer ) /** * Method writeReportSet. - * + * * @param reportSet * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeReportSet( ReportSet reportSet, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( ( reportSet.getId() != null ) && !reportSet.getId().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "id", reportSet.getId() ); - } - if ( reportSet.getInherited() != null ) - { - serializer.attribute( NAMESPACE, "inherited", reportSet.getInherited() ); - } - if ( ( reportSet.getReports() != null ) && ( reportSet.getReports().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "reports" ); - for ( Iterator iter = reportSet.getReports().iterator(); iter.hasNext(); ) - { + private void writeReportSet(ReportSet reportSet, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if ((reportSet.getId() != null) && !reportSet.getId().equals("default")) { + serializer.attribute(NAMESPACE, "id", reportSet.getId()); + } + if (reportSet.getInherited() != null) { + serializer.attribute(NAMESPACE, "inherited", reportSet.getInherited()); + } + if ((reportSet.getReports() != null) && (reportSet.getReports().size() > 0)) { + serializer.startTag(NAMESPACE, "reports"); + for (Iterator iter = reportSet.getReports().iterator(); iter.hasNext(); ) { String report = (String) iter.next(); - serializer.startTag( NAMESPACE, "report" ).text( report ).endTag( NAMESPACE, "report" ); + serializer.startTag(NAMESPACE, "report").text(report).endTag(NAMESPACE, "report"); } - serializer.endTag( NAMESPACE, "reports" ); + serializer.endTag(NAMESPACE, "reports"); } - if ( reportSet.getConfiguration() != null ) - { - ((Xpp3Dom) reportSet.getConfiguration()).writeToSerializer( NAMESPACE, serializer ); + if (reportSet.getConfiguration() != null) { + ((Xpp3Dom) reportSet.getConfiguration()).writeToSerializer(NAMESPACE, serializer); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeReportSet( ReportSet, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeReportSet( ReportSet, String, XmlSerializer ) /** * Method writeReporting. - * + * * @param reporting * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeReporting( Reporting reporting, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( reporting.getExcludeDefaults() != null ) - { - serializer.attribute( NAMESPACE, "excludeDefaults", reporting.getExcludeDefaults() ); - } - if ( reporting.getOutputDirectory() != null ) - { - serializer.attribute( NAMESPACE, "outputDirectory", reporting.getOutputDirectory() ); - } - if ( ( reporting.getPlugins() != null ) && ( reporting.getPlugins().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "plugins" ); - for ( Iterator iter = reporting.getPlugins().iterator(); iter.hasNext(); ) - { + private void writeReporting(Reporting reporting, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (reporting.getExcludeDefaults() != null) { + serializer.attribute(NAMESPACE, "excludeDefaults", reporting.getExcludeDefaults()); + } + if (reporting.getOutputDirectory() != null) { + serializer.attribute(NAMESPACE, "outputDirectory", reporting.getOutputDirectory()); + } + if ((reporting.getPlugins() != null) && (reporting.getPlugins().size() > 0)) { + serializer.startTag(NAMESPACE, "plugins"); + for (Iterator iter = reporting.getPlugins().iterator(); iter.hasNext(); ) { ReportPlugin o = (ReportPlugin) iter.next(); - writeReportPlugin( o, "plugin", serializer ); + writeReportPlugin(o, "plugin", serializer); } - serializer.endTag( NAMESPACE, "plugins" ); + serializer.endTag(NAMESPACE, "plugins"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeReporting( Reporting, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeReporting( Reporting, String, XmlSerializer ) /** * Method writeRepository. - * + * * @param repository * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeRepository( Repository repository, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( repository.getId() != null ) - { - serializer.attribute( NAMESPACE, "id", repository.getId() ); - } - if ( repository.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", repository.getName() ); - } - if ( repository.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", repository.getUrl() ); - } - if ( ( repository.getLayout() != null ) && !repository.getLayout().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "layout", repository.getLayout() ); - } - if ( repository.getReleases() != null ) - { - writeRepositoryPolicy( (RepositoryPolicy) repository.getReleases(), "releases", serializer ); - } - if ( repository.getSnapshots() != null ) - { - writeRepositoryPolicy( (RepositoryPolicy) repository.getSnapshots(), "snapshots", serializer ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeRepository( Repository, String, XmlSerializer ) + private void writeRepository(Repository repository, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (repository.getId() != null) { + serializer.attribute(NAMESPACE, "id", repository.getId()); + } + if (repository.getName() != null) { + serializer.attribute(NAMESPACE, "name", repository.getName()); + } + if (repository.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", repository.getUrl()); + } + if ((repository.getLayout() != null) && !repository.getLayout().equals("default")) { + serializer.attribute(NAMESPACE, "layout", repository.getLayout()); + } + if (repository.getReleases() != null) { + writeRepositoryPolicy((RepositoryPolicy) repository.getReleases(), "releases", serializer); + } + if (repository.getSnapshots() != null) { + writeRepositoryPolicy((RepositoryPolicy) repository.getSnapshots(), "snapshots", serializer); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeRepository( Repository, String, XmlSerializer ) /** * Method writeRepositoryBase. - * + * * @param repositoryBase * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeRepositoryBase( RepositoryBase repositoryBase, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( repositoryBase.getId() != null ) - { - serializer.attribute( NAMESPACE, "id", repositoryBase.getId() ); - } - if ( repositoryBase.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", repositoryBase.getName() ); - } - if ( repositoryBase.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", repositoryBase.getUrl() ); - } - if ( ( repositoryBase.getLayout() != null ) && !repositoryBase.getLayout().equals( "default" ) ) - { - serializer.attribute( NAMESPACE, "layout", repositoryBase.getLayout() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeRepositoryBase( RepositoryBase, String, XmlSerializer ) + private void writeRepositoryBase(RepositoryBase repositoryBase, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (repositoryBase.getId() != null) { + serializer.attribute(NAMESPACE, "id", repositoryBase.getId()); + } + if (repositoryBase.getName() != null) { + serializer.attribute(NAMESPACE, "name", repositoryBase.getName()); + } + if (repositoryBase.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", repositoryBase.getUrl()); + } + if ((repositoryBase.getLayout() != null) && !repositoryBase.getLayout().equals("default")) { + serializer.attribute(NAMESPACE, "layout", repositoryBase.getLayout()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeRepositoryBase( RepositoryBase, String, XmlSerializer ) /** * Method writeRepositoryPolicy. - * + * * @param repositoryPolicy * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeRepositoryPolicy( RepositoryPolicy repositoryPolicy, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( repositoryPolicy.getEnabled() != null ) - { - serializer.attribute( NAMESPACE, "enabled", repositoryPolicy.getEnabled() ); - } - if ( repositoryPolicy.getUpdatePolicy() != null ) - { - serializer.attribute( NAMESPACE, "updatePolicy", repositoryPolicy.getUpdatePolicy() ); - } - if ( repositoryPolicy.getChecksumPolicy() != null ) - { - serializer.attribute( NAMESPACE, "checksumPolicy", repositoryPolicy.getChecksumPolicy() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeRepositoryPolicy( RepositoryPolicy, String, XmlSerializer ) + private void writeRepositoryPolicy(RepositoryPolicy repositoryPolicy, String tagName, XmlSerializer serializer) + throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (repositoryPolicy.getEnabled() != null) { + serializer.attribute(NAMESPACE, "enabled", repositoryPolicy.getEnabled()); + } + if (repositoryPolicy.getUpdatePolicy() != null) { + serializer.attribute(NAMESPACE, "updatePolicy", repositoryPolicy.getUpdatePolicy()); + } + if (repositoryPolicy.getChecksumPolicy() != null) { + serializer.attribute(NAMESPACE, "checksumPolicy", repositoryPolicy.getChecksumPolicy()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeRepositoryPolicy( RepositoryPolicy, String, XmlSerializer ) /** * Method writeResource. - * + * * @param resource * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeResource( Resource resource, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( resource.getTargetPath() != null ) - { - serializer.attribute( NAMESPACE, "targetPath", resource.getTargetPath() ); - } - if ( resource.getFiltering() != null ) - { - serializer.attribute( NAMESPACE, "filtering", resource.getFiltering() ); - } - if ( resource.getDirectory() != null ) - { - serializer.attribute( NAMESPACE, "directory", resource.getDirectory() ); - } - if ( ( resource.getIncludes() != null ) && ( resource.getIncludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "includes" ); - for ( Iterator iter = resource.getIncludes().iterator(); iter.hasNext(); ) - { + private void writeResource(Resource resource, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (resource.getTargetPath() != null) { + serializer.attribute(NAMESPACE, "targetPath", resource.getTargetPath()); + } + if (resource.getFiltering() != null) { + serializer.attribute(NAMESPACE, "filtering", resource.getFiltering()); + } + if (resource.getDirectory() != null) { + serializer.attribute(NAMESPACE, "directory", resource.getDirectory()); + } + if ((resource.getIncludes() != null) && (resource.getIncludes().size() > 0)) { + serializer.startTag(NAMESPACE, "includes"); + for (Iterator iter = resource.getIncludes().iterator(); iter.hasNext(); ) { String include = (String) iter.next(); - serializer.startTag( NAMESPACE, "include" ).text( include ).endTag( NAMESPACE, "include" ); + serializer.startTag(NAMESPACE, "include").text(include).endTag(NAMESPACE, "include"); } - serializer.endTag( NAMESPACE, "includes" ); + serializer.endTag(NAMESPACE, "includes"); } - if ( ( resource.getExcludes() != null ) && ( resource.getExcludes().size() > 0 ) ) - { - serializer.startTag( NAMESPACE, "excludes" ); - for ( Iterator iter = resource.getExcludes().iterator(); iter.hasNext(); ) - { + if ((resource.getExcludes() != null) && (resource.getExcludes().size() > 0)) { + serializer.startTag(NAMESPACE, "excludes"); + for (Iterator iter = resource.getExcludes().iterator(); iter.hasNext(); ) { String exclude = (String) iter.next(); - serializer.startTag( NAMESPACE, "exclude" ).text( exclude ).endTag( NAMESPACE, "exclude" ); + serializer.startTag(NAMESPACE, "exclude").text(exclude).endTag(NAMESPACE, "exclude"); } - serializer.endTag( NAMESPACE, "excludes" ); + serializer.endTag(NAMESPACE, "excludes"); } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeResource( Resource, String, XmlSerializer ) + serializer.endTag(NAMESPACE, tagName); + } // -- void writeResource( Resource, String, XmlSerializer ) /** * Method writeScm. - * + * * @param scm * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeScm( Scm scm, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( scm.getConnection() != null ) - { - serializer.attribute( NAMESPACE, "connection", scm.getConnection() ); - } - if ( scm.getDeveloperConnection() != null ) - { - serializer.attribute( NAMESPACE, "developerConnection", scm.getDeveloperConnection() ); - } - if ( ( scm.getTag() != null ) && !scm.getTag().equals( "HEAD" ) ) - { - serializer.attribute( NAMESPACE, "tag", scm.getTag() ); - } - if ( scm.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", scm.getUrl() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeScm( Scm, String, XmlSerializer ) + private void writeScm(Scm scm, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (scm.getConnection() != null) { + serializer.attribute(NAMESPACE, "connection", scm.getConnection()); + } + if (scm.getDeveloperConnection() != null) { + serializer.attribute(NAMESPACE, "developerConnection", scm.getDeveloperConnection()); + } + if ((scm.getTag() != null) && !scm.getTag().equals("HEAD")) { + serializer.attribute(NAMESPACE, "tag", scm.getTag()); + } + if (scm.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", scm.getUrl()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeScm( Scm, String, XmlSerializer ) /** * Method writeSite. - * + * * @param site * @param serializer * @param tagName * @throws java.io.IOException */ - private void writeSite( Site site, String tagName, XmlSerializer serializer ) - throws java.io.IOException - { - serializer.startTag( NAMESPACE, tagName ); - if ( site.getId() != null ) - { - serializer.attribute( NAMESPACE, "id", site.getId() ); - } - if ( site.getName() != null ) - { - serializer.attribute( NAMESPACE, "name", site.getName() ); - } - if ( site.getUrl() != null ) - { - serializer.attribute( NAMESPACE, "url", site.getUrl() ); - } - serializer.endTag( NAMESPACE, tagName ); - } //-- void writeSite( Site, String, XmlSerializer ) - + private void writeSite(Site site, String tagName, XmlSerializer serializer) throws java.io.IOException { + serializer.startTag(NAMESPACE, tagName); + if (site.getId() != null) { + serializer.attribute(NAMESPACE, "id", site.getId()); + } + if (site.getName() != null) { + serializer.attribute(NAMESPACE, "name", site.getName()); + } + if (site.getUrl() != null) { + serializer.attribute(NAMESPACE, "url", site.getUrl()); + } + serializer.endTag(NAMESPACE, tagName); + } // -- void writeSite( Site, String, XmlSerializer ) } diff --git a/polyglot-xml/src/test/java/org/sonatype/maven/polyglot/xml/TestReaderComparedToDefault.java b/polyglot-xml/src/test/java/org/sonatype/maven/polyglot/xml/TestReaderComparedToDefault.java index 68c1fb6b..9dc741b0 100644 --- a/polyglot-xml/src/test/java/org/sonatype/maven/polyglot/xml/TestReaderComparedToDefault.java +++ b/polyglot-xml/src/test/java/org/sonatype/maven/polyglot/xml/TestReaderComparedToDefault.java @@ -1,57 +1,64 @@ package org.sonatype.maven.polyglot.xml; +import com.cedarsoftware.util.DeepEquals; import java.io.IOException; - import org.apache.maven.model.Model; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.junit.Assert; import org.junit.Test; -import com.cedarsoftware.util.DeepEquals; - public class TestReaderComparedToDefault { - private static final String POM_MAVEN_V_4 = "/pom/pom_maven_v4.xml"; - private static final String POM_MAVEN_V_4_1 = "/pom/pom_maven_v4_1.xml"; - - @Test - public void testModelEqualToReference() throws IOException, XmlPullParserException { - Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader().read(getClass().getResourceAsStream(POM_MAVEN_V_4)); - Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader().read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); - - Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); - } - - @Test - public void testModelEqualToReferenceByExample1() throws IOException, XmlPullParserException { - Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader().read(getClass().getResourceAsStream("/pom/pom_build_properties_v4.xml")); - Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader().read(getClass().getResourceAsStream("/pom/pom_build_properties_v4_1.xml")); - - Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); - } - - @Test - public void testModelEqualToReferenceByExample2() throws IOException, XmlPullParserException { - Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader().read(getClass().getResourceAsStream("/pom/pom_CiManagement_v4.xml")); - Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader().read(getClass().getResourceAsStream("/pom/pom_CiManagement_v4_1.xml")); - - Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); - } - - @Test - public void testAssertionIncludesDeepProperties() throws IOException, XmlPullParserException { - Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader().read(getClass().getResourceAsStream(POM_MAVEN_V_4)); - Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader().read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); - - modelV4.getDependencyManagement().getDependencies().get(3).setArtifactId("shouldFailtest"); - - Assert.assertFalse(DeepEquals.deepEquals(modelV4, modelV41)); - } - - @Test - public void testParsedDependencyManagement() throws IOException, XmlPullParserException { - Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader().read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); - - Assert.assertTrue(modelV41.getDependencyManagement().getDependencies().size() == 36); - } + private static final String POM_MAVEN_V_4 = "/pom/pom_maven_v4.xml"; + private static final String POM_MAVEN_V_4_1 = "/pom/pom_maven_v4_1.xml"; + + @Test + public void testModelEqualToReference() throws IOException, XmlPullParserException { + Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader() + .read(getClass().getResourceAsStream(POM_MAVEN_V_4)); + Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader() + .read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); + + Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); + } + + @Test + public void testModelEqualToReferenceByExample1() throws IOException, XmlPullParserException { + Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader() + .read(getClass().getResourceAsStream("/pom/pom_build_properties_v4.xml")); + Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader() + .read(getClass().getResourceAsStream("/pom/pom_build_properties_v4_1.xml")); + + Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); + } + + @Test + public void testModelEqualToReferenceByExample2() throws IOException, XmlPullParserException { + Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader() + .read(getClass().getResourceAsStream("/pom/pom_CiManagement_v4.xml")); + Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader() + .read(getClass().getResourceAsStream("/pom/pom_CiManagement_v4_1.xml")); + + Assert.assertTrue(DeepEquals.deepEquals(modelV4, modelV41)); + } + + @Test + public void testAssertionIncludesDeepProperties() throws IOException, XmlPullParserException { + Model modelV4 = new org.apache.maven.model.io.xpp3.MavenXpp3Reader() + .read(getClass().getResourceAsStream(POM_MAVEN_V_4)); + Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader() + .read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); + + modelV4.getDependencyManagement().getDependencies().get(3).setArtifactId("shouldFailtest"); + + Assert.assertFalse(DeepEquals.deepEquals(modelV4, modelV41)); + } + + @Test + public void testParsedDependencyManagement() throws IOException, XmlPullParserException { + Model modelV41 = new org.sonatype.maven.polyglot.xml.xpp3.PolyglotMavenXpp3Reader() + .read(getClass().getResourceAsStream(POM_MAVEN_V_4_1)); + + Assert.assertTrue(modelV41.getDependencyManagement().getDependencies().size() == 36); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructDependency.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructDependency.java index 3caa0ff1..2181f3d5 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructDependency.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructDependency.java @@ -7,46 +7,45 @@ */ package org.sonatype.maven.polyglot.yaml; +import java.util.regex.Matcher; import org.apache.maven.model.Dependency; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; -import java.util.regex.Matcher; - public class ConstructDependency extends AbstractConstruct { - @Override - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - return createDependency(scalar.getValue(), new Dependency()); - } + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + return createDependency(scalar.getValue(), new Dependency()); + } - public static Dependency createDependency(String scalar, Dependency dependency) { - Matcher matcher = ModelResolver.DEPENDENCY_PATTERN.matcher(scalar); - if (matcher.matches()) { - //scope and version are present - String version = matcher.group("version"); - dependency.setVersion(version); - String scope = matcher.group("scope"); - dependency.setScope(scope); - } else { - matcher = ModelResolver.COORDINATE_PATTERN.matcher(scalar); - //version is present - if (matcher.matches()) { - String version = matcher.group("version"); - dependency.setVersion(version); - } else { - matcher = ModelResolver.GROUP_NAME_PATTERN.matcher(scalar); - if (!matcher.matches()) { - throw new IllegalArgumentException("Unexpected node: " + scalar); + public static Dependency createDependency(String scalar, Dependency dependency) { + Matcher matcher = ModelResolver.DEPENDENCY_PATTERN.matcher(scalar); + if (matcher.matches()) { + // scope and version are present + String version = matcher.group("version"); + dependency.setVersion(version); + String scope = matcher.group("scope"); + dependency.setScope(scope); + } else { + matcher = ModelResolver.COORDINATE_PATTERN.matcher(scalar); + // version is present + if (matcher.matches()) { + String version = matcher.group("version"); + dependency.setVersion(version); + } else { + matcher = ModelResolver.GROUP_NAME_PATTERN.matcher(scalar); + if (!matcher.matches()) { + throw new IllegalArgumentException("Unexpected node: " + scalar); + } + } } - } + // groupId and artifactId are always present + String groupId = matcher.group("groupId"); + String artifactId = matcher.group("artifactId"); + dependency.setGroupId(groupId); + dependency.setArtifactId(artifactId); + return dependency; } - //groupId and artifactId are always present - String groupId = matcher.group("groupId"); - String artifactId = matcher.group("artifactId"); - dependency.setGroupId(groupId); - dependency.setArtifactId(artifactId); - return dependency; - } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructExtension.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructExtension.java index 3f416444..f306c6d7 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructExtension.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructExtension.java @@ -8,16 +8,15 @@ package org.sonatype.maven.polyglot.yaml; import org.apache.maven.model.Extension; -import org.apache.maven.model.Plugin; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; public class ConstructExtension extends AbstractConstruct { - @Override - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); - return coord.mergeExtension(new Extension()); - } + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); + return coord.mergeExtension(new Extension()); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructParent.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructParent.java index b3b20158..595f8f2a 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructParent.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructParent.java @@ -7,19 +7,16 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.Extension; import org.apache.maven.model.Parent; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; -import java.util.regex.Matcher; - public class ConstructParent extends AbstractConstruct { - @Override - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); - return coord.mergeParent(new Parent()); - } + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); + return coord.mergeParent(new Parent()); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructPlugin.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructPlugin.java index 11231b67..9933ec9b 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructPlugin.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructPlugin.java @@ -13,10 +13,10 @@ import org.yaml.snakeyaml.nodes.ScalarNode; public class ConstructPlugin extends AbstractConstruct { - @Override - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); - return coord.mergePlugin(new Plugin()); - } + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); + return coord.mergePlugin(new Plugin()); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructReportPlugin.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructReportPlugin.java index 689ac9ed..e5e253d1 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructReportPlugin.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ConstructReportPlugin.java @@ -7,17 +7,16 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.Dependency; import org.apache.maven.model.ReportPlugin; import org.yaml.snakeyaml.constructor.AbstractConstruct; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; public class ConstructReportPlugin extends AbstractConstruct { - @Override - public Object construct(Node node) { - ScalarNode scalar = (ScalarNode) node; - Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); - return coord.mergeReportPlugin(new ReportPlugin()); - } + @Override + public Object construct(Node node) { + ScalarNode scalar = (ScalarNode) node; + Coordinate coord = Coordinate.createCoordinate(scalar.getValue()); + return coord.mergeReportPlugin(new ReportPlugin()); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/Coordinate.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/Coordinate.java index 8260aee3..fb004e7b 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/Coordinate.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/Coordinate.java @@ -7,78 +7,77 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.*; - import java.util.regex.Matcher; +import org.apache.maven.model.*; public class Coordinate { - private String groupId; - private String artifactId; - private String version; + private String groupId; + private String artifactId; + private String version; - public Coordinate(String groupId, String artifactId, String version) { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - } + public Coordinate(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public String getArtifactId() { - return artifactId; - } + public String getArtifactId() { + return artifactId; + } - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public static Coordinate createCoordinate(String scalar) { - Matcher matcher = ModelResolver.COORDINATE_PATTERN.matcher(scalar); - if (matcher.matches()) { - return new Coordinate(matcher.group("groupId"), matcher.group("artifactId"), matcher.group("version")); - } else { - matcher = ModelResolver.GROUP_NAME_PATTERN.matcher(scalar); - if (!matcher.matches()) { - throw new IllegalArgumentException("Unexpected node: " + scalar); - } - return new Coordinate(matcher.group("groupId"), matcher.group("artifactId"), null); + public static Coordinate createCoordinate(String scalar) { + Matcher matcher = ModelResolver.COORDINATE_PATTERN.matcher(scalar); + if (matcher.matches()) { + return new Coordinate(matcher.group("groupId"), matcher.group("artifactId"), matcher.group("version")); + } else { + matcher = ModelResolver.GROUP_NAME_PATTERN.matcher(scalar); + if (!matcher.matches()) { + throw new IllegalArgumentException("Unexpected node: " + scalar); + } + return new Coordinate(matcher.group("groupId"), matcher.group("artifactId"), null); + } } - } - public Model mergeModel(Model model) { - model.setGroupId(groupId); - model.setArtifactId(artifactId); - if(version != null) model.setVersion(version); - return model; - } + public Model mergeModel(Model model) { + model.setGroupId(groupId); + model.setArtifactId(artifactId); + if (version != null) model.setVersion(version); + return model; + } - public Plugin mergePlugin(Plugin plugin) { - plugin.setGroupId(groupId); - plugin.setArtifactId(artifactId); - if(version != null) plugin.setVersion(version); - return plugin; - } + public Plugin mergePlugin(Plugin plugin) { + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + if (version != null) plugin.setVersion(version); + return plugin; + } - public ReportPlugin mergeReportPlugin(ReportPlugin plugin) { - plugin.setGroupId(groupId); - plugin.setArtifactId(artifactId); - if(version != null) plugin.setVersion(version); - return plugin; - } + public ReportPlugin mergeReportPlugin(ReportPlugin plugin) { + plugin.setGroupId(groupId); + plugin.setArtifactId(artifactId); + if (version != null) plugin.setVersion(version); + return plugin; + } - public Extension mergeExtension(Extension extension) { - extension.setGroupId(groupId); - extension.setArtifactId(artifactId); - if(version != null) extension.setVersion(version); - return extension; - } + public Extension mergeExtension(Extension extension) { + extension.setGroupId(groupId); + extension.setArtifactId(artifactId); + if (version != null) extension.setVersion(version); + return extension; + } - public Parent mergeParent(Parent parent) { - parent.setGroupId(groupId); - parent.setArtifactId(artifactId); - if(version != null) parent.setVersion(version); - return parent; - } + public Parent mergeParent(Parent parent) { + parent.setGroupId(groupId); + parent.setArtifactId(artifactId); + if (version != null) parent.setVersion(version); + return parent; + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelConstructor.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelConstructor.java index 536d9ccc..bef6c314 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelConstructor.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelConstructor.java @@ -7,6 +7,12 @@ */ package org.sonatype.maven.polyglot.yaml; +import static java.lang.String.format; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.maven.model.*; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.yaml.snakeyaml.LoaderOptions; @@ -16,13 +22,6 @@ import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.*; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static java.lang.String.format; - /** * YAML model constructor. * @@ -33,279 +32,280 @@ */ public final class ModelConstructor extends Constructor { - private static final Tag XPP3DOM_TAG = new Tag("!!" + Xpp3Dom.class.getName()); - - /** - * It maps the runtime class to its Construct implementation. - */ - private final Map, Construct> pomConstructors = new HashMap<>(); - - public ModelConstructor(LoaderOptions loadingConfig) { - super(Model.class, loadingConfig); - - yamlConstructors.put(XPP3DOM_TAG, new ConstructXpp3Dom()); - yamlClassConstructors.put(NodeId.mapping, new MavenObjectConstruct()); - pomConstructors.put(Dependency.class, new ConstructDependency()); - pomConstructors.put(Parent.class, new ConstructParent()); - pomConstructors.put(Extension.class, new ConstructExtension()); - pomConstructors.put(Plugin.class, new ConstructPlugin()); - pomConstructors.put(ReportPlugin.class, new ConstructReportPlugin()); - - TypeDescription desc; - - desc = new TypeDescription(Model.class); - desc.putListPropertyType("licenses", License.class); - desc.putListPropertyType("mailingLists", MailingList.class); - desc.putListPropertyType("dependencies", Dependency.class); - desc.putListPropertyType("modules", String.class); - desc.putListPropertyType("profiles", Profile.class); - desc.putListPropertyType("repositories", Repository.class); - desc.putListPropertyType("pluginRepositories", Repository.class); - desc.putListPropertyType("developers", Developer.class); - desc.putListPropertyType("contributors", Contributor.class); - addTypeDescription(desc); - - desc = new TypeDescription(Dependency.class); - desc.putListPropertyType("exclusions", Exclusion.class); - addTypeDescription(desc); - - desc = new TypeDescription(DependencyManagement.class); - desc.putListPropertyType("dependencies", Dependency.class); - addTypeDescription(desc); - - desc = new TypeDescription(Build.class); - desc.putListPropertyType("extensions", Extension.class); - desc.putListPropertyType("resources", Resource.class); - desc.putListPropertyType("testResources", Resource.class); - desc.putListPropertyType("filters", String.class); - desc.putListPropertyType("plugins", Plugin.class); - addTypeDescription(desc); - - desc = new TypeDescription(BuildBase.class); - desc.putListPropertyType("resources", Resource.class); - desc.putListPropertyType("testResources", Resource.class); - desc.putListPropertyType("filters", String.class); - desc.putListPropertyType("plugins", Plugin.class); - addTypeDescription(desc); - - desc = new TypeDescription(PluginManagement.class); - desc.putListPropertyType("plugins", Plugin.class); - addTypeDescription(desc); - - desc = new TypeDescription(Plugin.class); - desc.putListPropertyType("executions", PluginExecution.class); - addTypeDescription(desc); - - desc = new TypeDescription(PluginExecution.class); - desc.putListPropertyType("goals", String.class); - addTypeDescription(desc); - - desc = new TypeDescription(Reporting.class); - desc.putListPropertyType("plugins", ReportPlugin.class); - addTypeDescription(desc); - - desc = new TypeDescription(ReportPlugin.class); - desc.putListPropertyType("reportSets", ReportSet.class); - addTypeDescription(desc); - - desc = new TypeDescription(ReportSet.class); - desc.putListPropertyType("reports", String.class); - addTypeDescription(desc); - - desc = new TypeDescription(CiManagement.class); - desc.putListPropertyType("notifiers", Notifier.class); - addTypeDescription(desc); - - desc = new TypeDescription(Developer.class); - desc.putListPropertyType("roles", String.class); - addTypeDescription(desc); - - desc = new TypeDescription(Contributor.class); - desc.putListPropertyType("roles", String.class); - addTypeDescription(desc); - - desc = new TypeDescription(MailingList.class); - desc.putListPropertyType("otherArchives", String.class); - addTypeDescription(desc); - - // Simple types - addTypeDescription(new TypeDescription(DistributionManagement.class)); - addTypeDescription(new TypeDescription(Scm.class)); - addTypeDescription(new TypeDescription(IssueManagement.class)); - addTypeDescription(new TypeDescription(Parent.class)); - addTypeDescription(new TypeDescription(Organization.class)); - } - - @Override - protected Construct getConstructor(Node node) { - if (pomConstructors.containsKey(node.getType()) && node instanceof ScalarNode) { - //construct compact form from scalar - return pomConstructors.get(node.getType()); - } else { - return super.getConstructor(node); + private static final Tag XPP3DOM_TAG = new Tag("!!" + Xpp3Dom.class.getName()); + + /** + * It maps the runtime class to its Construct implementation. + */ + private final Map, Construct> pomConstructors = new HashMap<>(); + + public ModelConstructor(LoaderOptions loadingConfig) { + super(Model.class, loadingConfig); + + yamlConstructors.put(XPP3DOM_TAG, new ConstructXpp3Dom()); + yamlClassConstructors.put(NodeId.mapping, new MavenObjectConstruct()); + pomConstructors.put(Dependency.class, new ConstructDependency()); + pomConstructors.put(Parent.class, new ConstructParent()); + pomConstructors.put(Extension.class, new ConstructExtension()); + pomConstructors.put(Plugin.class, new ConstructPlugin()); + pomConstructors.put(ReportPlugin.class, new ConstructReportPlugin()); + + TypeDescription desc; + + desc = new TypeDescription(Model.class); + desc.putListPropertyType("licenses", License.class); + desc.putListPropertyType("mailingLists", MailingList.class); + desc.putListPropertyType("dependencies", Dependency.class); + desc.putListPropertyType("modules", String.class); + desc.putListPropertyType("profiles", Profile.class); + desc.putListPropertyType("repositories", Repository.class); + desc.putListPropertyType("pluginRepositories", Repository.class); + desc.putListPropertyType("developers", Developer.class); + desc.putListPropertyType("contributors", Contributor.class); + addTypeDescription(desc); + + desc = new TypeDescription(Dependency.class); + desc.putListPropertyType("exclusions", Exclusion.class); + addTypeDescription(desc); + + desc = new TypeDescription(DependencyManagement.class); + desc.putListPropertyType("dependencies", Dependency.class); + addTypeDescription(desc); + + desc = new TypeDescription(Build.class); + desc.putListPropertyType("extensions", Extension.class); + desc.putListPropertyType("resources", Resource.class); + desc.putListPropertyType("testResources", Resource.class); + desc.putListPropertyType("filters", String.class); + desc.putListPropertyType("plugins", Plugin.class); + addTypeDescription(desc); + + desc = new TypeDescription(BuildBase.class); + desc.putListPropertyType("resources", Resource.class); + desc.putListPropertyType("testResources", Resource.class); + desc.putListPropertyType("filters", String.class); + desc.putListPropertyType("plugins", Plugin.class); + addTypeDescription(desc); + + desc = new TypeDescription(PluginManagement.class); + desc.putListPropertyType("plugins", Plugin.class); + addTypeDescription(desc); + + desc = new TypeDescription(Plugin.class); + desc.putListPropertyType("executions", PluginExecution.class); + addTypeDescription(desc); + + desc = new TypeDescription(PluginExecution.class); + desc.putListPropertyType("goals", String.class); + addTypeDescription(desc); + + desc = new TypeDescription(Reporting.class); + desc.putListPropertyType("plugins", ReportPlugin.class); + addTypeDescription(desc); + + desc = new TypeDescription(ReportPlugin.class); + desc.putListPropertyType("reportSets", ReportSet.class); + addTypeDescription(desc); + + desc = new TypeDescription(ReportSet.class); + desc.putListPropertyType("reports", String.class); + addTypeDescription(desc); + + desc = new TypeDescription(CiManagement.class); + desc.putListPropertyType("notifiers", Notifier.class); + addTypeDescription(desc); + + desc = new TypeDescription(Developer.class); + desc.putListPropertyType("roles", String.class); + addTypeDescription(desc); + + desc = new TypeDescription(Contributor.class); + desc.putListPropertyType("roles", String.class); + addTypeDescription(desc); + + desc = new TypeDescription(MailingList.class); + desc.putListPropertyType("otherArchives", String.class); + addTypeDescription(desc); + + // Simple types + addTypeDescription(new TypeDescription(DistributionManagement.class)); + addTypeDescription(new TypeDescription(Scm.class)); + addTypeDescription(new TypeDescription(IssueManagement.class)); + addTypeDescription(new TypeDescription(Parent.class)); + addTypeDescription(new TypeDescription(Organization.class)); } - } - - private class ConstructXpp3Dom implements Construct { - private static final String ATTRIBUTE_PREFIX = "attr/"; - - private Xpp3Dom toDom(Xpp3Dom parent, Map map) { - - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey().toString(); - Object entryValue = entry.getValue(); - Xpp3Dom child = new Xpp3Dom(key); - - if (key.startsWith(ATTRIBUTE_PREFIX)) { - toAttribute(parent, key.replace(ATTRIBUTE_PREFIX, ""), entryValue); - continue; - } - // lists need the insertion of intermediate XML DOM nodes which hold the actual values - if (entryValue instanceof List && !((List) entryValue).isEmpty()) { - toDom(child, key, (List) entryValue); - } else if (entryValue instanceof Map) { - //noinspection unchecked - child = toDom(child, (Map) entryValue); - } else { // if not a list or map then copy the string value - child.setValue(entryValue.toString()); + @Override + protected Construct getConstructor(Node node) { + if (pomConstructors.containsKey(node.getType()) && node instanceof ScalarNode) { + // construct compact form from scalar + return pomConstructors.get(node.getType()); + } else { + return super.getConstructor(node); } - parent.addChild(child); - } - return parent; } - private void toDom(Xpp3Dom parent, String parentKey, List list) { - Object firstItem = list.get(0); - - String childKey; - - // deal with YAML explicit pairs which are mapped to Object[] by SnakeYAML - if (firstItem.getClass().isArray()) { - for (Object item : list) { - Object[] pair = (Object[]) item; - childKey = "" + pair[0]; - Xpp3Dom itemNode = new Xpp3Dom(childKey); - if (pair[1] != null && pair[1] instanceof Map) - //noinspection unchecked - toDom(itemNode, (Map) pair[1]); - else - itemNode.setValue("" + pair[1]); - parent.addChild(itemNode); - } - } else { // automagically determine the node's child key using the collection node's name - if (!parentKey.endsWith("s")) { - throw new RuntimeException(format("collection key '%s' does not end in 's'. Please resort to the " + - "documentation on how to use explicit pairs for specifying child node names", parentKey)); + private class ConstructXpp3Dom implements Construct { + private static final String ATTRIBUTE_PREFIX = "attr/"; + + private Xpp3Dom toDom(Xpp3Dom parent, Map map) { + + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey().toString(); + Object entryValue = entry.getValue(); + Xpp3Dom child = new Xpp3Dom(key); + + if (key.startsWith(ATTRIBUTE_PREFIX)) { + toAttribute(parent, key.replace(ATTRIBUTE_PREFIX, ""), entryValue); + continue; + } + + // lists need the insertion of intermediate XML DOM nodes which hold the actual values + if (entryValue instanceof List && !((List) entryValue).isEmpty()) { + toDom(child, key, (List) entryValue); + } else if (entryValue instanceof Map) { + //noinspection unchecked + child = toDom(child, (Map) entryValue); + } else { // if not a list or map then copy the string value + child.setValue(entryValue.toString()); + } + parent.addChild(child); + } + return parent; } - if ("reportPlugins".equals(parentKey)) { - childKey = "plugin"; - } else { - childKey = parentKey.substring(0, parentKey.length() - 1); - if (childKey.endsWith("ie")) { - childKey = childKey.substring(0, childKey.length() - 2) + "y"; - } + private void toDom(Xpp3Dom parent, String parentKey, List list) { + Object firstItem = list.get(0); + + String childKey; + + // deal with YAML explicit pairs which are mapped to Object[] by SnakeYAML + if (firstItem.getClass().isArray()) { + for (Object item : list) { + Object[] pair = (Object[]) item; + childKey = "" + pair[0]; + Xpp3Dom itemNode = new Xpp3Dom(childKey); + if (pair[1] != null && pair[1] instanceof Map) + //noinspection unchecked + toDom(itemNode, (Map) pair[1]); + else itemNode.setValue("" + pair[1]); + parent.addChild(itemNode); + } + } else { // automagically determine the node's child key using the collection node's name + if (!parentKey.endsWith("s")) { + throw new RuntimeException(format( + "collection key '%s' does not end in 's'. Please resort to the " + + "documentation on how to use explicit pairs for specifying child node names", + parentKey)); + } + + if ("reportPlugins".equals(parentKey)) { + childKey = "plugin"; + } else { + childKey = parentKey.substring(0, parentKey.length() - 1); + if (childKey.endsWith("ie")) { + childKey = childKey.substring(0, childKey.length() - 2) + "y"; + } + } + + for (Object item : list) { + Xpp3Dom itemNode = new Xpp3Dom(childKey); + if (item instanceof Map) + //noinspection unchecked + toDom(itemNode, (Map) item); + else itemNode.setValue(item.toString()); + parent.addChild(itemNode); + } + } } - for (Object item : list) { - Xpp3Dom itemNode = new Xpp3Dom(childKey); - if (item instanceof Map) - //noinspection unchecked - toDom(itemNode, (Map) item); - else - itemNode.setValue(item.toString()); - parent.addChild(itemNode); - } - } - } + private void toAttribute(Xpp3Dom parent, String key, Object value) { + if (value instanceof List || value instanceof Map) { + throw new YAMLException("Attribute's value has to be a plain string. Node: " + parent); + } - private void toAttribute(Xpp3Dom parent, String key, Object value) { - if (value instanceof List || value instanceof Map) { - throw new YAMLException("Attribute's value has to be a plain string. Node: " + parent); - } - - parent.setAttribute(key, value.toString()); - } + parent.setAttribute(key, value.toString()); + } - public Object construct(Node node) { - Map mapping = constructMapping((MappingNode) node); - Xpp3Dom parent = new Xpp3Dom("configuration"); - return toDom(parent, mapping); - } + public Object construct(Node node) { + Map mapping = constructMapping((MappingNode) node); + Xpp3Dom parent = new Xpp3Dom("configuration"); + return toDom(parent, mapping); + } - public void construct2ndStep(Node node, Object object) { - throw new YAMLException("Unexpected recursive mapping structure. Node: " + node); + public void construct2ndStep(Node node, Object object) { + throw new YAMLException("Unexpected recursive mapping structure. Node: " + node); + } } - } - class MavenObjectConstruct extends Constructor.ConstructMapping { - @Override - protected Object constructJavaBean2ndStep(MappingNode node, Object object) { - Class type = node.getType(); - - List specialCases = Arrays.asList(Dependency.class, Model.class, Plugin.class, ReportPlugin.class); - List configurationContainers = Arrays.asList(Plugin.class, PluginExecution.class, - ReportPlugin.class, ReportSet.class); - - if (configurationContainers.contains(type)) { - for (NodeTuple valueNode : node.getValue()) { - Node keyNode = valueNode.getKeyNode(); - Node childValueNode = valueNode.getValueNode(); - if (keyNode instanceof ScalarNode && "configuration".equals(((ScalarNode) keyNode).getValue())) { - childValueNode.setTag(XPP3DOM_TAG); - } + class MavenObjectConstruct extends Constructor.ConstructMapping { + @Override + protected Object constructJavaBean2ndStep(MappingNode node, Object object) { + Class type = node.getType(); + + List specialCases = + Arrays.asList(Dependency.class, Model.class, Plugin.class, ReportPlugin.class); + List configurationContainers = + Arrays.asList(Plugin.class, PluginExecution.class, ReportPlugin.class, ReportSet.class); + + if (configurationContainers.contains(type)) { + for (NodeTuple valueNode : node.getValue()) { + Node keyNode = valueNode.getKeyNode(); + Node childValueNode = valueNode.getValueNode(); + if (keyNode instanceof ScalarNode && "configuration".equals(((ScalarNode) keyNode).getValue())) { + childValueNode.setTag(XPP3DOM_TAG); + } + } + } + + if (specialCases.contains(type)) { + String coordinate = removeId(node); + if (coordinate == null) { + return super.constructJavaBean2ndStep(node, object); + } + if (type.equals(Dependency.class)) { + Dependency dep = (Dependency) super.constructJavaBean2ndStep(node, object); + return ConstructDependency.createDependency(coordinate, dep); + } else if (type.equals(Model.class)) { + Coordinate coord = Coordinate.createCoordinate(coordinate); + Model model = (Model) super.constructJavaBean2ndStep(node, object); + return coord.mergeModel(model); + } else if (type.equals(Plugin.class)) { + Coordinate coord = Coordinate.createCoordinate(coordinate); + Plugin plugin = (Plugin) super.constructJavaBean2ndStep(node, object); + return coord.mergePlugin(plugin); + } else if (type.equals(ReportPlugin.class)) { + Coordinate coord = Coordinate.createCoordinate(coordinate); + ReportPlugin plugin = (ReportPlugin) super.constructJavaBean2ndStep(node, object); + return coord.mergeReportPlugin(plugin); + } + } + // create JavaBean + return super.constructJavaBean2ndStep(node, object); } - } + } - if (specialCases.contains(type)) { - String coordinate = removeId(node); - if (coordinate == null) { - return super.constructJavaBean2ndStep(node, object); + /** + * Dirty hack - remove 'id' if it is present. + * + * @param node - the node to remove the coordinate from + * @return removed coordinate if it was removed + */ + private String removeId(MappingNode node) { + NodeTuple id = null; + String scalar = null; + for (NodeTuple tuple : node.getValue()) { + ScalarNode keyNode = (ScalarNode) tuple.getKeyNode(); + String key = keyNode.getValue(); + if ("id".equals(key)) { + id = tuple; + ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); + scalar = valueNode.getValue(); + } } - if (type.equals(Dependency.class)) { - Dependency dep = (Dependency) super.constructJavaBean2ndStep(node, object); - return ConstructDependency.createDependency(coordinate, dep); - } else if (type.equals(Model.class)) { - Coordinate coord = Coordinate.createCoordinate(coordinate); - Model model = (Model) super.constructJavaBean2ndStep(node, object); - return coord.mergeModel(model); - } else if (type.equals(Plugin.class)) { - Coordinate coord = Coordinate.createCoordinate(coordinate); - Plugin plugin = (Plugin) super.constructJavaBean2ndStep(node, object); - return coord.mergePlugin(plugin); - } else if (type.equals(ReportPlugin.class)) { - Coordinate coord = Coordinate.createCoordinate(coordinate); - ReportPlugin plugin = (ReportPlugin) super.constructJavaBean2ndStep(node, object); - return coord.mergeReportPlugin(plugin); + if (id != null) { + node.getValue().remove(id); } - } - // create JavaBean - return super.constructJavaBean2ndStep(node, object); - } - } - - /** - * Dirty hack - remove 'id' if it is present. - * - * @param node - the node to remove the coordinate from - * @return removed coordinate if it was removed - */ - private String removeId(MappingNode node) { - NodeTuple id = null; - String scalar = null; - for (NodeTuple tuple : node.getValue()) { - ScalarNode keyNode = (ScalarNode) tuple.getKeyNode(); - String key = keyNode.getValue(); - if ("id".equals(key)) { - id = tuple; - ScalarNode valueNode = (ScalarNode) tuple.getValueNode(); - scalar = valueNode.getValue(); - } - } - if (id != null) { - node.getValue().remove(id); + return scalar; } - return scalar; - } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelRepresenter.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelRepresenter.java index 43c2a8d9..7e4cc6e9 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelRepresenter.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelRepresenter.java @@ -7,14 +7,18 @@ */ package org.sonatype.maven.polyglot.yaml; +import static java.lang.String.format; + +import java.beans.IntrospectionException; +import java.util.*; import org.apache.maven.model.Contributor; import org.apache.maven.model.Dependency; import org.apache.maven.model.Developer; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeTuple; @@ -22,11 +26,6 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import java.beans.IntrospectionException; -import java.util.*; - -import static java.lang.String.format; - /** * YAML model representer. * @@ -35,242 +34,237 @@ * @since 0.7 */ class ModelRepresenter extends Representer { - public ModelRepresenter(DumperOptions options) { - super(options); - this.representers.put(Xpp3Dom.class, new RepresentXpp3Dom()); - Represent stringRepresenter = this.representers.get(String.class); - this.representers.put(Boolean.class, stringRepresenter); - this.multiRepresenters.put(Number.class, stringRepresenter); - this.multiRepresenters.put(Date.class, stringRepresenter); - this.multiRepresenters.put(Enum.class, stringRepresenter); - this.multiRepresenters.put(Calendar.class, stringRepresenter); - } - - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, - Object propertyValue, Tag customTag) { - if (property != null && property.getName().equals("pomFile")) { - // "pomFile" is not a part of POM http://maven.apache.org/xsd/maven-4.0.0.xsd - return null; + public ModelRepresenter(DumperOptions options) { + super(options); + this.representers.put(Xpp3Dom.class, new RepresentXpp3Dom()); + Represent stringRepresenter = this.representers.get(String.class); + this.representers.put(Boolean.class, stringRepresenter); + this.multiRepresenters.put(Number.class, stringRepresenter); + this.multiRepresenters.put(Date.class, stringRepresenter); + this.multiRepresenters.put(Enum.class, stringRepresenter); + this.multiRepresenters.put(Calendar.class, stringRepresenter); } - if (propertyValue == null) return null; - if (propertyValue instanceof Map) { - Map map = (Map) propertyValue; - if (map.isEmpty()) return null; - } - if (propertyValue instanceof List) { - List map = (List) propertyValue; - if (map.isEmpty()) return null; - } - if (javaBean instanceof Dependency) { - //skip optional if it is false - if (skipBoolean(property, "optional", propertyValue, false)) return null; - //skip type if it is jar - if (skipString(property, "type", propertyValue, "jar")) return null; - } - if (javaBean instanceof Plugin) { - //skip extensions if it is false - if (skipBoolean(property, "extensions", propertyValue, false)) return null; - //skip inherited if it is true - if (skipBoolean(property, "inherited", propertyValue, true)) return null; + protected NodeTuple representJavaBeanProperty( + Object javaBean, Property property, Object propertyValue, Tag customTag) { + if (property != null && property.getName().equals("pomFile")) { + // "pomFile" is not a part of POM http://maven.apache.org/xsd/maven-4.0.0.xsd + return null; + } + + if (propertyValue == null) return null; + if (propertyValue instanceof Map) { + Map map = (Map) propertyValue; + if (map.isEmpty()) return null; + } + if (propertyValue instanceof List) { + List map = (List) propertyValue; + if (map.isEmpty()) return null; + } + if (javaBean instanceof Dependency) { + // skip optional if it is false + if (skipBoolean(property, "optional", propertyValue, false)) return null; + // skip type if it is jar + if (skipString(property, "type", propertyValue, "jar")) return null; + } + if (javaBean instanceof Plugin) { + // skip extensions if it is false + if (skipBoolean(property, "extensions", propertyValue, false)) return null; + // skip inherited if it is true + if (skipBoolean(property, "inherited", propertyValue, true)) return null; + } + return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); } - return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - } - private boolean skipString(Property property, String name, Object propertyValue, String value) { - if (name.equals(property.getName())) { - String v = (String) propertyValue; - return (value.equals(v)); + private boolean skipString(Property property, String name, Object propertyValue, String value) { + if (name.equals(property.getName())) { + String v = (String) propertyValue; + return (value.equals(v)); + } + return false; } - return false; - } - private boolean skipBoolean(Property property, String name, Object propertyValue, boolean value) { - if (name.equals(property.getName())) { - Boolean v = (Boolean) propertyValue; - return (v.equals(value)); + private boolean skipBoolean(Property property, String name, Object propertyValue, boolean value) { + if (name.equals(property.getName())) { + Boolean v = (Boolean) propertyValue; + return (v.equals(value)); + } + return false; } - return false; - } + private class RepresentXpp3Dom implements Represent { + private static final String ATTRIBUTE_PREFIX = "attr/"; - private class RepresentXpp3Dom implements Represent { - private static final String ATTRIBUTE_PREFIX = "attr/"; + public Node representData(Object data) { + return representMapping(Tag.MAP, toMap((Xpp3Dom) data), DumperOptions.FlowStyle.AUTO); + } - public Node representData(Object data) { - return representMapping(Tag.MAP, toMap((Xpp3Dom) data), DumperOptions.FlowStyle.AUTO); - } + private Map toMap(Xpp3Dom node) { + Map map = new LinkedHashMap<>(); - private Map toMap(Xpp3Dom node) { - Map map = new LinkedHashMap<>(); + int n = node.getChildCount(); + for (int i = 0; i < n; i++) { + Xpp3Dom child = node.getChild(i); + String childName = child.getName(); - int n = node.getChildCount(); - for (int i = 0; i < n; i++) { - Xpp3Dom child = node.getChild(i); - String childName = child.getName(); + String singularName = null; + int childNameLength = childName.length(); + if ("reportPlugins".equals(childName)) { + singularName = "plugin"; + } else if (childNameLength > 3 && childName.endsWith("ies")) { + singularName = childName.substring(0, childNameLength - 3); + } else if (childNameLength > 1 && childName.endsWith("s")) { + singularName = childName.substring(0, childNameLength - 1); + } - String singularName = null; - int childNameLength = childName.length(); - if ("reportPlugins".equals(childName)) { - singularName = "plugin"; - } else if (childNameLength > 3 && childName.endsWith("ies")) { - singularName = childName.substring(0, childNameLength - 3); - } else if (childNameLength > 1 && childName.endsWith("s")) { - singularName = childName.substring(0, childNameLength - 1); - } + Object childValue = child.getValue(); + if (childValue == null) { + boolean isList = singularName != null; + if (isList) { // check for eventual list construction + for (int j = 0, grandChildCount = child.getChildCount(); j < grandChildCount; j++) { + String grandChildName = child.getChild(j).getName(); + isList &= grandChildName.equals(singularName); + } + } + if (isList) { + childValue = toList(child, singularName); + } else { + childValue = toMap(child); + } + } + map.put(childName, childValue); + } - Object childValue = child.getValue(); - if (childValue == null) { - boolean isList = singularName != null; - if (isList) { // check for eventual list construction - for (int j = 0, grandChildCount = child.getChildCount(); j < grandChildCount; j++) { - String grandChildName = child.getChild(j).getName(); - isList &= grandChildName.equals(singularName); + for (String attrName : node.getAttributeNames()) { + map.put(ATTRIBUTE_PREFIX + attrName, node.getAttribute(attrName)); } - } - if (isList) { - childValue = toList(child, singularName); - } else { - childValue = toMap(child); - } - } - map.put(childName, childValue); - } - for (String attrName : node.getAttributeNames()) { - map.put(ATTRIBUTE_PREFIX + attrName, node.getAttribute(attrName)); - } + return map; + } - return map; - } + private List toList(Xpp3Dom node, String childName) { + List list = new ArrayList<>(); - private List toList(Xpp3Dom node, String childName) { - List list = new ArrayList<>(); + int n = node.getChildCount(); + for (int i = 0; i < n; i++) { + Xpp3Dom child = node.getChild(i); - int n = node.getChildCount(); - for (int i = 0; i < n; i++) { - Xpp3Dom child = node.getChild(i); + if (!childName.equals(child.getName())) { + throw new YAMLException(format( + "child name: '%s' does not match expected name: '%s' at node %s", + child.getName(), childName, node)); + } - if (!childName.equals(child.getName())) { - throw new YAMLException(format("child name: '%s' does not match expected name: '%s' at node %s", - child.getName(), childName, node)); - } + Object childValue = child.getValue(); + if (childValue == null) { + childValue = toMap(child); + } + list.add(childValue); + } - Object childValue = child.getValue(); - if (childValue == null) { - childValue = toMap(child); + return list; } - list.add(childValue); - } - - return list; } - } - // Model elements order { - //TODO move to polyglot-common, or to org.apache.maven:maven-model - private static List ORDER_MODEL = new ArrayList(Arrays.asList( - "modelEncoding", - "modelVersion", - "parent", - "groupId", - "artifactId", - "version", - "packaging", + // Model elements order { + // TODO move to polyglot-common, or to org.apache.maven:maven-model + private static List ORDER_MODEL = new ArrayList(Arrays.asList( + "modelEncoding", + "modelVersion", + "parent", + "groupId", + "artifactId", + "version", + "packaging", + "name", + "description", + "url", + "inceptionYear", + "organization", + "licenses", + "developers", + "contributers", + "mailingLists", + "scm", + "issueManagement", + "ciManagement", + "properties", + "prerequisites", + "modules", + "dependencyManagement", + "dependencies", + "distributionManagement", + // "repositories", + // "pluginRepositories", + "build", + "profiles", + "reporting")); + private static List ORDER_DEVELOPER = new ArrayList(Arrays.asList("name", "id", "email")); + private static List ORDER_CONTRIBUTOR = new ArrayList(Arrays.asList("name", "id", "email")); + private static List ORDER_DEPENDENCY = + new ArrayList(Arrays.asList("groupId", "artifactId", "version", "type", "classifier", "scope")); + private static List ORDER_PLUGIN = new ArrayList( + Arrays.asList("groupId", "artifactId", "version", "inherited", "extensions", "configuration")); + // } - "name", - "description", - "url", - "inceptionYear", - "organization", - "licenses", - "developers", - "contributers", - "mailingLists", - "scm", - "issueManagement", - "ciManagement", - - "properties", - "prerequisites", - "modules", - "dependencyManagement", - "dependencies", - "distributionManagement", - //"repositories", - //"pluginRepositories", - "build", - "profiles", - "reporting" - )); - private static List ORDER_DEVELOPER = new ArrayList(Arrays.asList( - "name", "id", "email")); - private static List ORDER_CONTRIBUTOR = new ArrayList(Arrays.asList( - "name", "id", "email")); - private static List ORDER_DEPENDENCY = new ArrayList(Arrays.asList( - "groupId", "artifactId", "version", "type", "classifier", "scope")); - private static List ORDER_PLUGIN = new ArrayList(Arrays.asList( - "groupId", "artifactId", "version", "inherited", "extensions", "configuration")); - //} - - /* - * Change the default order. Important data goes first. - */ - @Override - protected Set getProperties(Class type) { - try { - if (type.isAssignableFrom(Model.class)) { - return sortTypeWithOrder(type, ORDER_MODEL); - } else if (type.isAssignableFrom(Developer.class)) { - return sortTypeWithOrder(type, ORDER_DEVELOPER); - } else if (type.isAssignableFrom(Contributor.class)) { - return sortTypeWithOrder(type, ORDER_CONTRIBUTOR); - } else if (type.isAssignableFrom(Dependency.class)) { - return sortTypeWithOrder(type, ORDER_DEPENDENCY); - } else if (type.isAssignableFrom(Plugin.class)) { - return sortTypeWithOrder(type, ORDER_PLUGIN); - } else { - return super.getProperties(type); - } - } catch (IntrospectionException e) { - throw new YAMLException(e); + /* + * Change the default order. Important data goes first. + */ + @Override + protected Set getProperties(Class type) { + try { + if (type.isAssignableFrom(Model.class)) { + return sortTypeWithOrder(type, ORDER_MODEL); + } else if (type.isAssignableFrom(Developer.class)) { + return sortTypeWithOrder(type, ORDER_DEVELOPER); + } else if (type.isAssignableFrom(Contributor.class)) { + return sortTypeWithOrder(type, ORDER_CONTRIBUTOR); + } else if (type.isAssignableFrom(Dependency.class)) { + return sortTypeWithOrder(type, ORDER_DEPENDENCY); + } else if (type.isAssignableFrom(Plugin.class)) { + return sortTypeWithOrder(type, ORDER_PLUGIN); + } else { + return super.getProperties(type); + } + } catch (IntrospectionException e) { + throw new YAMLException(e); + } } - } - private Set sortTypeWithOrder(Class type, List order) - throws IntrospectionException { - Set standard = super.getProperties(type); - Set sorted = new TreeSet(new ModelPropertyComparator(order)); - sorted.addAll(standard); - return sorted; - } + private Set sortTypeWithOrder(Class type, List order) + throws IntrospectionException { + Set standard = super.getProperties(type); + Set sorted = new TreeSet(new ModelPropertyComparator(order)); + sorted.addAll(standard); + return sorted; + } - private class ModelPropertyComparator implements Comparator { - private List names; + private class ModelPropertyComparator implements Comparator { + private List names; - public ModelPropertyComparator(List names) { - this.names = names; - } + public ModelPropertyComparator(List names) { + this.names = names; + } - public int compare(Property o1, Property o2) { - // important go first - for (String name : names) { - int c = compareByName(o1, o2, name); - if (c != 0) { - return c; + public int compare(Property o1, Property o2) { + // important go first + for (String name : names) { + int c = compareByName(o1, o2, name); + if (c != 0) { + return c; + } + } + // all the rest + return o1.compareTo(o2); } - } - // all the rest - return o1.compareTo(o2); - } - private int compareByName(Property o1, Property o2, String name) { - if (o1.getName().equals(name)) { - return -1; - } else if (o2.getName().equals(name)) { - return 1; - } - return 0;// compare further + private int compareByName(Property o1, Property o2, String name) { + if (o1.getName().equals(name)) { + return -1; + } else if (o2.getName().equals(name)) { + return 1; + } + return 0; // compare further + } } - } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelResolver.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelResolver.java index c419ebc1..8e3a0bfd 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelResolver.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/ModelResolver.java @@ -7,21 +7,22 @@ */ package org.sonatype.maven.polyglot.yaml; +import java.util.regex.Pattern; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.resolver.Resolver; -import java.util.regex.Pattern; - /** * POM resolver does not need to resolve implicit scalar types as defined in * http://www.yaml.org/type/ */ public class ModelResolver extends Resolver { public static final Pattern POM_NULL = Pattern.compile("^(?:null| )$"); - public static final Pattern COORDINATE_PATTERN = Pattern.compile("^(?:(?[^:]+?):(?[^:]+?):(?[0-9][^:]+?))$"); + public static final Pattern COORDINATE_PATTERN = + Pattern.compile("^(?:(?[^:]+?):(?[^:]+?):(?[0-9][^:]+?))$"); public static final Pattern GROUP_NAME_PATTERN = Pattern.compile("^(?:(?[^:]+?):(?[^:]+?))$"); - //TODO scopes: compile|provided|runtime|test|system|import - public static final Pattern DEPENDENCY_PATTERN = Pattern.compile("^(?:(?[^:]+?):(?[^:]+?):(?[^:]+?):(?[0-9].+?))$"); + // TODO scopes: compile|provided|runtime|test|system|import + public static final Pattern DEPENDENCY_PATTERN = + Pattern.compile("^(?:(?[^:]+?):(?[^:]+?):(?[^:]+?):(?[0-9].+?))$"); @Override protected void addImplicitResolvers() { diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlMapping.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlMapping.java index f4d65c82..a0c4e2a8 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlMapping.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlMapping.java @@ -9,7 +9,6 @@ import javax.inject.Named; import javax.inject.Singleton; - import org.sonatype.maven.polyglot.mapping.MappingSupport; /** @@ -22,11 +21,11 @@ @Singleton @Named("yaml") public class YamlMapping extends MappingSupport { - public YamlMapping() { - super("yaml"); - setPomNames("pom.yaml", "pom.yml"); - setAcceptLocationExtensions(".yaml", ".yml"); - setAcceptOptionKeys("yaml:4.0.0"); - setPriority(1); - } -} \ No newline at end of file + public YamlMapping() { + super("yaml"); + setPomNames("pom.yaml", "pom.yml"); + setAcceptLocationExtensions(".yaml", ".yml"); + setAcceptOptionKeys("yaml:4.0.0"); + setPriority(1); + } +} diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelReader.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelReader.java index 797264a2..09db99b2 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelReader.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelReader.java @@ -7,9 +7,11 @@ */ package org.sonatype.maven.polyglot.yaml; +import java.io.IOException; +import java.io.Reader; +import java.util.Map; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelParseException; import org.sonatype.maven.polyglot.io.ModelReaderSupport; @@ -18,10 +20,6 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; -import java.io.IOException; -import java.io.Reader; -import java.util.Map; - /** * YAML model reader. * @@ -33,19 +31,19 @@ @Singleton @Named("yaml") public class YamlModelReader extends ModelReaderSupport { - private final Yaml yaml; - - public YamlModelReader() { - ModelConstructor constructor = new ModelConstructor(new LoaderOptions()); - DumperOptions options = new DumperOptions(); - yaml = new Yaml(constructor, new Representer(options), options, new ModelResolver()); - } + private final Yaml yaml; - public Model read(Reader input, Map options) throws IOException, ModelParseException { - if (input == null) { - throw new IllegalArgumentException("YAML Reader is null."); + public YamlModelReader() { + ModelConstructor constructor = new ModelConstructor(new LoaderOptions()); + DumperOptions options = new DumperOptions(); + yaml = new Yaml(constructor, new Representer(options), options, new ModelResolver()); } - return (Model) yaml.load(input); - } + public Model read(Reader input, Map options) throws IOException, ModelParseException { + if (input == null) { + throw new IllegalArgumentException("YAML Reader is null."); + } + + return (Model) yaml.load(input); + } } diff --git a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelWriter.java b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelWriter.java index c8f7e4d0..9118818c 100644 --- a/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelWriter.java +++ b/polyglot-yaml/src/main/java/org/sonatype/maven/polyglot/yaml/YamlModelWriter.java @@ -7,9 +7,11 @@ */ package org.sonatype.maven.polyglot.yaml; +import java.io.IOException; +import java.io.Writer; +import java.util.Map; import javax.inject.Named; import javax.inject.Singleton; - import org.apache.maven.model.Model; import org.sonatype.maven.polyglot.io.ModelWriterSupport; import org.yaml.snakeyaml.DumperOptions; @@ -20,10 +22,6 @@ import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.serializer.Serializer; -import java.io.IOException; -import java.io.Writer; -import java.util.Map; - /** * YAML model writer. * @@ -34,20 +32,21 @@ @Singleton @Named("yaml") public class YamlModelWriter extends ModelWriterSupport { - public void write(Writer output, Map o, Model model) throws IOException { - DumperOptions dumperOptions = new DumperOptions(); - dumperOptions.setIndent(2); - dumperOptions.setWidth(80); - dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); - Serializer serializer = new Serializer(new Emitter(output, dumperOptions), new ModelResolver(), dumperOptions, Tag.MAP); - Representer representer = new ModelRepresenter(dumperOptions); - try { - serializer.open(); - Node node = representer.represent(model); - serializer.serialize(node); - serializer.close(); - } catch (IOException e) { - throw new YAMLException(e); + public void write(Writer output, Map o, Model model) throws IOException { + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setIndent(2); + dumperOptions.setWidth(80); + dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); + Serializer serializer = + new Serializer(new Emitter(output, dumperOptions), new ModelResolver(), dumperOptions, Tag.MAP); + Representer representer = new ModelRepresenter(dumperOptions); + try { + serializer.open(); + Node node = representer.represent(model); + serializer.serialize(node); + serializer.close(); + } catch (IOException e) { + throw new YAMLException(e); + } } - } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CloneTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CloneTest.java index f7c6770c..5ea26e29 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CloneTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CloneTest.java @@ -7,43 +7,39 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.Model; -import org.apache.maven.model.io.ModelWriter; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.util.Properties; - -import static org.junit.Assert.assertNotNull; +import org.apache.maven.model.Model; +import org.apache.maven.model.io.ModelWriter; +import org.junit.Test; public class CloneTest { - @Test - public void testModelCloning() - throws Exception { - getModel().clone(); - } + @Test + public void testModelCloning() throws Exception { + getModel().clone(); + } - @Test - public void testModelWriter() - throws Exception { - StringWriter sw = new StringWriter(); - ModelWriter writer = new YamlModelWriter(); - Model model = getModel(); - Properties p = new Properties(); - p.setProperty("FOO", "BAR"); - model.setProperties(p); - writer.write(sw, null, model); - //System.out.println(sw.toString()); - } + @Test + public void testModelWriter() throws Exception { + StringWriter sw = new StringWriter(); + ModelWriter writer = new YamlModelWriter(); + Model model = getModel(); + Properties p = new Properties(); + p.setProperty("FOO", "BAR"); + model.setProperties(p); + writer.write(sw, null, model); + // System.out.println(sw.toString()); + } - protected Model getModel() - throws Exception { - YamlModelReader modelReader = new YamlModelReader(); - URL url = getClass().getResource("test2.yml"); - assertNotNull(url); - InputStream reader = url.openStream(); - return modelReader.read(reader, null); - } -} \ No newline at end of file + protected Model getModel() throws Exception { + YamlModelReader modelReader = new YamlModelReader(); + URL url = getClass().getResource("test2.yml"); + assertNotNull(url); + InputStream reader = url.openStream(); + return modelReader.read(reader, null); + } +} diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CompactFormatTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CompactFormatTest.java index feb6347c..3d545e56 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CompactFormatTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/CompactFormatTest.java @@ -7,224 +7,225 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.*; -import org.junit.Test; - -import java.io.InputStream; -import java.util.List; -import java.util.Properties; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.io.InputStream; +import java.util.List; +import java.util.Properties; +import org.apache.maven.model.*; +import org.junit.Test; + public class CompactFormatTest { - @Test - public void testModelReader() throws Exception { - Model model = getModel("different-dependencies.yaml"); - assertNotNull(model); - - Parent parent = model.getParent(); - assertNull(parent); - - assertEquals("org.yaml", model.getGroupId()); - assertEquals("snakeyaml", model.getArtifactId()); - assertEquals("1.17-SNAPSHOT", model.getVersion()); - assertEquals("SnakeYAML", model.getName()); - - // Dependencies - List dependencies = model.getDependencies(); - assertEquals(10, dependencies.size()); - - Dependency d0 = dependencies.get(0); - assertEquals("junit", d0.getGroupId()); - assertEquals("junit", d0.getArtifactId()); - assertEquals("4.12", d0.getVersion()); - - Dependency d1 = dependencies.get(1); - assertEquals("org.springframework", d1.getGroupId()); - assertEquals("spring", d1.getArtifactId()); - assertEquals("2.5.6", d1.getVersion()); - - Dependency mega = dependencies.get(3); - assertEquals("org.mega", mega.getGroupId()); - assertEquals("package1", mega.getArtifactId()); - assertEquals("1.0b", mega.getVersion()); - assertEquals(2, mega.getExclusions().size()); - - Dependency joda = dependencies.get(4); - assertEquals("joda-time", joda.getGroupId()); - assertEquals("joda-time", joda.getArtifactId()); - assertEquals("test", joda.getScope()); - assertEquals("1.6", joda.getVersion()); - - Dependency commons = dependencies.get(5); - assertEquals("commons-io", commons.getGroupId()); - assertEquals("commons-io", commons.getArtifactId()); - assertNull(commons.getScope()); - assertEquals("2.4-SNAPSHOT", commons.getVersion()); - - Dependency httpclient = dependencies.get(6); - assertEquals("org.apache.httpcomponents", httpclient.getGroupId()); - assertEquals("httpclient", httpclient.getArtifactId()); - assertEquals("runtime", httpclient.getScope()); - assertEquals("4.2.5", httpclient.getVersion()); - assertEquals(2, httpclient.getExclusions().size()); - - Dependency jumbo = dependencies.get(7); - assertEquals("jumbo", jumbo.getGroupId()); - assertEquals("humbo", jumbo.getArtifactId()); - assertEquals("system", jumbo.getScope()); - assertEquals("0.1", jumbo.getVersion()); - assertEquals(1, jumbo.getExclusions().size()); - - Dependency redundantId = dependencies.get(8); - assertEquals("org.jumbo", redundantId.getGroupId()); - assertEquals("humo", redundantId.getArtifactId()); - assertNull(redundantId.getScope()); - assertEquals("0.1alpha", redundantId.getVersion()); - assertEquals(0, redundantId.getExclusions().size()); - - //log:log4me - Dependency noVersion = dependencies.get(9); - assertEquals("log", noVersion.getGroupId()); - assertEquals("log4me", noVersion.getArtifactId()); - assertNull(noVersion.getScope()); - assertNull(noVersion.getVersion()); - - } - - @Test - public void testColonInFlowContext() throws Exception { - // support for colon in the flow context is improved - // in SnakeYAML 2.0 - try { - getModel("dependencies-colon-issue.yaml"); - } catch (Exception e) { - String message = e.getMessage(); - assertTrue(message, message.contains("Unable to find property 'groupId:log4j' on class: org.apache.maven.model.Exclusion")); + @Test + public void testModelReader() throws Exception { + Model model = getModel("different-dependencies.yaml"); + assertNotNull(model); + + Parent parent = model.getParent(); + assertNull(parent); + + assertEquals("org.yaml", model.getGroupId()); + assertEquals("snakeyaml", model.getArtifactId()); + assertEquals("1.17-SNAPSHOT", model.getVersion()); + assertEquals("SnakeYAML", model.getName()); + + // Dependencies + List dependencies = model.getDependencies(); + assertEquals(10, dependencies.size()); + + Dependency d0 = dependencies.get(0); + assertEquals("junit", d0.getGroupId()); + assertEquals("junit", d0.getArtifactId()); + assertEquals("4.12", d0.getVersion()); + + Dependency d1 = dependencies.get(1); + assertEquals("org.springframework", d1.getGroupId()); + assertEquals("spring", d1.getArtifactId()); + assertEquals("2.5.6", d1.getVersion()); + + Dependency mega = dependencies.get(3); + assertEquals("org.mega", mega.getGroupId()); + assertEquals("package1", mega.getArtifactId()); + assertEquals("1.0b", mega.getVersion()); + assertEquals(2, mega.getExclusions().size()); + + Dependency joda = dependencies.get(4); + assertEquals("joda-time", joda.getGroupId()); + assertEquals("joda-time", joda.getArtifactId()); + assertEquals("test", joda.getScope()); + assertEquals("1.6", joda.getVersion()); + + Dependency commons = dependencies.get(5); + assertEquals("commons-io", commons.getGroupId()); + assertEquals("commons-io", commons.getArtifactId()); + assertNull(commons.getScope()); + assertEquals("2.4-SNAPSHOT", commons.getVersion()); + + Dependency httpclient = dependencies.get(6); + assertEquals("org.apache.httpcomponents", httpclient.getGroupId()); + assertEquals("httpclient", httpclient.getArtifactId()); + assertEquals("runtime", httpclient.getScope()); + assertEquals("4.2.5", httpclient.getVersion()); + assertEquals(2, httpclient.getExclusions().size()); + + Dependency jumbo = dependencies.get(7); + assertEquals("jumbo", jumbo.getGroupId()); + assertEquals("humbo", jumbo.getArtifactId()); + assertEquals("system", jumbo.getScope()); + assertEquals("0.1", jumbo.getVersion()); + assertEquals(1, jumbo.getExclusions().size()); + + Dependency redundantId = dependencies.get(8); + assertEquals("org.jumbo", redundantId.getGroupId()); + assertEquals("humo", redundantId.getArtifactId()); + assertNull(redundantId.getScope()); + assertEquals("0.1alpha", redundantId.getVersion()); + assertEquals(0, redundantId.getExclusions().size()); + + // log:log4me + Dependency noVersion = dependencies.get(9); + assertEquals("log", noVersion.getGroupId()); + assertEquals("log4me", noVersion.getArtifactId()); + assertNull(noVersion.getScope()); + assertNull(noVersion.getVersion()); + } + + @Test + public void testColonInFlowContext() throws Exception { + // support for colon in the flow context is improved + // in SnakeYAML 2.0 + try { + getModel("dependencies-colon-issue.yaml"); + } catch (Exception e) { + String message = e.getMessage(); + assertTrue( + message, + message.contains( + "Unable to find property 'groupId:log4j' on class: org.apache.maven.model.Exclusion")); + } + } + + @Test + public void testCompactParent() throws Exception { + Model model = getModel("compact-parent.yaml"); + assertNotNull(model); + Parent parent = model.getParent(); + // org.apache:father:1.0.0.0 + assertEquals("org.apache", parent.getGroupId()); + assertEquals("father", parent.getArtifactId()); + assertEquals("1.0.0.0", parent.getVersion()); + } + + @Test + public void testCompactPomId() throws Exception { + Model model = getModel("compact-pom-id.yaml"); + assertNotNull(model); + assertEquals("org.yaml", model.getGroupId()); + assertEquals("snakeyaml", model.getArtifactId()); + assertEquals("1.17", model.getVersion()); + } + + @Test + public void testCompactBuildExtensions() throws Exception { + Model model = getModel("compact-build-extensions.yaml"); + assertNotNull(model); + Build build = model.getBuild(); + List extensions = build.getExtensions(); + assertEquals(1, extensions.size()); + Extension extension = extensions.get(0); + // org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2 + assertEquals("org.apache.maven.wagon", extension.getGroupId()); + assertEquals("wagon-ssh-external", extension.getArtifactId()); + assertEquals("1.0-beta-2", extension.getVersion()); + } + + @Test + public void testCompactProperties() throws Exception { + Model model = getModel("compact-properties.yaml"); + assertNotNull(model); + Properties properties = model.getProperties(); + assertEquals("UTF-8", properties.get("project.build.sourceEncoding")); + assertEquals("${project.build.directory}/surefire-reports", properties.get("sonar.junit.reportsPath")); + } + + @Test + public void testCompactPrerequisites() throws Exception { + Model model = getModel("compact-prerequisites.yaml"); + assertNotNull(model); + Prerequisites prerequisites = model.getPrerequisites(); + assertEquals("3.3.1", prerequisites.getMaven()); + } + + @Test + public void testCompactExample() throws Exception { + Model model = getModel("compact-example.yaml"); + assertNotNull(model); + } + + @Test + public void testCompactBuildPlugins() throws Exception { + Model model = getModel("compact-build-plugins.yaml"); + assertNotNull(model); + Build build = model.getBuild(); + List plugins = build.getPlugins(); + assertEquals(5, plugins.size()); + Plugin extension = plugins.get(0); + // org.apache.maven.plugins:maven-compiler-plugin:2.3 + assertEquals("org.apache.maven.plugins", extension.getGroupId()); + assertEquals("maven-compiler-plugin", extension.getArtifactId()); + assertEquals("2.3", extension.getVersion()); + + Plugin site = plugins.get(2); + // org.apache.maven.plugins:maven-site-plugin:2.3.2 + assertEquals("org.apache.maven.plugins", site.getGroupId()); + assertEquals("maven-site-plugin", site.getArtifactId()); + assertEquals("2.3.2", site.getVersion()); + assertNotNull(site.getConfiguration()); + } + + @Test + public void testCompactBuildPluginManagement() throws Exception { + Model model = getModel("compact-build-plugin-management.yaml"); + assertNotNull(model); + Build build = model.getBuild(); + List plugins = build.getPluginManagement().getPlugins(); + assertEquals(5, plugins.size()); + Plugin extension = plugins.get(0); + // org.apache.maven.plugins:maven-compiler-plugin:2.3 + assertEquals("org.apache.maven.plugins", extension.getGroupId()); + assertEquals("maven-compiler-plugin", extension.getArtifactId()); + assertEquals("2.3", extension.getVersion()); + + Plugin site = plugins.get(2); + // org.apache.maven.plugins:maven-site-plugin:2.3.2 + assertEquals("org.apache.maven.plugins", site.getGroupId()); + assertEquals("maven-site-plugin", site.getArtifactId()); + assertEquals("2.3.2", site.getVersion()); + assertNotNull(site.getConfiguration()); + } + + @Test + public void testCompactReportPlugins() throws Exception { + Model model = getModel("compact-report-plugins.yaml"); + assertNotNull(model); + Reporting reporting = model.getReporting(); + List plugins = reporting.getPlugins(); + assertEquals(1, plugins.size()); + ReportPlugin extension = plugins.get(0); + // org.apache.maven.plugins:maven-compiler-plugin:2.3 + assertEquals("org.apache.maven.plugins", extension.getGroupId()); + assertEquals("maven-surefire-report-plugin", extension.getArtifactId()); + assertEquals("2.18.1", extension.getVersion()); + } + + protected Model getModel(String name) throws Exception { + YamlModelReader modelReader = new YamlModelReader(); + InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); + assertNotNull(input); + return modelReader.read(input, null); } - } - - @Test - public void testCompactParent() throws Exception { - Model model = getModel("compact-parent.yaml"); - assertNotNull(model); - Parent parent = model.getParent(); - //org.apache:father:1.0.0.0 - assertEquals("org.apache", parent.getGroupId()); - assertEquals("father", parent.getArtifactId()); - assertEquals("1.0.0.0", parent.getVersion()); - } - - @Test - public void testCompactPomId() throws Exception { - Model model = getModel("compact-pom-id.yaml"); - assertNotNull(model); - assertEquals("org.yaml", model.getGroupId()); - assertEquals("snakeyaml", model.getArtifactId()); - assertEquals("1.17", model.getVersion()); - } - - @Test - public void testCompactBuildExtensions() throws Exception { - Model model = getModel("compact-build-extensions.yaml"); - assertNotNull(model); - Build build = model.getBuild(); - List extensions = build.getExtensions(); - assertEquals(1, extensions.size()); - Extension extension = extensions.get(0); - //org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2 - assertEquals("org.apache.maven.wagon", extension.getGroupId()); - assertEquals("wagon-ssh-external", extension.getArtifactId()); - assertEquals("1.0-beta-2", extension.getVersion()); - } - - @Test - public void testCompactProperties() throws Exception { - Model model = getModel("compact-properties.yaml"); - assertNotNull(model); - Properties properties = model.getProperties(); - assertEquals("UTF-8", properties.get("project.build.sourceEncoding")); - assertEquals("${project.build.directory}/surefire-reports", properties.get("sonar.junit.reportsPath")); - } - - @Test - public void testCompactPrerequisites() throws Exception { - Model model = getModel("compact-prerequisites.yaml"); - assertNotNull(model); - Prerequisites prerequisites = model.getPrerequisites(); - assertEquals("3.3.1", prerequisites.getMaven()); - } - - @Test - public void testCompactExample() throws Exception { - Model model = getModel("compact-example.yaml"); - assertNotNull(model); - } - - @Test - public void testCompactBuildPlugins() throws Exception { - Model model = getModel("compact-build-plugins.yaml"); - assertNotNull(model); - Build build = model.getBuild(); - List plugins = build.getPlugins(); - assertEquals(5, plugins.size()); - Plugin extension = plugins.get(0); - //org.apache.maven.plugins:maven-compiler-plugin:2.3 - assertEquals("org.apache.maven.plugins", extension.getGroupId()); - assertEquals("maven-compiler-plugin", extension.getArtifactId()); - assertEquals("2.3", extension.getVersion()); - - Plugin site = plugins.get(2); - //org.apache.maven.plugins:maven-site-plugin:2.3.2 - assertEquals("org.apache.maven.plugins", site.getGroupId()); - assertEquals("maven-site-plugin", site.getArtifactId()); - assertEquals("2.3.2", site.getVersion()); - assertNotNull(site.getConfiguration()); - } - - @Test - public void testCompactBuildPluginManagement() throws Exception { - Model model = getModel("compact-build-plugin-management.yaml"); - assertNotNull(model); - Build build = model.getBuild(); - List plugins = build.getPluginManagement().getPlugins(); - assertEquals(5, plugins.size()); - Plugin extension = plugins.get(0); - //org.apache.maven.plugins:maven-compiler-plugin:2.3 - assertEquals("org.apache.maven.plugins", extension.getGroupId()); - assertEquals("maven-compiler-plugin", extension.getArtifactId()); - assertEquals("2.3", extension.getVersion()); - - Plugin site = plugins.get(2); - //org.apache.maven.plugins:maven-site-plugin:2.3.2 - assertEquals("org.apache.maven.plugins", site.getGroupId()); - assertEquals("maven-site-plugin", site.getArtifactId()); - assertEquals("2.3.2", site.getVersion()); - assertNotNull(site.getConfiguration()); - } - - @Test - public void testCompactReportPlugins() throws Exception { - Model model = getModel("compact-report-plugins.yaml"); - assertNotNull(model); - Reporting reporting = model.getReporting(); - List plugins = reporting.getPlugins(); - assertEquals(1, plugins.size()); - ReportPlugin extension = plugins.get(0); - //org.apache.maven.plugins:maven-compiler-plugin:2.3 - assertEquals("org.apache.maven.plugins", extension.getGroupId()); - assertEquals("maven-surefire-report-plugin", extension.getArtifactId()); - assertEquals("2.18.1", extension.getVersion()); - } - - protected Model getModel(String name) throws Exception { - YamlModelReader modelReader = new YamlModelReader(); - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - assertNotNull(input); - return modelReader.read(input, null); - } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ElementsWithAttributesTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ElementsWithAttributesTest.java index ea3d7c2c..b3e5b337 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ElementsWithAttributesTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ElementsWithAttributesTest.java @@ -1,18 +1,21 @@ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; +import static org.sonatype.maven.polyglot.yaml.Util.getModel; + import org.apache.maven.model.Model; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.sonatype.maven.polyglot.yaml.Util.getModel; - public class ElementsWithAttributesTest { - @Test - public void testCompactExample() throws Exception { - Model model = getModel("elements-with-attributes-example.yaml"); - Xpp3Dom configuration = (Xpp3Dom) model.getBuild().getPlugins().get(0).getExecutions().get(0).getConfiguration(); + @Test + public void testCompactExample() throws Exception { + Model model = getModel("elements-with-attributes-example.yaml"); + Xpp3Dom configuration = (Xpp3Dom) + model.getBuild().getPlugins().get(0).getExecutions().get(0).getConfiguration(); - assertEquals("Hello from polyglot-yaml", configuration.getChild("target").getChild("echo").getAttribute("message")); - } + assertEquals( + "Hello from polyglot-yaml", + configuration.getChild("target").getChild("echo").getAttribute("message")); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue36Test.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue36Test.java index 47ca82a9..94461c8b 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue36Test.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue36Test.java @@ -7,30 +7,29 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.Model; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.InputStream; - -import static org.junit.Assert.assertNotNull; +import org.apache.maven.model.Model; +import org.junit.Test; public class Issue36Test { - @Test - public void testOriginalYaml() throws Exception { - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issue36.yaml"); - assertNotNull(input); - YamlModelReader modelReader = new YamlModelReader(); - Model model = modelReader.read(input, null); - assertNotNull(model); - } + @Test + public void testOriginalYaml() throws Exception { + InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issue36.yaml"); + assertNotNull(input); + YamlModelReader modelReader = new YamlModelReader(); + Model model = modelReader.read(input, null); + assertNotNull(model); + } - @Test - public void testShortYaml() throws Exception { - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issue36-short.yaml"); - assertNotNull(input); - YamlModelReader modelReader = new YamlModelReader(); - Model model = modelReader.read(input, null); - assertNotNull(model); - } + @Test + public void testShortYaml() throws Exception { + InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issue36-short.yaml"); + assertNotNull(input); + YamlModelReader modelReader = new YamlModelReader(); + Model model = modelReader.read(input, null); + assertNotNull(model); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue44NestedListsTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue44NestedListsTest.java index 223dcb5b..275ef324 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue44NestedListsTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue44NestedListsTest.java @@ -7,134 +7,135 @@ */ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.InputStream; import org.apache.maven.model.ConfigurationContainer; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - /** * @see polyglot-yaml does not handle nested lists */ public class Issue44NestedListsTest { - /** - * It converts nested lists from YAML into Maven's {@link ConfigurationContainer} XML DOM nodes and automagically - * inserts XML child nodes with names derived from the parent's plural node name. - */ - @Test - public void readNestedLists() throws Exception { - - // given - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("issue44-nested-lists.yaml"); - assertNotNull(input); - - String expectedContents = Util.getLocalResource("issue44-nested-lists-expected.xml"); - - YamlModelReader modelReader = new YamlModelReader(); - - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals("proguard-maven-plugin", plugin.getArtifactId()); - assertEquals("2.0.11", plugin.getVersion()); - - Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); - - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } - - /** - * It converts explicitly specified YAML pairs into Maven's {@link ConfigurationContainer} XML DOM nodes. This method - * can be used if the list container node name is not a plural form of the list items node names. - */ - @Test - public void readExplicitPairs() throws Exception { - - // given - InputStream input = - Thread.currentThread().getContextClassLoader().getResourceAsStream("issue44-explicit-pairs.yaml"); - assertNotNull(input); - - String expectedContents = Util.getLocalResource("issue44-explicit-pairs-expected.xml"); - - YamlModelReader modelReader = new YamlModelReader(); - - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals("test-plugin", plugin.getArtifactId()); - assertEquals("3.4", plugin.getVersion()); - - Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); - - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } - - /** - * It converts the given sample Maven resources configuration containing nested lists from YAML into Maven's - * {@link ConfigurationContainer} XML DOM nodes. - */ - @Test - public void readMavenResources() throws Exception { - - // given - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream( - "issue44-maven-resources.yaml"); - assertNotNull(input); - - String expectedContents = Util.getLocalResource("issue44-maven-resources-expected.xml"); - - YamlModelReader modelReader = new YamlModelReader(); - - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals("maven-resources-plugin", plugin.getArtifactId()); - assertEquals("2.7", plugin.getVersion()); - - Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); - - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } - - /** - * It converts the given sample Maven legacy reportPlugins configuration containing nested lists from YAML into - * Maven's {@link ConfigurationContainer} XML DOM nodes. - */ - @Test - public void readLegacyReportPlugins() throws Exception { - - // given - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream( - "issue44-legacy-report-plugins.yaml"); - assertNotNull(input); - - String expectedContents = Util.getLocalResource("issue44-legacy-report-plugins-expected.xml"); - - YamlModelReader modelReader = new YamlModelReader(); - - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals("maven-site-plugin", plugin.getArtifactId()); - assertEquals("3.4", plugin.getVersion()); + /** + * It converts nested lists from YAML into Maven's {@link ConfigurationContainer} XML DOM nodes and automagically + * inserts XML child nodes with names derived from the parent's plural node name. + */ + @Test + public void readNestedLists() throws Exception { + + // given + InputStream input = + Thread.currentThread().getContextClassLoader().getResourceAsStream("issue44-nested-lists.yaml"); + assertNotNull(input); + + String expectedContents = Util.getLocalResource("issue44-nested-lists-expected.xml"); - Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); + YamlModelReader modelReader = new YamlModelReader(); + + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals("proguard-maven-plugin", plugin.getArtifactId()); + assertEquals("2.0.11", plugin.getVersion()); + + Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); + + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } + + /** + * It converts explicitly specified YAML pairs into Maven's {@link ConfigurationContainer} XML DOM nodes. This method + * can be used if the list container node name is not a plural form of the list items node names. + */ + @Test + public void readExplicitPairs() throws Exception { + + // given + InputStream input = + Thread.currentThread().getContextClassLoader().getResourceAsStream("issue44-explicit-pairs.yaml"); + assertNotNull(input); + + String expectedContents = Util.getLocalResource("issue44-explicit-pairs-expected.xml"); + + YamlModelReader modelReader = new YamlModelReader(); + + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals("test-plugin", plugin.getArtifactId()); + assertEquals("3.4", plugin.getVersion()); + + Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); + + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } + + /** + * It converts the given sample Maven resources configuration containing nested lists from YAML into Maven's + * {@link ConfigurationContainer} XML DOM nodes. + */ + @Test + public void readMavenResources() throws Exception { + + // given + InputStream input = + Thread.currentThread().getContextClassLoader().getResourceAsStream("issue44-maven-resources.yaml"); + assertNotNull(input); + + String expectedContents = Util.getLocalResource("issue44-maven-resources-expected.xml"); + + YamlModelReader modelReader = new YamlModelReader(); + + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals("maven-resources-plugin", plugin.getArtifactId()); + assertEquals("2.7", plugin.getVersion()); + + Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); + + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } + + /** + * It converts the given sample Maven legacy reportPlugins configuration containing nested lists from YAML into + * Maven's {@link ConfigurationContainer} XML DOM nodes. + */ + @Test + public void readLegacyReportPlugins() throws Exception { + + // given + InputStream input = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("issue44-legacy-report-plugins.yaml"); + assertNotNull(input); + + String expectedContents = Util.getLocalResource("issue44-legacy-report-plugins-expected.xml"); + + YamlModelReader modelReader = new YamlModelReader(); + + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals("maven-site-plugin", plugin.getArtifactId()); + assertEquals("3.4", plugin.getVersion()); - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } + Xpp3Dom conf = (Xpp3Dom) plugin.getConfiguration(); + + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue62ShadePluginConfigurationTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue62ShadePluginConfigurationTest.java index 370fd962..97c4c831 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue62ShadePluginConfigurationTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Issue62ShadePluginConfigurationTest.java @@ -7,73 +7,72 @@ */ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.InputStream; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - /** * @see [polyglot-yaml] does not handle shade plugin */ public class Issue62ShadePluginConfigurationTest { - private static final String PLUGIN_ARTIFACT_ID = "maven-shade-plugin"; - private static final String PLUGIN_VERSION = "2.4.3"; + private static final String PLUGIN_ARTIFACT_ID = "maven-shade-plugin"; + private static final String PLUGIN_VERSION = "2.4.3"; - @Test - public void readShadePluginConfig() throws Exception { + @Test + public void readShadePluginConfig() throws Exception { - // given - InputStream input = getResourceAsStream("issue62-shade-plugin-config.yaml"); - assertNotNull(input); + // given + InputStream input = getResourceAsStream("issue62-shade-plugin-config.yaml"); + assertNotNull(input); - String expectedContents = Util.getLocalResource("issue62-shade-plugin-config-expected.xml"); + String expectedContents = Util.getLocalResource("issue62-shade-plugin-config-expected.xml"); - YamlModelReader modelReader = new YamlModelReader(); + YamlModelReader modelReader = new YamlModelReader(); - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals(PLUGIN_ARTIFACT_ID, plugin.getArtifactId()); - assertEquals(PLUGIN_VERSION, plugin.getVersion()); + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals(PLUGIN_ARTIFACT_ID, plugin.getArtifactId()); + assertEquals(PLUGIN_VERSION, plugin.getVersion()); - Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); + Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } - @Test - public void readShadePluginConfigWithExplicitPairs() throws Exception { + @Test + public void readShadePluginConfigWithExplicitPairs() throws Exception { - // given - InputStream input = getResourceAsStream("issue62-shade-plugin-config-with-pairs.yaml"); - assertNotNull(input); + // given + InputStream input = getResourceAsStream("issue62-shade-plugin-config-with-pairs.yaml"); + assertNotNull(input); - String expectedContents = Util.getLocalResource("issue62-shade-plugin-config-with-pairs-expected.xml"); + String expectedContents = Util.getLocalResource("issue62-shade-plugin-config-with-pairs-expected.xml"); - YamlModelReader modelReader = new YamlModelReader(); + YamlModelReader modelReader = new YamlModelReader(); - // when - Model model = modelReader.read(input, null); - assertNotNull(model); - Plugin plugin = model.getBuild().getPlugins().get(0); - assertEquals(PLUGIN_ARTIFACT_ID, plugin.getArtifactId()); - assertEquals(PLUGIN_VERSION, plugin.getVersion()); + // when + Model model = modelReader.read(input, null); + assertNotNull(model); + Plugin plugin = model.getBuild().getPlugins().get(0); + assertEquals(PLUGIN_ARTIFACT_ID, plugin.getArtifactId()); + assertEquals(PLUGIN_VERSION, plugin.getVersion()); - Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); + Xpp3Dom conf = (Xpp3Dom) plugin.getExecutions().get(0).getConfiguration(); - // then - assertEquals(expectedContents.trim(), conf.toString().trim()); - } + // then + assertEquals(expectedContents.trim(), conf.toString().trim()); + } - private InputStream getResourceAsStream(String name) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - } + private InputStream getResourceAsStream(String name) { + return Thread.currentThread().getContextClassLoader().getResourceAsStream(name); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelRepresenterTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelRepresenterTest.java index a1b9ab85..341a96cf 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelRepresenterTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelRepresenterTest.java @@ -1,5 +1,10 @@ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; + +import java.io.InputStream; +import java.io.StringWriter; +import java.io.Writer; import org.apache.maven.model.Plugin; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; @@ -11,50 +16,45 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.serializer.Serializer; -import java.io.InputStream; -import java.io.StringWriter; -import java.io.Writer; - -import static org.junit.Assert.assertEquals; - public class ModelRepresenterTest { - private ModelRepresenter modelRepresenter; - - @Before - public void setUp() throws Exception { - modelRepresenter = new ModelRepresenter(new DumperOptions()); - } - - @Test - public void representXpp3Dom() throws Exception { - // given - final Plugin plugin = new Plugin(); - - InputStream input = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("modelrepresenter/represent-xpp3-dom-lists.xml"); - Xpp3Dom configurationDom = Xpp3DomBuilder.build(input, "UTF-8"); - - plugin.setConfiguration(configurationDom); - plugin.setGroupId(null); - - String expectedRepresentation = Util.getLocalResource("modelrepresenter/represent-xpp3-dom-lists-expected.yaml"); - - // when - Node node = modelRepresenter.represent(plugin); - - // then - Writer stringWriter = new StringWriter(); - DumperOptions dumperOptions = new DumperOptions(); - dumperOptions.setIndent(2); - dumperOptions.setWidth(80); - dumperOptions.setPrettyFlow(false); - Serializer serializer = - new Serializer(new Emitter(stringWriter, dumperOptions), new ModelResolver(), dumperOptions, Tag.MAP); - serializer.open(); - serializer.serialize(node); - serializer.close(); - - assertEquals(expectedRepresentation.trim(), stringWriter.toString().trim()); - } - -} \ No newline at end of file + private ModelRepresenter modelRepresenter; + + @Before + public void setUp() throws Exception { + modelRepresenter = new ModelRepresenter(new DumperOptions()); + } + + @Test + public void representXpp3Dom() throws Exception { + // given + final Plugin plugin = new Plugin(); + + InputStream input = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("modelrepresenter/represent-xpp3-dom-lists.xml"); + Xpp3Dom configurationDom = Xpp3DomBuilder.build(input, "UTF-8"); + + plugin.setConfiguration(configurationDom); + plugin.setGroupId(null); + + String expectedRepresentation = + Util.getLocalResource("modelrepresenter/represent-xpp3-dom-lists-expected.yaml"); + + // when + Node node = modelRepresenter.represent(plugin); + + // then + Writer stringWriter = new StringWriter(); + DumperOptions dumperOptions = new DumperOptions(); + dumperOptions.setIndent(2); + dumperOptions.setWidth(80); + dumperOptions.setPrettyFlow(false); + Serializer serializer = + new Serializer(new Emitter(stringWriter, dumperOptions), new ModelResolver(), dumperOptions, Tag.MAP); + serializer.open(); + serializer.serialize(node); + serializer.close(); + + assertEquals(expectedRepresentation.trim(), stringWriter.toString().trim()); + } +} diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelResolverTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelResolverTest.java index fefc6261..86bdbb80 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelResolverTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/ModelResolverTest.java @@ -7,52 +7,51 @@ */ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.regex.Matcher; import org.junit.Test; import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.Tag; -import java.util.regex.Matcher; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - public class ModelResolverTest { - @Test - public void testModelNullResolver() { - ModelResolver resolver = new ModelResolver(); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "Null", true)); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "NULL", true)); - assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, "null", true)); - assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, " ", true)); - assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, "", true)); - } - - @Test - public void testModelResolver() { - ModelResolver resolver = new ModelResolver(); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "8", true)); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "3.1", true)); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "true", true)); - assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "false", true)); - } - - @Test - public void testCoordinateRE() { - Matcher matcher = ModelResolver.COORDINATE_PATTERN.matcher("org.yaml:snakeyaml:1.17-SNAPSHOT"); - assertTrue(matcher.matches()); - assertEquals("org.yaml", matcher.group("groupId")); - assertEquals("snakeyaml", matcher.group("artifactId")); - assertEquals("1.17-SNAPSHOT", matcher.group("version")); - } - - @Test - public void testDependencyREwithScope() { - Matcher matcher = ModelResolver.DEPENDENCY_PATTERN.matcher("org.yaml:snakeyaml:test:1.17-SNAPSHOT"); - assertTrue(matcher.matches()); - assertEquals("org.yaml", matcher.group("groupId")); - assertEquals("snakeyaml", matcher.group("artifactId")); - assertEquals("test", matcher.group("scope")); - assertEquals("1.17-SNAPSHOT", matcher.group("version")); - } + @Test + public void testModelNullResolver() { + ModelResolver resolver = new ModelResolver(); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "Null", true)); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "NULL", true)); + assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, "null", true)); + assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, " ", true)); + assertEquals(Tag.NULL, resolver.resolve(NodeId.scalar, "", true)); + } + + @Test + public void testModelResolver() { + ModelResolver resolver = new ModelResolver(); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "8", true)); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "3.1", true)); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "true", true)); + assertEquals(Tag.STR, resolver.resolve(NodeId.scalar, "false", true)); + } + + @Test + public void testCoordinateRE() { + Matcher matcher = ModelResolver.COORDINATE_PATTERN.matcher("org.yaml:snakeyaml:1.17-SNAPSHOT"); + assertTrue(matcher.matches()); + assertEquals("org.yaml", matcher.group("groupId")); + assertEquals("snakeyaml", matcher.group("artifactId")); + assertEquals("1.17-SNAPSHOT", matcher.group("version")); + } + + @Test + public void testDependencyREwithScope() { + Matcher matcher = ModelResolver.DEPENDENCY_PATTERN.matcher("org.yaml:snakeyaml:test:1.17-SNAPSHOT"); + assertTrue(matcher.matches()); + assertEquals("org.yaml", matcher.group("groupId")); + assertEquals("snakeyaml", matcher.group("artifactId")); + assertEquals("test", matcher.group("scope")); + assertEquals("1.17-SNAPSHOT", matcher.group("version")); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/SnakeYamlModelReaderTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/SnakeYamlModelReaderTest.java index 69238561..f59348a0 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/SnakeYamlModelReaderTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/SnakeYamlModelReaderTest.java @@ -7,10 +7,7 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.*; -import org.apache.maven.model.io.ModelWriter; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.junit.Test; +import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -18,123 +15,125 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Properties; - -import static org.junit.Assert.*; +import org.apache.maven.model.*; +import org.apache.maven.model.io.ModelWriter; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.junit.Test; public class SnakeYamlModelReaderTest { - @Test - public void testModelCloning() throws Exception { - getModel().clone(); - } - - @Test - public void testModelReader() throws Exception { - Model model = getModel(); - assertNotNull(model); - - Parent parent = model.getParent(); - assertNull(parent); - - assertEquals("org.yaml", model.getGroupId()); - assertEquals("snakeyaml", model.getArtifactId()); - assertEquals("1.17-SNAPSHOT", model.getVersion()); - assertEquals("SnakeYAML", model.getName()); - - // Developers - List developers = model.getDevelopers(); - Developer dev0 = developers.get(0); - assertEquals("asomov", dev0.getId()); - assertEquals("Andrey Somov", dev0.getName()); - - // Contributors - List contributors = model.getContributors(); - assertEquals(0, contributors.size()); - - // Dependencies - List dependencies = model.getDependencies(); - assertEquals(4, dependencies.size()); - - Dependency d0 = dependencies.get(0); - assertEquals("junit", d0.getGroupId()); - assertEquals("junit", d0.getArtifactId()); - assertEquals("4.12", d0.getVersion()); - - Dependency d1 = dependencies.get(1); - assertEquals("org.springframework", d1.getGroupId()); - assertEquals("spring", d1.getArtifactId()); - assertEquals("2.5.6", d1.getVersion()); - - // Modules - List modules = model.getModules(); - assertEquals(0, modules.size()); - - // Build - Build build = model.getBuild(); - List plugins = build.getPlugins(); - assertEquals(10, plugins.size()); - Plugin p0 = plugins.get(0); - assertEquals("org.apache.maven.plugins", p0.getGroupId()); - assertEquals("maven-compiler-plugin", p0.getArtifactId()); - assertEquals("3.3", p0.getVersion()); - Xpp3Dom configuration = (Xpp3Dom) p0.getConfiguration(); - assertNotNull(configuration); - assertEquals(3, configuration.getChildCount()); - assertEquals("1.5", configuration.getChild("source").getValue()); - assertEquals("1.5", configuration.getChild("target").getValue()); - - // DistributionManagement - DistributionManagement distMan = model.getDistributionManagement(); - Site site = distMan.getSite(); - assertNull(site); - - // SCM - Scm scm = model.getScm(); - assertEquals("scm:hg:http://bitbucket.org/asomov/snakeyaml", scm.getConnection()); - assertEquals("scm:hg:https://bitbucket.org/asomov/snakeyaml", scm.getDeveloperConnection()); - assertEquals("https://bitbucket.org/asomov/snakeyaml/src", scm.getUrl()); - - // IssueManagement - IssueManagement issueManagement = model.getIssueManagement(); - assertEquals("Bitbucket", issueManagement.getSystem()); - assertEquals("https://bitbucket.org/asomov/snakeyaml/issues", issueManagement.getUrl()); - - // CiManagement - CiManagement ciManagement = model.getCiManagement(); - assertNull(ciManagement); - } - - @Test - public void testModelWriter() throws Exception { - StringWriter sw = new StringWriter(); - ModelWriter writer = new YamlModelWriter(); - Model model = getModel(); - Properties p = new Properties(); - p.setProperty("FOO", "BAR"); - model.setProperties(p); - writer.write(sw, null, model); - String output = sw.toString(); - //System.out.println(output); - assertTrue(output, output.contains("\nproperties: {FOO: BAR}\n")); - assertFalse("Null values should be printed.", output.contains("reporting: null")); - assertFalse("Empty maps should be printed.", output.contains("properties: {}")); - assertFalse("Empty lists should be printed.", output.contains("extensions: []")); - assertFalse("AsMap should be printed.", output.contains("AsMap")); - assertFalse("getModelEncoding should be printed.", output.contains("getModelEncoding")); - - String expected = Util.getLocalResource("snakeyaml/generated-pom.yaml"); - //assertEquals(expected.trim(), output.trim()); - - YamlModelReader modelReader = new YamlModelReader(); - InputStream stream = new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8)); - - Model model2 = modelReader.read(stream, null); - assertNotNull(model2); - } - - protected Model getModel() throws Exception { - YamlModelReader modelReader = new YamlModelReader(); - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("snakeyaml/pom.yaml"); - assertNotNull(input); - return modelReader.read(input, null); - } + @Test + public void testModelCloning() throws Exception { + getModel().clone(); + } + + @Test + public void testModelReader() throws Exception { + Model model = getModel(); + assertNotNull(model); + + Parent parent = model.getParent(); + assertNull(parent); + + assertEquals("org.yaml", model.getGroupId()); + assertEquals("snakeyaml", model.getArtifactId()); + assertEquals("1.17-SNAPSHOT", model.getVersion()); + assertEquals("SnakeYAML", model.getName()); + + // Developers + List developers = model.getDevelopers(); + Developer dev0 = developers.get(0); + assertEquals("asomov", dev0.getId()); + assertEquals("Andrey Somov", dev0.getName()); + + // Contributors + List contributors = model.getContributors(); + assertEquals(0, contributors.size()); + + // Dependencies + List dependencies = model.getDependencies(); + assertEquals(4, dependencies.size()); + + Dependency d0 = dependencies.get(0); + assertEquals("junit", d0.getGroupId()); + assertEquals("junit", d0.getArtifactId()); + assertEquals("4.12", d0.getVersion()); + + Dependency d1 = dependencies.get(1); + assertEquals("org.springframework", d1.getGroupId()); + assertEquals("spring", d1.getArtifactId()); + assertEquals("2.5.6", d1.getVersion()); + + // Modules + List modules = model.getModules(); + assertEquals(0, modules.size()); + + // Build + Build build = model.getBuild(); + List plugins = build.getPlugins(); + assertEquals(10, plugins.size()); + Plugin p0 = plugins.get(0); + assertEquals("org.apache.maven.plugins", p0.getGroupId()); + assertEquals("maven-compiler-plugin", p0.getArtifactId()); + assertEquals("3.3", p0.getVersion()); + Xpp3Dom configuration = (Xpp3Dom) p0.getConfiguration(); + assertNotNull(configuration); + assertEquals(3, configuration.getChildCount()); + assertEquals("1.5", configuration.getChild("source").getValue()); + assertEquals("1.5", configuration.getChild("target").getValue()); + + // DistributionManagement + DistributionManagement distMan = model.getDistributionManagement(); + Site site = distMan.getSite(); + assertNull(site); + + // SCM + Scm scm = model.getScm(); + assertEquals("scm:hg:http://bitbucket.org/asomov/snakeyaml", scm.getConnection()); + assertEquals("scm:hg:https://bitbucket.org/asomov/snakeyaml", scm.getDeveloperConnection()); + assertEquals("https://bitbucket.org/asomov/snakeyaml/src", scm.getUrl()); + + // IssueManagement + IssueManagement issueManagement = model.getIssueManagement(); + assertEquals("Bitbucket", issueManagement.getSystem()); + assertEquals("https://bitbucket.org/asomov/snakeyaml/issues", issueManagement.getUrl()); + + // CiManagement + CiManagement ciManagement = model.getCiManagement(); + assertNull(ciManagement); + } + + @Test + public void testModelWriter() throws Exception { + StringWriter sw = new StringWriter(); + ModelWriter writer = new YamlModelWriter(); + Model model = getModel(); + Properties p = new Properties(); + p.setProperty("FOO", "BAR"); + model.setProperties(p); + writer.write(sw, null, model); + String output = sw.toString(); + // System.out.println(output); + assertTrue(output, output.contains("\nproperties: {FOO: BAR}\n")); + assertFalse("Null values should be printed.", output.contains("reporting: null")); + assertFalse("Empty maps should be printed.", output.contains("properties: {}")); + assertFalse("Empty lists should be printed.", output.contains("extensions: []")); + assertFalse("AsMap should be printed.", output.contains("AsMap")); + assertFalse("getModelEncoding should be printed.", output.contains("getModelEncoding")); + + String expected = Util.getLocalResource("snakeyaml/generated-pom.yaml"); + // assertEquals(expected.trim(), output.trim()); + + YamlModelReader modelReader = new YamlModelReader(); + InputStream stream = new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8)); + + Model model2 = modelReader.read(stream, null); + assertNotNull(model2); + } + + protected Model getModel() throws Exception { + YamlModelReader modelReader = new YamlModelReader(); + InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("snakeyaml/pom.yaml"); + assertNotNull(input); + return modelReader.read(input, null); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Util.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Util.java index d2499f99..f7db9e77 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Util.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/Util.java @@ -7,52 +7,51 @@ */ package org.sonatype.maven.polyglot.yaml; -import org.apache.maven.model.Model; - import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.maven.model.Model; public class Util { - /** - * Read resource form classpath - * @param theName - the resource name - */ - public static String getLocalResource(String theName) { - try { - InputStream input; - input = Thread.currentThread().getContextClassLoader().getResourceAsStream(theName); - if (input == null) { - throw new RuntimeException("Can not find " + theName); - } - BufferedInputStream is = new BufferedInputStream(input); - StringBuilder buf = new StringBuilder(3000); - int i; - try { - while ((i = is.read()) != -1) { - buf.append((char) i); + /** + * Read resource form classpath + * @param theName - the resource name + */ + public static String getLocalResource(String theName) { + try { + InputStream input; + input = Thread.currentThread().getContextClassLoader().getResourceAsStream(theName); + if (input == null) { + throw new RuntimeException("Can not find " + theName); + } + BufferedInputStream is = new BufferedInputStream(input); + StringBuilder buf = new StringBuilder(3000); + int i; + try { + while ((i = is.read()) != -1) { + buf.append((char) i); + } + } finally { + is.close(); + } + String resource = buf.toString(); + // convert EOLs + String[] lines = resource.split("\\r?\\n"); + StringBuilder buffer = new StringBuilder(); + for (int j = 0; j < lines.length; j++) { + buffer.append(lines[j]); + buffer.append("\n"); + } + return buffer.toString(); + } catch (IOException e) { + throw new RuntimeException(e); } - } finally { - is.close(); - } - String resource = buf.toString(); - // convert EOLs - String[] lines = resource.split("\\r?\\n"); - StringBuilder buffer = new StringBuilder(); - for (int j = 0; j < lines.length; j++) { - buffer.append(lines[j]); - buffer.append("\n"); - } - return buffer.toString(); - } catch (IOException e) { - throw new RuntimeException(e); } - } - public static Model getModel(String fileName) throws Exception { - YamlModelReader modelReader = new YamlModelReader(); - InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); - return modelReader.read(input, null); - } + public static Model getModel(String fileName) throws Exception { + YamlModelReader modelReader = new YamlModelReader(); + InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); + return modelReader.read(input, null); + } } diff --git a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/YamlModelReaderTest.java b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/YamlModelReaderTest.java index 8518383f..132f2b4a 100644 --- a/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/YamlModelReaderTest.java +++ b/polyglot-yaml/src/test/java/org/sonatype/maven/polyglot/yaml/YamlModelReaderTest.java @@ -7,6 +7,16 @@ */ package org.sonatype.maven.polyglot.yaml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URL; +import java.util.List; +import java.util.Properties; import org.apache.maven.model.Build; import org.apache.maven.model.CiManagement; import org.apache.maven.model.Contributor; @@ -24,151 +34,140 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URL; -import java.util.List; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class YamlModelReaderTest { - @Test - public void testModelCloning() throws Exception { - getModel().clone(); - } - - @Test - public void testModelReader() throws Exception { - Model model = getModel(); - assertNotNull(model); - - Parent parent = model.getParent(); - assertEquals("org.sonatype.maven", parent.getGroupId()); - assertEquals("maven-parent", parent.getArtifactId()); - assertEquals("1.0", parent.getVersion()); - - assertEquals("org.sonatype.raven", model.getGroupId()); - assertEquals("raven", model.getArtifactId()); - assertEquals("1.0-SNAPSHOT", model.getVersion()); - assertEquals("Raven", model.getName()); - - // Developers - List developers = model.getDevelopers(); - Developer dev0 = developers.get(0); - assertEquals("jvanzyl", dev0.getId()); - assertEquals("Jason van Zyl", dev0.getName()); - - // Contributors - List contributors = model.getContributors(); - Contributor con0 = contributors.get(0); - assertEquals("Will Price", con0.getName()); - - // DependencyManagement - List depManDependencies = model.getDependencyManagement().getDependencies(); - assertEquals(2, depManDependencies.size()); - - Dependency dmd0 = depManDependencies.get(0); - assertEquals("org.apache.maven", dmd0.getGroupId()); - assertEquals("maven-model-builder", dmd0.getArtifactId()); - assertEquals("3.0", dmd0.getVersion()); - - Dependency dmd1 = depManDependencies.get(1); - assertEquals("org.yaml", dmd1.getGroupId()); - assertEquals("snakeyaml", dmd1.getArtifactId()); - assertEquals("1.4", dmd1.getVersion()); - - // Dependencies - List dependencies = model.getDependencies(); - assertEquals(3, dependencies.size()); - - Dependency d0 = dependencies.get(0); - assertEquals("org.apache.maven", d0.getGroupId()); - assertEquals("maven-core", d0.getArtifactId()); - assertEquals("3.0", d0.getVersion()); - - Dependency d1 = dependencies.get(1); - assertEquals("org.yaml", d1.getGroupId()); - assertEquals("snakeyaml", d1.getArtifactId()); - assertEquals("1.4", d1.getVersion()); - - // Modules - List modules = model.getModules(); - assertEquals("reader", modules.get(0)); - assertEquals("writer", modules.get(1)); - assertEquals("shell-integration", modules.get(2)); - - // Build - Build build = model.getBuild(); - List plugins = build.getPlugins(); - assertEquals(1, plugins.size()); - Plugin p0 = plugins.get(0); - assertEquals("org.apache.maven.plugins", p0.getGroupId()); - assertEquals("maven-compiler-plugin", p0.getArtifactId()); - assertEquals("2.0.2", p0.getVersion()); - Xpp3Dom configuration = (Xpp3Dom) p0.getConfiguration(); - assertNotNull(configuration); - assertEquals(2, configuration.getChildCount()); - assertEquals("1.6", configuration.getChild("source").getValue()); - assertEquals("1.5", configuration.getChild("target").getValue()); - - // DistributionManagement - DistributionManagement distMan = model.getDistributionManagement(); - Site site = distMan.getSite(); - assertEquals("site", site.getId()); - assertEquals("http://www.apache.org", site.getUrl()); - DeploymentRepository releases = distMan.getRepository(); - assertEquals("releases", releases.getId()); - assertEquals("releases", releases.getName()); - assertEquals("http://maven.sonatype.org/releases", releases.getUrl()); - DeploymentRepository snapshots = distMan.getSnapshotRepository(); - assertEquals("snapshots", snapshots.getId()); - assertEquals("snapshots", snapshots.getName()); - assertEquals("http://maven.sonatype.org/snapshots", snapshots.getUrl()); - - // SCM - Scm scm = model.getScm(); - assertEquals("connection", scm.getConnection()); - assertEquals("developerConnection", scm.getDeveloperConnection()); - assertEquals("http://maven.sonatype.org/scm", scm.getUrl()); - - // IssueManagement - IssueManagement issueManagement = model.getIssueManagement(); - assertEquals("jira", issueManagement.getSystem()); - assertEquals("http://jira.codehaus.org/browse/MNG", issueManagement.getUrl()); - - // CiManagement - CiManagement ciManagement = model.getCiManagement(); - assertEquals("hudson", ciManagement.getSystem()); - assertEquals("http://grid.sonatype.org/ci", ciManagement.getUrl()); - - // Profiles - } - - @Test - public void testModelWriter() throws Exception { - StringWriter sw = new StringWriter(); - ModelWriter writer = new YamlModelWriter(); - Model model = getModel(); - Properties p = new Properties(); - p.setProperty("FOO", "BAR"); - model.setProperties(p); - writer.write(sw, null, model); - String output = sw.toString(); - //System.out.println(output); - assertTrue(output, output.contains("\nproperties: {FOO: BAR}\n")); - assertFalse(output, output.contains("extensions: []")); - assertFalse(output, output.contains("properties: {}")); - } - - protected Model getModel() throws Exception { - YamlModelReader modelReader = new YamlModelReader(); - URL url = getClass().getResource("test.yml"); - assertNotNull(url); - InputStream reader = url.openStream(); - return modelReader.read(reader, null); - } + @Test + public void testModelCloning() throws Exception { + getModel().clone(); + } + + @Test + public void testModelReader() throws Exception { + Model model = getModel(); + assertNotNull(model); + + Parent parent = model.getParent(); + assertEquals("org.sonatype.maven", parent.getGroupId()); + assertEquals("maven-parent", parent.getArtifactId()); + assertEquals("1.0", parent.getVersion()); + + assertEquals("org.sonatype.raven", model.getGroupId()); + assertEquals("raven", model.getArtifactId()); + assertEquals("1.0-SNAPSHOT", model.getVersion()); + assertEquals("Raven", model.getName()); + + // Developers + List developers = model.getDevelopers(); + Developer dev0 = developers.get(0); + assertEquals("jvanzyl", dev0.getId()); + assertEquals("Jason van Zyl", dev0.getName()); + + // Contributors + List contributors = model.getContributors(); + Contributor con0 = contributors.get(0); + assertEquals("Will Price", con0.getName()); + + // DependencyManagement + List depManDependencies = model.getDependencyManagement().getDependencies(); + assertEquals(2, depManDependencies.size()); + + Dependency dmd0 = depManDependencies.get(0); + assertEquals("org.apache.maven", dmd0.getGroupId()); + assertEquals("maven-model-builder", dmd0.getArtifactId()); + assertEquals("3.0", dmd0.getVersion()); + + Dependency dmd1 = depManDependencies.get(1); + assertEquals("org.yaml", dmd1.getGroupId()); + assertEquals("snakeyaml", dmd1.getArtifactId()); + assertEquals("1.4", dmd1.getVersion()); + + // Dependencies + List dependencies = model.getDependencies(); + assertEquals(3, dependencies.size()); + + Dependency d0 = dependencies.get(0); + assertEquals("org.apache.maven", d0.getGroupId()); + assertEquals("maven-core", d0.getArtifactId()); + assertEquals("3.0", d0.getVersion()); + + Dependency d1 = dependencies.get(1); + assertEquals("org.yaml", d1.getGroupId()); + assertEquals("snakeyaml", d1.getArtifactId()); + assertEquals("1.4", d1.getVersion()); + + // Modules + List modules = model.getModules(); + assertEquals("reader", modules.get(0)); + assertEquals("writer", modules.get(1)); + assertEquals("shell-integration", modules.get(2)); + + // Build + Build build = model.getBuild(); + List plugins = build.getPlugins(); + assertEquals(1, plugins.size()); + Plugin p0 = plugins.get(0); + assertEquals("org.apache.maven.plugins", p0.getGroupId()); + assertEquals("maven-compiler-plugin", p0.getArtifactId()); + assertEquals("2.0.2", p0.getVersion()); + Xpp3Dom configuration = (Xpp3Dom) p0.getConfiguration(); + assertNotNull(configuration); + assertEquals(2, configuration.getChildCount()); + assertEquals("1.6", configuration.getChild("source").getValue()); + assertEquals("1.5", configuration.getChild("target").getValue()); + + // DistributionManagement + DistributionManagement distMan = model.getDistributionManagement(); + Site site = distMan.getSite(); + assertEquals("site", site.getId()); + assertEquals("http://www.apache.org", site.getUrl()); + DeploymentRepository releases = distMan.getRepository(); + assertEquals("releases", releases.getId()); + assertEquals("releases", releases.getName()); + assertEquals("http://maven.sonatype.org/releases", releases.getUrl()); + DeploymentRepository snapshots = distMan.getSnapshotRepository(); + assertEquals("snapshots", snapshots.getId()); + assertEquals("snapshots", snapshots.getName()); + assertEquals("http://maven.sonatype.org/snapshots", snapshots.getUrl()); + + // SCM + Scm scm = model.getScm(); + assertEquals("connection", scm.getConnection()); + assertEquals("developerConnection", scm.getDeveloperConnection()); + assertEquals("http://maven.sonatype.org/scm", scm.getUrl()); + + // IssueManagement + IssueManagement issueManagement = model.getIssueManagement(); + assertEquals("jira", issueManagement.getSystem()); + assertEquals("http://jira.codehaus.org/browse/MNG", issueManagement.getUrl()); + + // CiManagement + CiManagement ciManagement = model.getCiManagement(); + assertEquals("hudson", ciManagement.getSystem()); + assertEquals("http://grid.sonatype.org/ci", ciManagement.getUrl()); + + // Profiles + } + + @Test + public void testModelWriter() throws Exception { + StringWriter sw = new StringWriter(); + ModelWriter writer = new YamlModelWriter(); + Model model = getModel(); + Properties p = new Properties(); + p.setProperty("FOO", "BAR"); + model.setProperties(p); + writer.write(sw, null, model); + String output = sw.toString(); + // System.out.println(output); + assertTrue(output, output.contains("\nproperties: {FOO: BAR}\n")); + assertFalse(output, output.contains("extensions: []")); + assertFalse(output, output.contains("properties: {}")); + } + + protected Model getModel() throws Exception { + YamlModelReader modelReader = new YamlModelReader(); + URL url = getClass().getResource("test.yml"); + assertNotNull(url); + InputStream reader = url.openStream(); + return modelReader.read(reader, null); + } } diff --git a/pom.xml b/pom.xml index b0ba91c5..9ec45b26 100644 --- a/pom.xml +++ b/pom.xml @@ -10,14 +10,14 @@ io.takari takari - 51 + 55 io.takari.polyglot polyglot 0.7.2-SNAPSHOT - Polyglot :: Aggregator pom + Polyglot :: Aggregator @@ -27,24 +27,6 @@ - - 3.9.5 - 0.9.0.M2 - 3.5.1 - - - 2.0.8 - 8 - ignore - - - - scm:git:git@github.com:takari/polyglot-maven.git - scm:git:git@github.com:takari/polyglot-maven.git - https://github.com/takari/polyglot-maven - HEAD - - polyglot-common polyglot-atom @@ -60,6 +42,24 @@ polyglot-translate-plugin + + scm:git:git@github.com:takari/polyglot-maven.git + scm:git:git@github.com:takari/polyglot-maven.git + HEAD + https://github.com/takari/polyglot-maven + + + + 3.9.5 + 0.9.0.M2 + 3.5.1 + + + 2.0.8 + 8 + ignore + + @@ -193,32 +193,6 @@ - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - - enforce - - validate - - true - - - [3.3.9,) - - - 1.8.0 - - - - - - - @@ -265,9 +239,58 @@ + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-maven + + enforce + + validate + + true + + + [8,) + + + [3.3.9,) + + + + + + + + + spotless-workaround + + (,1.8] + + + + + com.diffplug.spotless + spotless-maven-plugin + + + default + + ${spotless.action} + + none + + + + + + takari-release @@ -280,10 +303,10 @@ sign-artifacts - verify sign + verify