Skip to content

Commit

Permalink
Merge pull request #572 from cescoffier/features/improve-constant-in-…
Browse files Browse the repository at this point in the history
…maven-plugin

Some fixes in the maven plugin
  • Loading branch information
stuartwdouglas authored Jan 20, 2019
2 parents 42d849b + bf692d7 commit 727fbe1
Show file tree
Hide file tree
Showing 15 changed files with 176 additions and 135 deletions.
89 changes: 59 additions & 30 deletions maven/src/main/java/org/jboss/shamrock/maven/CreateProjectMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,19 @@

import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.*;
import org.apache.maven.model.Build;
import org.apache.maven.model.BuildBase;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.Profile;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
Expand All @@ -38,11 +46,14 @@
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static org.fusesource.jansi.Ansi.ansi;
import static org.jboss.shamrock.maven.utilities.MojoUtils.configuration;
import static org.jboss.shamrock.maven.utilities.MojoUtils.plugin;
import static org.jboss.shamrock.maven.utilities.MojoUtils.*;

/**
* This goal helps in setting up Shamrock Maven project with shamrock-maven-plugin, with sensible defaults
Expand All @@ -51,10 +62,11 @@
public class CreateProjectMojo extends AbstractMojo {

private static final String JAVA_EXTENSION = ".java";
public static final String VERSION_PROP = "shamrock-version";

public static final String PLUGIN_VERSION_PROPERTY_NAME = "shamrock.version";
public static final String PLUGIN_VERSION_PROPERTY = "${" + PLUGIN_VERSION_PROPERTY_NAME + "}";
public static final String PLUGIN_KEY = MavenConstants.PLUGIN_GROUPID + ":" + MavenConstants.PLUGIN_ARTIFACTID;

public static final String PLUGIN_KEY = getPluginGroupId() + ":" + getPluginArtifactId();

/**
* The Maven project which will define and configure the shamrock-maven-plugin
Expand Down Expand Up @@ -109,36 +121,56 @@ public void execute() throws MojoExecutionException {
File pomFile = project.getFile();

Model model;
//Create pom.xml if not
// Create pom.xml if not
if (pomFile == null || !pomFile.isFile()) {
pomFile = createPomFileFromUserInputs();
// The previous method has set project to the new created project.
createDirectories();
templates.generate(project, path, className, getLog());
printUserInstructions(pomFile);
return;
}

//We should get cloned of the OriginalModel, as project.getModel will return effective model
model = project.getOriginalModel().clone();

createDirectories();
templates.generate(project, path, className, getLog());
// There is an existing `pom.xml` file
Optional<Plugin> maybe = MojoUtils.hasPlugin(project, PLUGIN_KEY);
if (maybe.isPresent()) {
printUserInstructions(pomFile);
getLog().info("The " + getPluginArtifactId() + " is already configured in the existing pom.xml, " +
" nothing to do.");
return;
}

// The plugin is not configured, add it.
// We should get cloned of the original model, as project.getModel will return effective model
model = project.getOriginalModel().clone();

if (!isTypeSupported(model.getPackaging())) {
throw new MojoExecutionException("Unable to add " + getPluginArtifactId() + " to the existing pom.xml " +
"file - unsupported project type: " + model.getPackaging());
}

// Ensure we don't have the project metadata provided by the user
if (projectArtifactId != null || projectGroupId != null) {
throw new MojoExecutionException("Unable to add " + getPluginArtifactId() + " to the existing pom.xml " +
"file - you can't provide project GAV and extend an existing pom.xml");
}

addVersionProperty(model);
addBom(model);
addMainPluginConfig(model);
ext.addExtensions(model, extensions, session, repositories, getLog());
addNativeProfile(model);
createDirectories();
save(pomFile, model);
}

private boolean isTypeSupported(String packaging) {
return packaging == null || packaging.equalsIgnoreCase("jar");
}

private void addBom(Model model) {
Dependency bom = new Dependency();
bom.setArtifactId(MojoUtils.get("bom-artifactId"));
bom.setGroupId(MavenConstants.PLUGIN_GROUPID);
bom.setVersion("${shamrock.version}");
bom.setGroupId(getPluginGroupId());
bom.setVersion("${shamrock.version}"); // Use the variable.
bom.setType("pom");
bom.setScope("import");

Expand All @@ -164,7 +196,7 @@ private void addNativeProfile(Model model) {
Profile profile = new Profile();
profile.setId("native");
BuildBase buildBase = new BuildBase();
Plugin plg = plugin(MavenConstants.PLUGIN_GROUPID, MavenConstants.PLUGIN_ARTIFACTID, PLUGIN_VERSION_PROPERTY);
Plugin plg = plugin(getPluginGroupId(), getPluginArtifactId(), PLUGIN_VERSION_PROPERTY);
PluginExecution exec = new PluginExecution();
exec.addGoal("native-image");
MojoUtils.Element element = new MojoUtils.Element("enableHttpUrlHandler", "true");
Expand All @@ -176,13 +208,13 @@ private void addNativeProfile(Model model) {
}

private void addMainPluginConfig(Model model) {
Plugin plugin = plugin(MavenConstants.PLUGIN_GROUPID, MavenConstants.PLUGIN_ARTIFACTID, PLUGIN_VERSION_PROPERTY);
Plugin plugin = plugin(getPluginGroupId(), getPluginArtifactId(), getPluginVersion());
if (isParentPom(model)) {
addPluginManagementSection(model, plugin);
//strip the shamrockVersion off
plugin = plugin(MavenConstants.PLUGIN_GROUPID, MavenConstants.PLUGIN_ARTIFACTID);
plugin = plugin(getPluginGroupId(), getPluginArtifactId());
} else {
plugin = plugin(MavenConstants.PLUGIN_GROUPID, MavenConstants.PLUGIN_ARTIFACTID, PLUGIN_VERSION_PROPERTY);
plugin = plugin(getPluginGroupId(), getPluginArtifactId(), PLUGIN_VERSION_PROPERTY);
}
PluginExecution pluginExec = new PluginExecution();
pluginExec.addGoal("build");
Expand All @@ -193,7 +225,7 @@ private void addMainPluginConfig(Model model) {

private void addVersionProperty(Model model) {
//Set a property at maven project level for Shamrock maven plugin versions
shamrockVersion = shamrockVersion == null ? MojoUtils.get(VERSION_PROP) : shamrockVersion;
shamrockVersion = shamrockVersion == null ? getPluginVersion() : shamrockVersion;
model.getProperties().putIfAbsent(PLUGIN_VERSION_PROPERTY_NAME, shamrockVersion);
}

Expand Down Expand Up @@ -240,7 +272,7 @@ private File createPomFileFromUserInputs() throws MojoExecutionException {
// Ask for maven version if not set
if (shamrockVersion == null) {
shamrockVersion = prompter.promptWithDefaultValue("Set the Shamrock version",
MojoUtils.get(VERSION_PROP));
getPluginVersion());
}

if (className == null) {
Expand Down Expand Up @@ -277,14 +309,11 @@ private File createPomFileFromUserInputs() throws MojoExecutionException {


Map<String, String> context = new HashMap<>();
context.put("mProjectGroupId", projectGroupId);
context.put("mProjectArtifactId", projectArtifactId);
context.put("mProjectVersion", projectVersion);
context.put("shamrockVersion", shamrockVersion != null ? shamrockVersion : MojoUtils.get(VERSION_PROP));
context.put("restAssuredVersion", MojoUtils.get("restAssuredVersion"));
context.put("docRoot", MojoUtils.get("doc-root"));

context.put("className", className);
context.put("project_groupId", projectGroupId);
context.put("project_artifactId", projectArtifactId);
context.put("project_version", projectVersion);
context.put("shamrock_version", shamrockVersion != null ? shamrockVersion : getPluginVersion());
context.put("class_name", className);
context.put("path", path);

templates.createNewProjectPomFile(context, pomFile);
Expand Down
9 changes: 6 additions & 3 deletions maven/src/main/java/org/jboss/shamrock/maven/DevMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.jboss.shamrock.dev.DevModeMain;
import org.jboss.shamrock.maven.utilities.MojoUtils;

/**
* The dev mojo, that runs a shamrock app in a forked process
Expand Down Expand Up @@ -115,8 +116,8 @@ public void execute() throws MojoFailureException {

boolean found = false;
for(Plugin i : project.getBuildPlugins()) {
if(i.getGroupId().equals(MavenConstants.PLUGIN_GROUPID)
&& i.getArtifactId().equals(MavenConstants.PLUGIN_ARTIFACTID)) {
if(i.getGroupId().equals(MojoUtils.getPluginGroupId())
&& i.getArtifactId().equals(MojoUtils.getPluginArtifactId())) {
for(PluginExecution p : i.getExecutions()) {
if(p.getGoals().contains("build")) {
found = true;
Expand All @@ -126,7 +127,9 @@ public void execute() throws MojoFailureException {
}
}
if(!found) {
getLog().warn("The shamrock-maven-plugin build goal was not configured for this project, skipping shamrock:dev as this is assumed to be a support library. If you want to run shamrock dev on this project make sure the shamrock-maven-plugin is configured with a build goal.");
getLog().warn("The shamrock-maven-plugin build goal was not configured for this project, " +
"skipping shamrock:dev as this is assumed to be a support library. If you want to run shamrock dev" +
" on this project make sure the shamrock-maven-plugin is configured with a build goal.");
return;
}

Expand Down
27 changes: 0 additions & 27 deletions maven/src/main/java/org/jboss/shamrock/maven/MavenConstants.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Component;
import org.jboss.shamrock.maven.utilities.MojoUtils;

import java.io.File;
import java.io.FileWriter;
Expand All @@ -33,11 +34,15 @@
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* Prompt implementation.
*
* <strong>Important:</strong> All variable named injected in the templates uses `_` as word separator. Indeed,
* FreeMarker does not support `-` as it interprets it as "minus".
*
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
@Component(role = SetupTemplates.class, instantiationStrategy = "singleton")
Expand All @@ -46,21 +51,33 @@ public class SetupTemplates {
private static final Configuration cfg;
private static final String JAVA_EXTENSION = ".java";

private Map<String, String> getDefaultContext() {
Map<String, String> context = new LinkedHashMap<>();
MojoUtils.getAllProperties().forEach((k, v) -> context.put(k.replace("-", "_"), v));
return context;
}

static {
cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setTemplateLoader(new ClassTemplateLoader(SetupTemplates.class, "/"));
}

public void createNewProjectPomFile(Map<String, String> context, File pomFile) throws MojoExecutionException {
Map<String, String> ctx = merge(getDefaultContext(), context);
try {
Template temp = cfg.getTemplate("templates/pom-template.ftl");
Writer out = new FileWriter(pomFile);
temp.process(context, out);
temp.process(ctx, out);
} catch (Exception e) {
throw new MojoExecutionException("Unable to generate pom.xml", e);
}
}

private Map<String, String> merge(Map<String, String> context, Map<String, String> toMerge) {
context.putAll(toMerge);
return context;
}

public void generate(MavenProject project, String path, String className, Log log) throws MojoExecutionException {
if (Strings.isNullOrEmpty(className)) {
return;
Expand Down Expand Up @@ -91,10 +108,10 @@ public void generate(MavenProject project, String path, String className, Log lo
File classFile = new File(root, className + JAVA_EXTENSION);
File testClassFile = new File(testRoot, className + "Test" + JAVA_EXTENSION);
Map<String, String> context = new HashMap<>();
context.put("classname", className);
context.put("class_name", className);
context.put("path", path);
if (packageName != null) {
context.put("packageName", packageName);
context.put("package_name", packageName);
}
try {
Template temp = cfg.getTemplate("templates/resource-template.ftl");
Expand All @@ -115,13 +132,14 @@ public void generate(MavenProject project, String path, String className, Log lo
}

public void createIndexPage(Map<String, String> context, File basedir, Log log) throws MojoExecutionException {
Map<String, String> ctx = merge(getDefaultContext(), context);
// Generate index page
File resources = new File(basedir, "src/main/resources/META-INF/resources");
File index = new File(mkdirs(resources, log), "index.html");
if (!index.exists()) {
try (Writer out = new FileWriter(index)) {
Template temp = cfg.getTemplate("templates/index.ftl");
temp.process(context, out);
temp.process(ctx, out);
log.info("Welcome page created in src/main/resources/META-INF/resources/" + index.getName());
} catch (Exception e) {
throw new MojoExecutionException("Unable to generate the welcome page", e);
Expand All @@ -131,12 +149,13 @@ public void createIndexPage(Map<String, String> context, File basedir, Log log)
}

public void createDockerFile(Map<String, String> context, File basedir, Log log) throws MojoExecutionException {
Map<String, String> ctx = merge(getDefaultContext(), context);
File dockerRoot = new File(basedir, "src/main/docker");
File docker = new File(mkdirs(dockerRoot, log), "Dockerfile");
try {
Template temp = cfg.getTemplate("templates/dockerfile.ftl");
Writer out = new FileWriter(docker);
temp.process(context, out);
temp.process(ctx, out);
} catch (Exception e) {
throw new MojoExecutionException("Unable to generate the docker file", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
import java.util.List;
import java.util.Optional;

import static org.jboss.shamrock.maven.MavenConstants.PLUGIN_GROUPID;

/**
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
Expand Down Expand Up @@ -98,8 +96,7 @@ public Dependency parse(String dependency, Log log) {
}

private List<Dependency> getDependenciesFromBom(MavenSession session, List<ArtifactRepository> repositories) throws MojoExecutionException {
String bomCoordinates = PLUGIN_GROUPID + ":" + MojoUtils.get("bom-artifactId") + ":"
+ MojoUtils.get("shamrock-version");
String bomCoordinates = MojoUtils.getPluginGroupId() + ":" + MojoUtils.get("bom-artifactId") + ":" + MojoUtils.getPluginVersion();
MavenProject bom = getMavenProject(bomCoordinates, session, repositories);
return bom.getDependencyManagement().getDependencies();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ private MojoUtils() {
// Avoid direct instantiation
}

public static String getPluginArtifactId() {
return get("plugin-artifactId");
}

public static String getPluginGroupId() {
return get("plugin-groupId");
}

public static String getPluginVersion() {
return get("plugin-version");
}

/**
* Checks whether or not the given project has a plugin with the given key. The key is given using the
* "groupId:artifactId" syntax.
Expand Down Expand Up @@ -149,6 +161,12 @@ public static Plugin plugin(String groupId, String artifactId, String version, L
return plugin;
}

public static Map<String, String> getAllProperties() {
Map<String, String> all = new HashMap<>();
properties.stringPropertyNames().forEach(s -> all.put(s, properties.getProperty(s)));
return all;
}

/**
* Element wrapper class for configuration elements
*/
Expand Down
Loading

0 comments on commit 727fbe1

Please sign in to comment.