diff --git a/core/src/main/java/io/fabric8/maven/core/extenvvar/ExternalEnvVarHandler.java b/core/src/main/java/io/fabric8/maven/core/extenvvar/ExternalEnvVarHandler.java index 5869c86010..16595af91b 100644 --- a/core/src/main/java/io/fabric8/maven/core/extenvvar/ExternalEnvVarHandler.java +++ b/core/src/main/java/io/fabric8/maven/core/extenvvar/ExternalEnvVarHandler.java @@ -18,6 +18,7 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; @@ -35,17 +36,17 @@ public class ExternalEnvVarHandler { public static final String ENVIRONMENT_SCHEMA_FILE = "io/fabric8/environment/schema.json"; private static ObjectMapper objectMapper = createObjectMapper(); - public static Map getExportedEnvironmentVariables(MavenProject project, Map envVars) { - Map ret = getEnvironmentVarsFromJsonSchema(project, envVars); + public static Map getExportedEnvironmentVariables(URLClassLoader compileClassloader, String outputDirectory, Map envVars) { + Map ret = getEnvironmentVarsFromJsonSchema(compileClassloader, outputDirectory, envVars); ret.putAll(envVars); return ret; } // ================================================================================================== - private static Map getEnvironmentVarsFromJsonSchema(MavenProject project, Map envVars) { + private static Map getEnvironmentVarsFromJsonSchema(URLClassLoader compileClassloader, String outputDirectory, Map envVars) { Map ret = new TreeMap<>(); - JsonSchema schema = getEnvironmentVariableJsonSchema(project, envVars); + JsonSchema schema = getEnvironmentVariableJsonSchema(compileClassloader, outputDirectory, envVars); Map properties = schema.getProperties(); Set> entries = properties.entrySet(); for (Map.Entry entry : entries) { @@ -56,10 +57,10 @@ private static Map getEnvironmentVarsFromJsonSchema(MavenProject return ret; } - private static JsonSchema getEnvironmentVariableJsonSchema(MavenProject project, Map envVars) { + private static JsonSchema getEnvironmentVariableJsonSchema(URLClassLoader compileClassloader, String outputDirectory, Map envVars) { try { - JsonSchema schema = ExternalEnvVarHandler.loadEnvironmentSchemas(MavenUtil.getCompileClassLoader(project), - project.getBuild().getOutputDirectory()); + JsonSchema schema = ExternalEnvVarHandler.loadEnvironmentSchemas(compileClassloader, + outputDirectory); if (schema == null) { schema = new JsonSchema(); } diff --git a/core/src/main/java/io/fabric8/maven/core/handler/ContainerHandler.java b/core/src/main/java/io/fabric8/maven/core/handler/ContainerHandler.java index 4dada46e25..1dda0734f7 100644 --- a/core/src/main/java/io/fabric8/maven/core/handler/ContainerHandler.java +++ b/core/src/main/java/io/fabric8/maven/core/handler/ContainerHandler.java @@ -15,10 +15,6 @@ */ package io.fabric8.maven.core.handler; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerBuilder; import io.fabric8.kubernetes.api.model.ContainerPort; @@ -30,14 +26,17 @@ import io.fabric8.kubernetes.api.model.VolumeMountBuilder; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.config.VolumeConfig; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.maven.docker.access.PortMapping; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.docker.util.EnvUtil; import io.fabric8.maven.docker.util.ImageName; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.project.MavenProject; import org.json.JSONArray; import org.json.JSONObject; @@ -49,12 +48,14 @@ class ContainerHandler { private final EnvVarHandler envVarHandler; private final ProbeHandler probeHandler; - private final MavenProject project; + private final Properties configurationProperties; + private final Artifact artifact; - public ContainerHandler(MavenProject project, EnvVarHandler envVarHandler, ProbeHandler probeHandler) { + public ContainerHandler(Properties configurationProperties, Artifact artifact, EnvVarHandler envVarHandler, ProbeHandler probeHandler) { this.envVarHandler = envVarHandler; this.probeHandler = probeHandler; - this.project = project; + this.configurationProperties = configurationProperties; + this.artifact = artifact; } List getContainers(ResourceConfig config, List images) { @@ -66,7 +67,7 @@ List getContainers(ResourceConfig config, List im Probe readinessProbe = probeHandler.getProbe(config.getReadiness()); Container container = new ContainerBuilder() - .withName(KubernetesResourceUtil.extractContainerName(project, imageConfig)) + .withName(KubernetesResourceUtil.extractContainerName(this.artifact, imageConfig)) .withImage(getImageName(imageConfig)) .withImagePullPolicy(getImagePullPolicy(config)) .withEnv(envVarHandler.getEnvironmentVariables(config.getEnv())) @@ -85,9 +86,8 @@ List getContainers(ResourceConfig config, List im private String getImagePullPolicy(ResourceConfig config) { String pullPolicy = config.getImagePullPolicy(); - String version = project.getVersion(); if (StringUtils.isBlank(pullPolicy) && - version != null && version.endsWith("SNAPSHOT")) { + this.artifact.getVersion() != null && this.artifact.getVersion().endsWith("SNAPSHOT")) { // TODO: Is that what we want ? return "PullAlways"; } @@ -98,7 +98,7 @@ private String getImageName(ImageConfiguration imageConfiguration) { if (StringUtils.isBlank(imageConfiguration.getName())) { return null; } - Properties props = EnvUtil.getPropertiesWithSystemOverrides(project); + Properties props = getPropertiesWithSystemOverrides(this.configurationProperties); String configuredRegistry = EnvUtil.fistRegistryOf( imageConfiguration.getRegistry(), props.getProperty("docker.pull.registry"), @@ -107,6 +107,16 @@ private String getImageName(ImageConfiguration imageConfiguration) { return new ImageName(imageConfiguration.getName()).getFullName(configuredRegistry); } + private Properties getPropertiesWithSystemOverrides(Properties configurationProperties) { + + if (configurationProperties == null) { + configurationProperties = new Properties(); + } + + configurationProperties.putAll(System.getProperties()); + return configurationProperties; + } + private SecurityContext createSecurityContext(ResourceConfig config) { return new SecurityContextBuilder() .withPrivileged(config.isContainerPrivileged()) @@ -139,7 +149,7 @@ private List getContainerPorts(ImageConfiguration imageConfig) { List ports = buildConfig.getPorts(); if (!ports.isEmpty()) { List ret = new ArrayList<>(); - PortMapping portMapping = new PortMapping(ports, project.getProperties()); + PortMapping portMapping = new PortMapping(ports, configurationProperties); JSONArray portSpecs = portMapping.toJson(); for (int i = 0; i < portSpecs.length(); i ++) { JSONObject portSpec = portSpecs.getJSONObject(i); diff --git a/core/src/main/java/io/fabric8/maven/core/handler/EnvVarHandler.java b/core/src/main/java/io/fabric8/maven/core/handler/EnvVarHandler.java index 6485da00f4..558eb2ad1b 100644 --- a/core/src/main/java/io/fabric8/maven/core/handler/EnvVarHandler.java +++ b/core/src/main/java/io/fabric8/maven/core/handler/EnvVarHandler.java @@ -15,33 +15,34 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.kubernetes.api.model.EnvVar; +import io.fabric8.kubernetes.api.model.EnvVarBuilder; +import io.fabric8.maven.core.extenvvar.ExternalEnvVarHandler; +import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import io.fabric8.kubernetes.api.model.EnvVar; -import io.fabric8.kubernetes.api.model.EnvVarBuilder; -import io.fabric8.maven.core.extenvvar.ExternalEnvVarHandler; -import org.apache.maven.project.MavenProject; - /** * @author roland * @since 08/04/16 */ class EnvVarHandler { - private MavenProject project; + private URLClassLoader urlClassLoader; + private String outputDirectory; - EnvVarHandler(MavenProject project) { - this.project = project; + EnvVarHandler(URLClassLoader compileClassloader, String outputDirectory) { + this.urlClassLoader = compileClassloader; + this.outputDirectory = outputDirectory; } List getEnvironmentVariables(Map envVars) { List ret = new ArrayList<>(); - Map envs = ExternalEnvVarHandler.getExportedEnvironmentVariables(project, envVars); + Map envs = ExternalEnvVarHandler.getExportedEnvironmentVariables(this.urlClassLoader, this.outputDirectory, envVars); Map envMap = convertToEnvVarMap(envs); ret.addAll(envMap.values()); diff --git a/core/src/main/java/io/fabric8/maven/core/handler/HandlerHub.java b/core/src/main/java/io/fabric8/maven/core/handler/HandlerHub.java index 3d886f774e..6a5d4f0d6e 100644 --- a/core/src/main/java/io/fabric8/maven/core/handler/HandlerHub.java +++ b/core/src/main/java/io/fabric8/maven/core/handler/HandlerHub.java @@ -15,7 +15,9 @@ */ package io.fabric8.maven.core.handler; -import org.apache.maven.project.MavenProject; +import io.fabric8.maven.core.model.Artifact; +import java.net.URLClassLoader; +import java.util.Properties; /** * @author roland @@ -31,10 +33,10 @@ public class HandlerHub { private final DaemonSetHandler daemonSetHandler; private final JobHandler jobHandler; - public HandlerHub(MavenProject project) { + public HandlerHub(URLClassLoader compileClassloader, String outputDirectory, Artifact artifact, Properties configuration) { ProbeHandler probeHandler = new ProbeHandler(); - EnvVarHandler envVarHandler = new EnvVarHandler(project); - ContainerHandler containerHandler = new ContainerHandler(project, envVarHandler, probeHandler); + EnvVarHandler envVarHandler = new EnvVarHandler(compileClassloader, outputDirectory); + ContainerHandler containerHandler = new ContainerHandler(configuration, artifact, envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); deploymentHandler = new DeploymentHandler(podTemplateHandler); diff --git a/core/src/main/java/io/fabric8/maven/core/model/Artifact.java b/core/src/main/java/io/fabric8/maven/core/model/Artifact.java new file mode 100644 index 0000000000..1288034b7b --- /dev/null +++ b/core/src/main/java/io/fabric8/maven/core/model/Artifact.java @@ -0,0 +1,36 @@ +package io.fabric8.maven.core.model; + +public class Artifact { + + private String groupId; + private String artifactId; + private String version; + + public Artifact() { + this("unknown", "empty-project", "0"); + } + + public Artifact(String version) { + this(); + this.version = version; + } + + public Artifact(String groupId, String artifactId, String version) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + } + + public String getGroupId() { + return groupId; + } + + public String getArtifactId() { + return artifactId; + } + + public String getVersion() { + return version; + } + +} diff --git a/core/src/main/java/io/fabric8/maven/core/util/ClassUtil.java b/core/src/main/java/io/fabric8/maven/core/util/ClassUtil.java index 752fe5a4ef..cfc01f4329 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/ClassUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/ClassUtil.java @@ -180,13 +180,13 @@ private static String convertToClass(String name, String prefix) { } - public static URLClassLoader createProjectClassLoader(final MavenProject project, Logger log) { + public static URLClassLoader createProjectClassLoader(List elements, Logger log) { try { List compileJars = new ArrayList<>(); - for (String element : project.getCompileClasspathElements()) { + for (String element : elements) { compileJars.add(new File(element).toURI().toURL()); } diff --git a/core/src/main/java/io/fabric8/maven/core/util/DockerServerUtil.java b/core/src/main/java/io/fabric8/maven/core/util/DockerServerUtil.java index 3e516a80f8..6bb86092cd 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/DockerServerUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/DockerServerUtil.java @@ -15,57 +15,28 @@ */ package io.fabric8.maven.core.util; -import java.util.HashMap; import java.util.Map; - import org.apache.commons.lang3.StringUtils; -import org.apache.maven.settings.Server; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.util.xml.Xpp3Dom; import org.json.JSONObject; public class DockerServerUtil { - public static Server getServer(final Settings settings, final String serverId) { - if (settings == null || StringUtils.isBlank(serverId)) { - return null; - } - return settings.getServer(serverId); - } - public static String getDockerJsonConfigString(final Settings settings, final String serverId) { - Server server = getServer(settings, serverId); - if (server == null) { - return new String(); + public static final String EMAIL = "email"; + + public static String getDockerJsonConfigString(final String serverId, final Map auth) { + + if (auth == null || auth.isEmpty()) { + return ""; } - Map auth = new HashMap(); - auth.put("username", server.getUsername()); - auth.put("password", server.getPassword()); - String mail = getConfigurationValue(server, "email"); - if (StringUtils.isBlank(mail)) { - mail = "foo@foo.com"; + if (!auth.containsKey(EMAIL) || StringUtils.isBlank(auth.get(EMAIL))) { + auth.put(EMAIL, "foo@foo.com"); } - auth.put("email", mail); JSONObject json = new JSONObject() .put(serverId, auth); return json.toString(); } - private static String getConfigurationValue(final Server server, final String key) { - - final Xpp3Dom configuration = (Xpp3Dom) server.getConfiguration(); - if (configuration == null) { - return null; - } - - final Xpp3Dom node = configuration.getChild(key); - if (node == null) { - return null; - } - - return node.getValue(); - } - } diff --git a/core/src/main/java/io/fabric8/maven/core/util/GitUtil.java b/core/src/main/java/io/fabric8/maven/core/util/GitUtil.java index 26ca506aa9..c1deda2b65 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/GitUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/GitUtil.java @@ -32,17 +32,13 @@ public class GitUtil { - public static Repository getGitRepository(MavenProject project) throws IOException { - MavenProject rootProject = MavenUtil.getRootProject(project); - File baseDir = rootProject.getBasedir(); - if (baseDir == null) { - baseDir = project.getBasedir(); - } - if (baseDir == null) { + public static Repository getGitRepository(File currentDir) throws IOException { + + if (currentDir == null) { // TODO: Why is this check needed ? - baseDir = new File(System.getProperty("basedir", ".")); + currentDir = new File(System.getProperty("basedir", ".")); } - File gitFolder = findGitFolder(baseDir); + File gitFolder = findGitFolder(currentDir); if (gitFolder == null) { // No git repository found return null; diff --git a/core/src/main/java/io/fabric8/maven/core/util/MavenUtil.java b/core/src/main/java/io/fabric8/maven/core/util/MavenUtil.java index ccb82eb19d..ca80ff220d 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/MavenUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/MavenUtil.java @@ -85,9 +85,9 @@ public static URLClassLoader getTestClassLoader(MavenProject project) { } } - public static String createDefaultResourceName(MavenProject project, String ... suffixes) { + public static String createDefaultResourceName(String artifactId, String ... suffixes) { String suffix = StringUtils.join(suffixes, "-"); - String ret = project.getArtifactId() + (suffix.length() > 0 ? "-" + suffix : ""); + String ret = artifactId + (suffix.length() > 0 ? "-" + suffix : ""); if (ret.length() > 63) { ret = ret.substring(0,63); } diff --git a/core/src/main/java/io/fabric8/maven/core/util/SpringBootUtil.java b/core/src/main/java/io/fabric8/maven/core/util/SpringBootUtil.java index d208e8574c..68d9022f8e 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/SpringBootUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/SpringBootUtil.java @@ -42,8 +42,7 @@ public class SpringBootUtil { * Returns the spring boot configuration (supports `application.properties` and `application.yml`) * or an empty properties object if not found */ - public static Properties getSpringBootApplicationProperties(MavenProject project) { - URLClassLoader compileClassLoader = MavenUtil.getCompileClassLoader(project); + public static Properties getSpringBootApplicationProperties(URLClassLoader compileClassLoader) { URL ymlResource = compileClassLoader.findResource("application.yml"); URL propertiesResource = compileClassLoader.findResource("application.properties"); diff --git a/core/src/main/java/io/fabric8/maven/core/util/kubernetes/KubernetesResourceUtil.java b/core/src/main/java/io/fabric8/maven/core/util/kubernetes/KubernetesResourceUtil.java index c772ebcc11..b359546f15 100644 --- a/core/src/main/java/io/fabric8/maven/core/util/kubernetes/KubernetesResourceUtil.java +++ b/core/src/main/java/io/fabric8/maven/core/util/kubernetes/KubernetesResourceUtil.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.util.kubernetes; +import io.fabric8.maven.core.model.Artifact; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; @@ -324,15 +325,15 @@ public static String getNameWithSuffix(String name, String kind) { return suffix != null ? name + "-" + suffix : name; } - public static String extractContainerName(MavenProject project, ImageConfiguration imageConfig) { + public static String extractContainerName(Artifact artifact, ImageConfiguration imageConfig) { String alias = imageConfig.getAlias(); - return alias != null ? alias : extractImageUser(imageConfig.getName(), project) + "-" + project.getArtifactId(); + return alias != null ? alias : extractImageUser(imageConfig.getName(), artifact.getGroupId()) + "-" + artifact.getArtifactId(); } - private static String extractImageUser(String image, MavenProject project) { + private static String extractImageUser(String image, String groupId) { ImageName name = new ImageName(image); String imageUser = name.getUser(); - String projectGroupId = project.getGroupId(); + String projectGroupId = groupId; if(imageUser != null) { return imageUser; } else { diff --git a/core/src/test/java/io/fabric8/maven/core/handler/ContainerHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/ContainerHandlerTest.java index fdb6b1b17e..792a6d6c2c 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/ContainerHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/ContainerHandlerTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.maven.core.model.Artifact; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -91,7 +92,7 @@ public void getContainersWithAliasTest() { tags.add("latest"); tags.add("test"); - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact("test-group", "test-artifact", "0"), envVarHandler, probeHandler); //container name with alias BuildImageConfiguration buildImageConfiguration = new BuildImageConfiguration.Builder(). @@ -155,7 +156,7 @@ public void registryHandling() { } testProject.getModel().setProperties(testProps); - ContainerHandler handler = new ContainerHandler(testProject, + ContainerHandler handler = new ContainerHandler(testProject.getProperties(), new Artifact(), envVarHandler, probeHandler); @@ -189,7 +190,7 @@ public void getContainerWithGroupArtifactTest() { tags.add("latest"); tags.add("test"); - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact("test-group", "test-artifact", "0"), envVarHandler, probeHandler); //container name with group id and aritact id without alias and user BuildImageConfiguration buildImageConfiguration = new BuildImageConfiguration.Builder(). ports(ports).from("fabric8/").cleanup("try").tags(tags) @@ -219,7 +220,7 @@ public void getContainerTestWithUser(){ tags.add("test"); //container name with user and image with tag - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact("test-group", "test-artifact", "0"), envVarHandler, probeHandler); BuildImageConfiguration buildImageConfiguration = new BuildImageConfiguration.Builder(). ports(ports).from("fabric8/").cleanup("try").tags(tags) @@ -250,8 +251,8 @@ public void imagePullPolicyWithPolicySetTest() { project2.setVersion("3.5-NEW"); //creating container Handler for all - ContainerHandler handler1 = new ContainerHandler(project1, envVarHandler, probeHandler); - ContainerHandler handler2 = new ContainerHandler(project2, envVarHandler, probeHandler); + ContainerHandler handler1 = new ContainerHandler(project1.getProperties(), new Artifact("3.5-SNAPSHOT"), envVarHandler, probeHandler); + ContainerHandler handler2 = new ContainerHandler(project2.getProperties(), new Artifact("3.5-NEW"), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -272,11 +273,11 @@ public void imagePullPolicyWithoutPolicySetTest(){ project2.setVersion("3.5-NEW"); //creating container Handler for two - ContainerHandler handler1 = new ContainerHandler(project1, envVarHandler, probeHandler); - ContainerHandler handler2 = new ContainerHandler(project2, envVarHandler, probeHandler); + ContainerHandler handler1 = new ContainerHandler(project1.getProperties(), new Artifact("3.5-SNAPSHOT"), envVarHandler, probeHandler); + ContainerHandler handler2 = new ContainerHandler(project2.getProperties(), new Artifact("3.5-NEW"), envVarHandler, probeHandler); //project without version - ContainerHandler handler3 = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler3 = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -299,7 +300,7 @@ public void imagePullPolicyWithoutPolicySetTest(){ @Test public void getImageNameTest(){ - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); //Image Configuration with name and without registry ImageConfiguration imageConfiguration2 = new ImageConfiguration.Builder(). @@ -329,7 +330,7 @@ public void getImageNameTest(){ @Test public void getRegistryTest() { - ContainerHandler handler = new ContainerHandler(project1, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project1.getProperties(), new Artifact(), envVarHandler, probeHandler); ImageConfiguration imageConfig = new ImageConfiguration.Builder(). name("test").alias("test-app").buildConfig(buildImageConfiguration1).build(); @@ -346,7 +347,7 @@ public void getRegistryTest() { @Test public void getVolumeMountWithoutMountTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -362,7 +363,7 @@ public void getVolumeMountWithoutMountTest() { @Test public void getVolumeMountWithoutNameTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -384,7 +385,7 @@ public void getVolumeMountWithoutNameTest() { @Test public void getVolumeMountWithNameAndMountTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); List mounts = new ArrayList<>(); mounts.add("/path/etc"); @@ -405,7 +406,7 @@ public void getVolumeMountWithNameAndMountTest() { @Test public void getVolumeMountWithMultipleMountTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -428,7 +429,7 @@ public void getVolumeMountWithMultipleMountTest() { @Test public void getVolumeMountWithEmptyVolumeTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -441,7 +442,7 @@ public void getVolumeMountWithEmptyVolumeTest() { @Test public void containerEmptyPortsTest() { - ContainerHandler handler = new ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(),new Artifact(), envVarHandler, probeHandler); images.clear(); images.add(imageConfiguration1); @@ -454,7 +455,7 @@ public void containerEmptyPortsTest() { @Test public void containerPortsWithoutPortTest() { - ContainerHandler handler = new ContainerHandler(project,envVarHandler,probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler,probeHandler); //without Ports BuildImageConfiguration buildImageConfiguration2 = new BuildImageConfiguration.Builder(). @@ -492,7 +493,7 @@ public void containerPortsWithDifferentPortTest(){ images.clear(); images.add(imageConfiguration1); - ContainerHandler handler = new ContainerHandler(project,envVarHandler,probeHandler); + ContainerHandler handler = new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); containers = handler.getContainers(config, images); List outputports = containers.get(0).getPorts(); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/DaemonSetHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/DaemonSetHandlerTest.java index 40900ec01c..b152b7fdcd 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/DaemonSetHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/DaemonSetHandlerTest.java @@ -15,14 +15,14 @@ */ package io.fabric8.maven.core.handler; -import java.util.ArrayList; -import java.util.List; - import io.fabric8.kubernetes.api.model.apps.DaemonSet; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.config.VolumeConfig; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; +import java.util.ArrayList; +import java.util.List; import mockit.Mocked; import org.apache.maven.project.MavenProject; import org.junit.Before; @@ -83,7 +83,7 @@ public void before(){ @Test public void daemonTemplateHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -118,7 +118,7 @@ public void daemonTemplateHandlerTest() { public void daemonTemplateHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -139,7 +139,7 @@ public void daemonTemplateHandlerWithInvalidNameTest() { public void daemonTemplateHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/DeploymentHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/DeploymentHandlerTest.java index 8639a8eb71..085b38281d 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/DeploymentHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/DeploymentHandlerTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.maven.core.model.Artifact; import java.util.ArrayList; import java.util.List; @@ -84,7 +85,7 @@ public void before(){ public void deploymentTemplateHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -121,7 +122,7 @@ public void deploymentTemplateHandlerTest() { public void deploymentTemplateHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -143,7 +144,7 @@ public void deploymentTemplateHandlerWithInvalidNameTest() { public void deploymentTemplateHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = new - ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/EnvVarHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/EnvVarHandlerTest.java index 559ef5ddf1..cef279c3fc 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/EnvVarHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/EnvVarHandlerTest.java @@ -15,13 +15,13 @@ */ package io.fabric8.maven.core.handler; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.EnvVarBuilder; import io.fabric8.maven.core.extenvvar.ExternalEnvVarHandler; +import io.fabric8.maven.core.util.MavenUtil; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import mockit.Expectations; import mockit.Mocked; import org.apache.maven.project.MavenProject; @@ -53,12 +53,12 @@ public class EnvVarHandlerTest { @Test public void emptyEnvVarHandlerTest(){ //Empty Environment Variable in Config - EnvVarHandler envVarHandler = new EnvVarHandler(project); + EnvVarHandler envVarHandler = new EnvVarHandler(null, project.getBuild().getOutputDirectory()); env.clear(); new Expectations(){{ - externalEnvVarHandler.getExportedEnvironmentVariables(project,env); + externalEnvVarHandler.getExportedEnvironmentVariables(null, project.getBuild().getOutputDirectory(),env); ret.putAll(env); result = ret; }}; @@ -83,10 +83,10 @@ public void envVarHandlerTest(){ env.put(var2.getName(), var2.getValue()); env.put(var3.getName(), var3.getValue()); - EnvVarHandler envVarHandler = new EnvVarHandler(project); + EnvVarHandler envVarHandler = new EnvVarHandler(null, project.getBuild().getOutputDirectory()); new Expectations(){{ - externalEnvVarHandler.getExportedEnvironmentVariables(project,env); + externalEnvVarHandler.getExportedEnvironmentVariables(null, project.getBuild().getOutputDirectory(),env); ret.putAll(env); result = ret; }}; @@ -109,10 +109,10 @@ public void envVarHandlerWithoutNameTest(){ env.clear(); env.put(null, var1.getValue()); - EnvVarHandler envVarHandler = new EnvVarHandler(project); + EnvVarHandler envVarHandler = new EnvVarHandler(null, project.getBuild().getOutputDirectory()); new Expectations(){{ - externalEnvVarHandler.getExportedEnvironmentVariables(project,env); + externalEnvVarHandler.getExportedEnvironmentVariables(null, project.getBuild().getOutputDirectory(),env); ret.put(null,"OK"); result = ret; }}; diff --git a/core/src/test/java/io/fabric8/maven/core/handler/JobHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/JobHandlerTest.java index 8e9830987b..bcd5166600 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/JobHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/JobHandlerTest.java @@ -15,14 +15,14 @@ */ package io.fabric8.maven.core.handler; -import java.util.ArrayList; -import java.util.List; - import io.fabric8.kubernetes.api.model.batch.Job; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.config.VolumeConfig; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; +import java.util.ArrayList; +import java.util.List; import mockit.Mocked; import org.apache.maven.project.MavenProject; import org.junit.Before; @@ -84,7 +84,7 @@ public void before(){ public void jobHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -119,7 +119,7 @@ public void jobHandlerTest() { public void daemonTemplateHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -140,7 +140,7 @@ public void daemonTemplateHandlerWithInvalidNameTest() { public void daemonTemplateHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = new - ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/PodTemplateHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/PodTemplateHandlerTest.java index cb4c28d124..8c4664fce2 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/PodTemplateHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/PodTemplateHandlerTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.maven.core.model.Artifact; import java.util.ArrayList; import java.util.List; @@ -82,7 +83,7 @@ public void before(){ public void podWithoutVolumeTemplateHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -111,7 +112,7 @@ public void podWithoutVolumeTemplateHandlerTest() { @Test public void podWithEmotyVolumeTemplateHandlerTest(){ ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); //Pod with empty Volume Config and wihtout ServiceAccount @@ -133,7 +134,7 @@ public void podWithEmotyVolumeTemplateHandlerTest(){ @Test public void podWithVolumeTemplateHandlerTest(){ ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); //Config with Volume Config and ServiceAccount @@ -166,7 +167,7 @@ public void podWithVolumeTemplateHandlerTest(){ @Test public void podWithInvalidVolumeTypeTemplateHandlerTest(){ ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -195,7 +196,7 @@ public void podWithInvalidVolumeTypeTemplateHandlerTest(){ @Test public void podWithoutEmptyTypeTemplateHandlerTest(){ ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/ReplicaSetHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/ReplicaSetHandlerTest.java index b8286d45e9..0f11ea8ec0 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/ReplicaSetHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/ReplicaSetHandlerTest.java @@ -15,14 +15,14 @@ */ package io.fabric8.maven.core.handler; -import java.util.ArrayList; -import java.util.List; - import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.config.VolumeConfig; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; +import java.util.ArrayList; +import java.util.List; import mockit.Mocked; import org.apache.maven.project.MavenProject; import org.junit.Before; @@ -84,7 +84,7 @@ public void before(){ public void replicaSetHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -121,7 +121,7 @@ public void replicaSetHandlerTest() { public void replicaSetHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -143,7 +143,7 @@ public void replicaSetHandlerWithInvalidNameTest() { public void replicaSetHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = new - ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/ReplicationControllerHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/ReplicationControllerHandlerTest.java index 1d33c6d0ba..5f3e0da0dd 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/ReplicationControllerHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/ReplicationControllerHandlerTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.maven.core.model.Artifact; import java.util.ArrayList; import java.util.List; @@ -84,7 +85,7 @@ public void before(){ public void replicationControllerHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -121,7 +122,7 @@ public void replicationControllerHandlerTest() { public void replicationControllerHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -143,7 +144,7 @@ public void replicationControllerHandlerWithInvalidNameTest() { public void replicationControllerHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = new - ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/handler/StatefulSetHandlerTest.java b/core/src/test/java/io/fabric8/maven/core/handler/StatefulSetHandlerTest.java index de37914205..694b3a94c1 100644 --- a/core/src/test/java/io/fabric8/maven/core/handler/StatefulSetHandlerTest.java +++ b/core/src/test/java/io/fabric8/maven/core/handler/StatefulSetHandlerTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.handler; +import io.fabric8.maven.core.model.Artifact; import java.util.ArrayList; import java.util.List; @@ -84,7 +85,7 @@ public void before(){ public void statefulSetHandlerTest() { ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -122,7 +123,7 @@ public void statefulSetHandlerTest() { public void statefulSetHandlerWithInvalidNameTest() { //invalid controller name ContainerHandler containerHandler = - new ContainerHandler(project, envVarHandler, probeHandler); + new ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); @@ -144,7 +145,7 @@ public void statefulSetHandlerWithInvalidNameTest() { public void statefulSetHandlerWithoutControllerTest() { //without controller name ContainerHandler containerHandler = new - ContainerHandler(project, envVarHandler, probeHandler); + ContainerHandler(project.getProperties(), new Artifact(), envVarHandler, probeHandler); PodTemplateHandler podTemplateHandler = new PodTemplateHandler(containerHandler); diff --git a/core/src/test/java/io/fabric8/maven/core/util/DockerServerUtilTest.java b/core/src/test/java/io/fabric8/maven/core/util/DockerServerUtilTest.java index ac9f45fdb5..7eff8fa468 100644 --- a/core/src/test/java/io/fabric8/maven/core/util/DockerServerUtilTest.java +++ b/core/src/test/java/io/fabric8/maven/core/util/DockerServerUtilTest.java @@ -15,6 +15,8 @@ */ package io.fabric8.maven.core.util; +import java.util.HashMap; +import java.util.Map; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.codehaus.plexus.util.xml.Xpp3Dom; @@ -57,26 +59,26 @@ private Settings createSettings() { return settings; } - @Test - public void testDockerUtilGetServer() { - Server server = DockerServerUtil.getServer(settings, "docker.io"); - assertEquals("docker.io", server.getId()); - assertEquals("username", server.getUsername()); - assertEquals("password", server.getPassword()); - } - @Test public void testDockerUtilGetServerJson() { - String server = DockerServerUtil.getDockerJsonConfigString(settings, "docker.io"); + + Map params = new HashMap<>(); + params.put("username", "username"); + params.put("password", "password"); + + String server = DockerServerUtil.getDockerJsonConfigString("docker.io", params); assertEquals("{\"docker.io\":{\"password\":\"password\",\"email\":\"foo@foo.com\",\"username\":\"username\"}}", server); - String server1 = DockerServerUtil.getDockerJsonConfigString(settings, "docker1.io"); + Map params1 = new HashMap<>(); + params1.put("username", "username1"); + params1.put("password", "password1"); + params1.put("email", "bar@bar.com"); + + String server1 = DockerServerUtil.getDockerJsonConfigString("docker1.io", params1); assertEquals("{\"docker1.io\":{\"password\":\"password1\",\"email\":\"bar@bar.com\",\"username\":\"username1\"}}", server1); - String server2 = DockerServerUtil.getDockerJsonConfigString(null,"docker.io"); + String server2 = DockerServerUtil.getDockerJsonConfigString("docker.io", null); assertEquals("",server2); - String server3 = DockerServerUtil.getDockerJsonConfigString(settings,"docker2.io"); - assertEquals("{\"docker2.io\":{\"password\":\"password2\",\"email\":\"foo@foo.com\",\"username\":\"username2\"}}",server3); } } diff --git a/core/src/test/java/io/fabric8/maven/core/util/KubernetesResourceUtilTest.java b/core/src/test/java/io/fabric8/maven/core/util/KubernetesResourceUtilTest.java index 70bac1db50..0e63d90c9f 100644 --- a/core/src/test/java/io/fabric8/maven/core/util/KubernetesResourceUtilTest.java +++ b/core/src/test/java/io/fabric8/maven/core/util/KubernetesResourceUtilTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.core.util; +import io.fabric8.maven.core.model.Artifact; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -151,20 +152,13 @@ public void invalidExtension() throws IOException { @Test public void containerName() { - new Expectations() {{ - project.getGroupId(); - result = "io.fabric8-test-"; - - project.getArtifactId(); - result = "fabric8-maven-plugin-dummy"; - }}; ImageConfiguration imageConfiguration = new ImageConfiguration.Builder() .name("dummy-image") .registry("example.com/someregistry") .name("test") .build(); - String containerName = KubernetesResourceUtil.extractContainerName(project, imageConfiguration); + String containerName = KubernetesResourceUtil.extractContainerName(new Artifact("io.fabric8-test-", "fabric8-maven-plugin-dummy", "0"), imageConfiguration); assertTrue(containerName.matches(KubernetesResourceUtil.CONTAINER_NAME_REGEX)); } diff --git a/enricher/api/pom.xml b/enricher/api/pom.xml index 171bcb794c..d81a7b9814 100644 --- a/enricher/api/pom.xml +++ b/enricher/api/pom.xml @@ -73,6 +73,12 @@ test + + org.assertj + assertj-core + test + + com.google.code.findbugs jsr305 diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/BaseEnricher.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/BaseEnricher.java index a8eebad850..0f2cd166c6 100644 --- a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/BaseEnricher.java +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/BaseEnricher.java @@ -15,17 +15,15 @@ */ package io.fabric8.maven.enricher.api; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.core.config.PlatformMode; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.PrefixedLogger; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.docker.util.Logger; -import org.apache.maven.project.MavenProject; +import java.util.List; +import java.util.Map; +import java.util.Properties; /** * @author roland @@ -42,7 +40,7 @@ public abstract class BaseEnricher implements Enricher { public BaseEnricher(EnricherContext buildContext, String name) { this.buildContext = buildContext; // Pick the configuration which is for us - this.config = new EnricherConfig(buildContext.getProject().getProperties(), + this.config = new EnricherConfig(this.buildContext.getProperties(), name, buildContext.getConfig()); this.log = new PrefixedLogger(name, buildContext.getLog()); this.name = name; @@ -68,18 +66,10 @@ public void addMissingResources(KubernetesListBuilder builder) { } @Override public Map getSelector(Kind kind) { return null; } - protected MavenProject getProject() { - if (buildContext != null) { - return buildContext.getProject(); - } - return null; - } - protected Logger getLog() { return log; } - protected List getImages() { return buildContext.getImages(); } @@ -112,12 +102,9 @@ protected EnricherContext getContext() { * Returns true if we are in OpenShift S2I binary building mode */ protected boolean isOpenShiftMode() { - MavenProject project = getProject(); - if (project != null) { - Properties properties = project.getProperties(); - if (properties != null) { - return PlatformMode.isOpenShiftMode(properties); - } + Properties properties = getContext().getProperties(); + if (properties != null) { + return PlatformMode.isOpenShiftMode(properties); } return false; } diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Dependency.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Dependency.java new file mode 100644 index 0000000000..5e96081d14 --- /dev/null +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Dependency.java @@ -0,0 +1,28 @@ +package io.fabric8.maven.enricher.api; + +import java.io.File; + +public class Dependency { + + private String type; + private String scope; + private File location; + + public Dependency(String type, String scope, File location) { + this.type = type; + this.scope = scope; + this.location = location; + } + + public String getType() { + return type; + } + + public String getScope() { + return scope; + } + + public File getLocation() { + return location; + } +} diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/DockerRegistryAuthentication.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/DockerRegistryAuthentication.java new file mode 100644 index 0000000000..19379d4451 --- /dev/null +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/DockerRegistryAuthentication.java @@ -0,0 +1,48 @@ +package io.fabric8.maven.enricher.api; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; + +public class DockerRegistryAuthentication { + + private String username; + private String password; + private String email; + + public DockerRegistryAuthentication() { + } + + public DockerRegistryAuthentication(String username, String password, String email) { + this.username = username; + this.password = password; + + + if (email == null || StringUtils.isBlank(email)) { + email = "foo@foo.com"; + } + + this.email = email; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getEmail() { + return email; + } + + public Map asMap() { + final Map params = new HashMap<>(); + params.put("username", this.username); + params.put("password", this.password); + params.put("email", this.email); + + return params; + } +} diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Enricher.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Enricher.java index f32d7bf0a1..ace340424a 100644 --- a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Enricher.java +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/Enricher.java @@ -15,10 +15,9 @@ */ package io.fabric8.maven.enricher.api; -import java.util.Map; - import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.core.config.Named; +import java.util.Map; /** * Interface describing enrichers which add to kubernetes descriptors diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/EnricherContext.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/EnricherContext.java index 6b6ce28fee..715b7034a5 100644 --- a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/EnricherContext.java +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/EnricherContext.java @@ -1,175 +1,170 @@ -/** - * Copyright 2016 Red Hat, Inc. - * - * Red Hat licenses this file to you under the Apache License, version - * 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - * implied. See the License for the specific language governing - * permissions and limitations under the License. - */ package io.fabric8.maven.enricher.api; -import java.util.List; - import io.fabric8.maven.core.config.ProcessorConfig; import io.fabric8.maven.core.config.ResourceConfig; -import io.fabric8.maven.core.util.GoalFinder; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.core.util.OpenShiftDependencyResources; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.docker.util.Logger; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; +import io.fabric8.maven.enricher.api.util.ProjectClassLoader; +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public interface EnricherContext { -/** - * The context given to each enricher from where it can extract build specific information. - * - * @author roland - * @since 01/04/16 - */ -public class EnricherContext { + String getNamespace(); - private MavenProject project; - private Logger log; + ResourceConfig getResources(); + + /** + * Returns true if we are in watch mode + */ + boolean isWatchMode(); - private List images; - private String namespace; + OpenShiftDependencyResources getOpenshiftDependencyResources(); + + /** + * Returns true if maven is running with any of the given goals + */ + boolean runningWithGoal(String... goals); + + /** + * Get properties of current project. Usually in case of Maven, they are the project properties. + * @return Properties of project. + */ + Properties getProperties(); - private ProcessorConfig config = ProcessorConfig.EMPTY; + /** + * Gets configuration values. Since there can be inner values, it returns a Map of Objects where an Object can be a simple type, List or another Map. + * @param id where to pick configuration. In case of Maven, plugin id. + * @return Configuration value. + */ + Map getConfiguration(String id); + + /** + * Gets artifact. + * @return Artifact. + */ + Artifact getArtifact(); + + /** + * Gets artifact identifier of root project. + * @return Root artifact id. + */ + String getRootArtifactId(); + + /** + * Returns the rot dir of project. Notice that in a submodule project, current dir is not the roor dir. + * @return Root dir. + */ + File getRootDir(); + + /** + * Gets current directory. + * @return Current directory. + */ + File getCurrentDir(); - private ResourceConfig resources; + /** + * Gets output directory. + * @return Output Directory. + */ + String getBuildOutputDirectory(); - private boolean useProjectClasspath; - private OpenShiftDependencyResources openshiftDependencyResources; - private MavenSession session; - private GoalFinder goalFinder; + /** + * Gets a map with fields username, password and email set. + * @param serverId Identifier to get the info. + * @return Docker Registry authentication parameters. + */ + DockerRegistryAuthentication getDockerRegistryAuth(String serverId); - private EnricherContext() {} + /** + * Returns if class is in compile classpath. + * @param all True if all of them must be there. + * @param clazz fully qualified class name. + * @return True if present, false otherwise. + */ + boolean isClassInCompileClasspath(boolean all, String... clazz); - public MavenProject getProject() { - return project; - } + /** + * Gets documentation url or null. + * @return Gets documentation url or null if not specified. + */ + String getDocumentationUrl(); - public List getImages() { - return images; - } + /** + * Gets dependencies defined in build tool + * @param transitive if transitive deps should be returned. + * @return List of dependencies. + */ + List getDependencies(boolean transitive); - public Logger getLog() { - return log; - } + /** + * Checks if given dependency is defined. + * @param groupId of dependency. + * @param artifactId of dependency. + * @return True if present, flse otherwise. + */ + boolean hasDependency(String groupId, String artifactId); - public ProcessorConfig getConfig() { - return config; - } + /** + * Returns if given plugin is present + * @param plugin to check. + * @return True if present, false otherwise. + */ + boolean hasPlugin(String plugin); - public ResourceConfig getResources() { - return resources; - } + /** + * Checks if there is a dependency of given group id. + * @param groupId to search. + * @return True if there is a dependency, false otherwise. + */ + boolean hasDependencyOnAnyArtifactOfGroup(String groupId); - public String getNamespace() { - return namespace; - } + /** + * Checks if there is a plugin of given group id. + * @param groupId to search. + * @return True if there is a plugin, false otherwise. + */ + boolean hasPluginOfAnyGroupId(String groupId); - public boolean isUseProjectClasspath() { - return useProjectClasspath; - } + /** + * Gets version of given dependency. + * @param groupId of the dependency. + * @param artifactId of the dependency. + * @return Version number. + */ + String getDependencyVersion(String groupId, String artifactId); - public Settings getSettings() { - return session != null ? session.getSettings() : null; - } + /** + * Gets Project Classloader. + * @return Classloader. + */ + ProjectClassLoader getProjectClassLoader(); - public OpenShiftDependencyResources getOpenshiftDependencyResources() { - return openshiftDependencyResources; - } + /** + * + * Gets processor Config + * @return processor config + */ + ProcessorConfig getConfig(); /** - * Returns true if we are in watch mode + * Get Logger. + * @return Logger. */ - public boolean isWatchMode() { - try { - return runningWithGoal("fabric8:watch-spring-boot", "fabric8:watch"); - } catch (MojoExecutionException e) { - throw new IllegalStateException("Cannot determine maven goals", e); - } - } + Logger getLog(); /** - * Returns true if maven is running with any of the given goals + * Get List of images + * @return */ - public boolean runningWithGoal(String... goals) throws MojoExecutionException { - for (String goal : goals) { - if (goalFinder.runningWithGoal(project, session, goal)) { - return true; - } - } - return false; - } - - // ======================================================================================================= - public static class Builder { - - private EnricherContext ctx = new EnricherContext(); - - public Builder session(MavenSession session) { - ctx.session = session; - return this; - }; - - public Builder goalFinder(GoalFinder goalFinder) { - ctx.goalFinder = goalFinder; - return this; - } - - public Builder log(Logger log) { - ctx.log = log; - return this; - } - - public Builder project(MavenProject project) { - ctx.project = project; - return this; - } - - public Builder config(ProcessorConfig config) { - ctx.config = config; - return this; - } - - public Builder resources(ResourceConfig resources) { - ctx.resources = resources; - return this; - } - - public Builder images(List images) { - ctx.images = images; - return this; - } - - public Builder namespace(String namespace) { - ctx.namespace = namespace; - return this; - } - - public Builder useProjectClasspath(boolean useProjectClasspath) { - ctx.useProjectClasspath = useProjectClasspath; - return this; - } - - public Builder openshiftDependencyResources(OpenShiftDependencyResources openShiftDependencyResources) { - ctx.openshiftDependencyResources = openShiftDependencyResources; - return this; - } - - public EnricherContext build() { - return ctx; - } - - } + List getImages(); + + boolean isUseProjectClasspath(); + + List getCompileClasspathElements(); + } diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/MavenEnricherContext.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/MavenEnricherContext.java new file mode 100644 index 0000000000..222467ba38 --- /dev/null +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/MavenEnricherContext.java @@ -0,0 +1,348 @@ +/** + * Copyright 2016 Red Hat, Inc. + * + * Red Hat licenses this file to you under the Apache License, version + * 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +package io.fabric8.maven.enricher.api; + +import io.fabric8.maven.core.config.ProcessorConfig; +import io.fabric8.maven.core.config.ResourceConfig; +import io.fabric8.maven.core.util.GoalFinder; +import io.fabric8.maven.core.util.MavenUtil; +import io.fabric8.maven.core.util.OpenShiftDependencyResources; +import io.fabric8.maven.docker.config.ImageConfiguration; +import io.fabric8.maven.docker.util.Logger; +import io.fabric8.maven.enricher.api.util.MavenConfigurationExtractor; +import io.fabric8.maven.enricher.api.util.ProjectClassLoader; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.DistributionManagement; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.Site; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Server; +import org.apache.maven.settings.Settings; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * The context given to each enricher from where it can extract build specific information. + * + * @author roland + * @since 01/04/16 + */ +public class MavenEnricherContext implements EnricherContext { + + private MavenProject project; + private Logger log; + + private List images; + private String namespace; + + private ProcessorConfig config = ProcessorConfig.EMPTY; + + private ResourceConfig resources; + + private boolean useProjectClasspath; + private OpenShiftDependencyResources openshiftDependencyResources; + private MavenSession session; + private GoalFinder goalFinder; + + private MavenEnricherContext() {} + + public MavenProject getProject() { + return project; + } + + @Override + public List getImages() { + return images; + } + + public Logger getLog() { + return log; + } + + @Override + public ProcessorConfig getConfig() { + return config; + } + + @Override + public ResourceConfig getResources() { + return resources; + } + + @Override + public String getNamespace() { + return namespace; + } + + @Override + public boolean isUseProjectClasspath() { + return useProjectClasspath; + } + + public Settings getSettings() { + return session != null ? session.getSettings() : null; + } + + @Override + public OpenShiftDependencyResources getOpenshiftDependencyResources() { + return openshiftDependencyResources; + } + + @Override + public boolean isWatchMode() { + return runningWithGoal("fabric8:watch-spring-boot", "fabric8:watch"); + } + + @Override + public boolean runningWithGoal(String... goals) { + for (String goal : goals) { + try { + if (goalFinder.runningWithGoal(project, session, goal)) { + return true; + } + } catch (MojoExecutionException e) { + throw new IllegalStateException("Cannot determine maven goals", e); + } + } + return false; + } + + @Override + public Properties getProperties() { + final MavenProject currentProject = getProject(); + if (currentProject == null) { + return new Properties(); + } + return currentProject.getProperties(); + } + + @Override + public Map getConfiguration(String id) { + final Plugin plugin = getProject().getPlugin(id); + + if (plugin == null) { + return new HashMap<>(); + } + + return MavenConfigurationExtractor.extract((Xpp3Dom) plugin.getConfiguration()); + } + + @Override + public io.fabric8.maven.core.model.Artifact getArtifact() { + + return new io.fabric8.maven.core.model.Artifact(getProject().getGroupId(),getProject().getArtifactId(), getProject().getVersion()); + } + + @Override + public String getRootArtifactId() { + return MavenUtil.getRootProject(getProject()).getArtifactId(); + } + + @Override + public File getRootDir() { + return MavenUtil.getRootProject(getProject()).getBasedir(); + } + + @Override + public File getCurrentDir() { + return getProject().getBasedir(); + } + + @Override + public String getBuildOutputDirectory() { + return getProject().getBuild().getOutputDirectory(); + } + + @Override + public DockerRegistryAuthentication getDockerRegistryAuth(String serverId) { + Server server = getServer(getSettings(), serverId); + + if (server == null) { + return null; + } + + final Map conf = MavenConfigurationExtractor.extract((Xpp3Dom) server.getConfiguration()); + + String mail = (String) conf.get("email"); + + return new DockerRegistryAuthentication(server.getUsername(), server.getPassword(), mail); + } + + private Server getServer(final Settings settings, final String serverId) { + if (settings == null || StringUtils.isBlank(serverId)) { + return null; + } + return settings.getServer(serverId); + } + + @Override + public boolean isClassInCompileClasspath(boolean all, String... clazz) { + if (all) { + return MavenUtil.hasAllClasses(getProject(), clazz); + } else { + return MavenUtil.hasClass(getProject(), clazz); + } + } + + @Override + public String getDocumentationUrl() { + DistributionManagement distributionManagement = findProjectDistributionManagement(); + if (distributionManagement != null) { + Site site = distributionManagement.getSite(); + if (site != null) { + return site.getUrl(); + } + } + return null; + } + + private DistributionManagement findProjectDistributionManagement() { + MavenProject currentProject = getProject(); + while (currentProject != null) { + DistributionManagement distributionManagement = currentProject.getDistributionManagement(); + if (distributionManagement != null) { + return distributionManagement; + } + currentProject = currentProject.getParent(); + } + return null; + } + + @Override + public List getDependencies(boolean transitive) { + final Set artifacts = transitive ? + getProject().getArtifacts() : getProject().getDependencyArtifacts(); + + final List dependencies = new ArrayList<>(); + + for (Artifact artifact : artifacts) { + dependencies.add(new Dependency(artifact.getType(), artifact.getScope(), artifact.getFile())); + } + + return dependencies; + } + + @Override + public boolean hasDependency(String groupId, String artifactId) { + return MavenUtil.hasDependency(getProject(), groupId, artifactId); + } + + @Override + public boolean hasPlugin(String plugin) { + return MavenUtil.hasPlugin(getProject(), plugin); + } + + @Override + public boolean hasDependencyOnAnyArtifactOfGroup(String groupId) { + return MavenUtil.hasDependencyOnAnyArtifactOfGroup(getProject(), groupId); + } + + @Override + public boolean hasPluginOfAnyGroupId(String groupId) { + return MavenUtil.hasPluginOfAnyGroupId(getProject(), groupId); + } + + @Override + public String getDependencyVersion(String groupId, String artifactId) { + return MavenUtil.getDependencyVersion(getProject(), groupId, artifactId); + } + + @Override + public ProjectClassLoader getProjectClassLoader() { + return new ProjectClassLoader(MavenUtil.getCompileClassLoader(getProject()), MavenUtil.getTestClassLoader(getProject())); + } + + @Override + public List getCompileClasspathElements() { + try { + return getProject().getCompileClasspathElements(); + } catch (DependencyResolutionRequiredException e) { + log.warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e); + } + return new ArrayList<>(); + } + + // ======================================================================================================= + public static class Builder { + + private MavenEnricherContext ctx = new MavenEnricherContext(); + + public Builder session(MavenSession session) { + ctx.session = session; + return this; + } + + public Builder goalFinder(GoalFinder goalFinder) { + ctx.goalFinder = goalFinder; + return this; + } + + public Builder log(Logger log) { + ctx.log = log; + return this; + } + + public Builder project(MavenProject project) { + ctx.project = project; + return this; + } + + public Builder config(ProcessorConfig config) { + ctx.config = config; + return this; + } + + public Builder resources(ResourceConfig resources) { + ctx.resources = resources; + return this; + } + + public Builder images(List images) { + ctx.images = images; + return this; + } + + public Builder namespace(String namespace) { + ctx.namespace = namespace; + return this; + } + + public Builder useProjectClasspath(boolean useProjectClasspath) { + ctx.useProjectClasspath = useProjectClasspath; + return this; + } + + public Builder openshiftDependencyResources(OpenShiftDependencyResources openShiftDependencyResources) { + ctx.openshiftDependencyResources = openShiftDependencyResources; + return this; + } + + public MavenEnricherContext build() { + return ctx; + } + + } +} diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractor.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractor.java new file mode 100644 index 0000000000..7c9a976382 --- /dev/null +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractor.java @@ -0,0 +1,73 @@ +package io.fabric8.maven.enricher.api.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +public class MavenConfigurationExtractor { + + private MavenConfigurationExtractor() { + } + + /** + * Transforms the Dom object into a Map. + * This Map can contain pairs key/value where value can be a simple type, another Map (Inner objects) + * and a list of simple types. + * + * Currently it is NOT supported List of complex objects. + * @param root object. + * @return Map of DOM structure. + */ + public static Map extract(Xpp3Dom root) { + if (root == null) { + return new HashMap<>(); + } + + return getElement(root); + } + + private static Map getElement(Xpp3Dom element) { + + final Map conf = new HashMap<>(); + + final Xpp3Dom[] currentElements = element.getChildren(); + + for (Xpp3Dom currentElement: currentElements) { + if (isSimpleType(currentElement)) { + + if (isAListOfElements(conf, currentElement)) { + addAsList(conf, currentElement); + } else { + conf.put(currentElement.getName(), currentElement.getValue()); + } + } else { + conf.put(currentElement.getName(), getElement(currentElement)); + } + } + + return conf; + + } + + private static void addAsList(Map conf, Xpp3Dom currentElement) { + final Object insertedValue = conf.get(currentElement.getName()); + if (insertedValue instanceof List) { + ((List) insertedValue).add(currentElement.getValue()); + } else { + final List list = new ArrayList<>(); + list.add((String) insertedValue); + list.add(currentElement.getValue()); + conf.put(currentElement.getName(), list); + } + } + + private static boolean isAListOfElements(Map conf, Xpp3Dom currentElement) { + return conf.containsKey(currentElement.getName()); + } + + private static boolean isSimpleType(Xpp3Dom currentElement) { + return currentElement.getChildCount() == 0; + } +} diff --git a/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/ProjectClassLoader.java b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/ProjectClassLoader.java new file mode 100644 index 0000000000..37a09124b2 --- /dev/null +++ b/enricher/api/src/main/java/io/fabric8/maven/enricher/api/util/ProjectClassLoader.java @@ -0,0 +1,22 @@ +package io.fabric8.maven.enricher.api.util; + +import java.net.URLClassLoader; + +public class ProjectClassLoader { + + private URLClassLoader compileClassLoader; + private URLClassLoader testClassLoader; + + public ProjectClassLoader(URLClassLoader compileClassLoader, URLClassLoader testClassLoader) { + this.compileClassLoader = compileClassLoader; + this.testClassLoader = testClassLoader; + } + + public URLClassLoader getCompileClassLoader() { + return compileClassLoader; + } + + public URLClassLoader getTestClassLoader() { + return testClassLoader; + } +} diff --git a/enricher/api/src/test/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractorTest.java b/enricher/api/src/test/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractorTest.java new file mode 100644 index 0000000000..508efd15d1 --- /dev/null +++ b/enricher/api/src/test/java/io/fabric8/maven/enricher/api/util/MavenConfigurationExtractorTest.java @@ -0,0 +1,149 @@ +package io.fabric8.maven.enricher.api.util; + +import java.io.StringReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.apache.maven.model.Plugin; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.codehaus.plexus.util.xml.Xpp3DomBuilder; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MavenConfigurationExtractorTest { + + + @Test + public void should_parse_simple_types() { + + // Given + final Plugin fakePlugin = createFakePlugin("ab"); + + // When + final Map config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); + + // Then + assertThat(config) + .containsEntry("a", "a") + .containsEntry("b", "b"); + + } + + @Test + public void should_parse_inner_objects() { + + // Given + final Plugin fakePlugin = createFakePlugin("" + + "b" + + ""); + + // When + final Map config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); + + // Then + final Map expected = new HashMap<>(); + expected.put("b", "b"); + assertThat(config) + .containsEntry("a", expected); + + } + + @Test + public void should_parse_deep_inner_objects() { + + // Given + final Plugin fakePlugin = createFakePlugin("" + + "" + + "" + + "" + + "e1" + + "" + + "" + + "" + + ""); + + // When + final Map config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); + + // Then + final Map e = new HashMap<>(); + e.put("e", "e1"); + final Map d = new HashMap<>(); + d.put("d", e); + final Map c = new HashMap<>(); + c.put("c", d); + final Map expected = new HashMap<>(); + expected.put("b", c); + assertThat(config) + .containsEntry("a", expected); + + } + + @Test + public void should_parse_list_of_elements() { + + // Given + final Plugin fakePlugin = createFakePlugin("" + + "" + + "c1c2" + + "" + + ""); + + // When + final Map config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); + + // Then + final Map expectedC = new HashMap<>(); + expectedC.put("c", Arrays.asList("c1", "c2")); + final Map expected = new HashMap<>(); + expected.put("b", expectedC); + + assertThat(config) + .containsEntry("a",expected); + + } + + @Test + public void should_parse_list_of_mixed_elements() { + + // Given + final Plugin fakePlugin = createFakePlugin("" + + "" + + "c1d1c2" + + "" + + ""); + + // When + final Map config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration()); + + // Then + final Map expectedC = new HashMap<>(); + expectedC.put("c", Arrays.asList("c1", "c2")); + expectedC.put("d", "d1"); + final Map expected = new HashMap<>(); + expected.put("b", expectedC); + + assertThat(config) + .containsEntry("a",expected); + + } + + private Plugin createFakePlugin(String config) { + Plugin plugin = new Plugin(); + plugin.setArtifactId("fabric8-maven-plugin"); + plugin.setGroupId("io.fabric8"); + String content = "" + + config + + ""; + Xpp3Dom dom; + try { + dom = Xpp3DomBuilder.build(new StringReader(content)); + } catch (Exception e) { + throw new RuntimeException(e); + } + plugin.setConfiguration(dom); + + return plugin; + } +} diff --git a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/AbstractLiveEnricher.java b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/AbstractLiveEnricher.java index 3995cb34ac..3fce6abbc8 100644 --- a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/AbstractLiveEnricher.java +++ b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/AbstractLiveEnricher.java @@ -26,7 +26,7 @@ import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; import io.fabric8.maven.core.util.kubernetes.ServiceUrlUtil; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import org.apache.commons.lang3.StringUtils; abstract public class AbstractLiveEnricher extends BaseEnricher { @@ -39,7 +39,7 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public AbstractLiveEnricher(EnricherContext buildContext, String name) { + public AbstractLiveEnricher(MavenEnricherContext buildContext, String name) { super(buildContext, name); } @@ -135,7 +135,7 @@ protected Stack unfoldExceptions(Throwable exception) { // Check a global prop from the project or system props protected Boolean asBooleanFromGlobalProp(String prop) { - String value = getProject().getProperties().getProperty(prop); + String value = getContext().getProperties().getProperty(prop); if (value == null) { value = System.getProperty(prop); } diff --git a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/CdEnricher.java b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/CdEnricher.java index 9a4d9a9dfe..1a250ff315 100644 --- a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/CdEnricher.java +++ b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/CdEnricher.java @@ -16,18 +16,15 @@ package io.fabric8.maven.enricher.deprecated; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.GitUtil; -import io.fabric8.maven.core.util.MavenUtil; import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.project.MavenProject; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; @@ -62,7 +59,7 @@ public String def() { protected String d; } - public CdEnricher(EnricherContext buildContext) { + public CdEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-deprecated-cd"); } @@ -88,9 +85,8 @@ private String getBuildId() { public Map getAnnotations(Kind kind) { if (isOnline() && (kind.isController() || kind == Kind.SERVICE)) { Map annotations = new HashMap<>(); - MavenProject rootProject = MavenUtil.getRootProject(getProject()); - String repoName = rootProject.getArtifactId(); - try (Repository repository = GitUtil.getGitRepository(getProject())) { + String repoName = getContext().getRootArtifactId(); + try (Repository repository = GitUtil.getGitRepository(getContext().getCurrentDir())) { // Git annotations (if git is used as SCM) if (repository != null) { String gitCommitId = GitUtil.getGitCommitId(repository); diff --git a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/DocLinkEnricher.java b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/DocLinkEnricher.java index dea04b7d38..c7eccc0f21 100644 --- a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/DocLinkEnricher.java +++ b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/DocLinkEnricher.java @@ -1,12 +1,12 @@ /** * Copyright 2016 Red Hat, Inc. - * + *

* Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or @@ -15,20 +15,16 @@ */ package io.fabric8.maven.enricher.deprecated; +import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.maven.enricher.api.Kind; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.Set; - -import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; -import io.fabric8.maven.enricher.api.EnricherContext; -import io.fabric8.maven.enricher.api.Kind; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.model.DistributionManagement; -import org.apache.maven.model.Site; -import org.apache.maven.project.MavenProject; /** * Adds a link to the generated documentation for this microservice so we can link to the versioned docs in the @@ -36,7 +32,7 @@ */ public class DocLinkEnricher extends AbstractLiveEnricher { - public DocLinkEnricher(EnricherContext buildContext) { + public DocLinkEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-deprecated-link"); } @@ -51,58 +47,37 @@ public Map getAnnotations(Kind kind) { } protected String findDocumentationUrl() { - DistributionManagement distributionManagement = findProjectDistributionManagement(); - if (distributionManagement != null) { - Site site = distributionManagement.getSite(); - if (site != null) { - String url = site.getUrl(); - if (StringUtils.isNotBlank(url)) { - // lets replace any properties... - MavenProject project = getProject(); - if (project != null) { - url = replaceProperties(url, project.getProperties()); - } - // lets convert the internal dns name to a public name - try { - String urlToParse = url; - int idx = url.indexOf("://"); - if (idx > 0) { - // lets strip any previous schemes such as "dav:" - int idx2 = url.substring(0, idx).lastIndexOf(':'); - if (idx2 >= 0 && idx2 < idx) { - urlToParse = url.substring(idx2 + 1); - } - } - URL u = new URL(urlToParse); - String serviceName = u.getHost(); - String protocol = u.getProtocol(); - if (isOnline()) { - // lets see if the host name is a service name in which case we'll resolve to the public URL - String publicUrl = getExternalServiceURL(serviceName, protocol); - if (StringUtils.isNotBlank(publicUrl)) { - return String.format("%s/%s",publicUrl, u.getPath()); - } - } - } catch (MalformedURLException e) { - getLog().error("Failed to parse URL: %s. %s", url, e); + String url = getContext().getDocumentationUrl(); + if (StringUtils.isNotBlank(url)) { + // lets replace any properties... + url = replaceProperties(url, getContext().getProperties()); + + // lets convert the internal dns name to a public name + try { + String urlToParse = url; + int idx = url.indexOf("://"); + if (idx > 0) { + // lets strip any previous schemes such as "dav:" + int idx2 = url.substring(0, idx).lastIndexOf(':'); + if (idx2 >= 0 && idx2 < idx) { + urlToParse = url.substring(idx2 + 1); } - return url; } + URL u = new URL(urlToParse); + String serviceName = u.getHost(); + String protocol = u.getProtocol(); + if (isOnline()) { + // lets see if the host name is a service name in which case we'll resolve to the public URL + String publicUrl = getExternalServiceURL(serviceName, protocol); + if (StringUtils.isNotBlank(publicUrl)) { + return String.format("%s/%s", publicUrl, u.getPath()); + } + } + } catch (MalformedURLException e) { + getLog().error("Failed to parse URL: %s. %s", url, e); } - } - return null; - } - - - protected DistributionManagement findProjectDistributionManagement() { - MavenProject project = getProject(); - while (project != null) { - DistributionManagement distributionManagement = project.getDistributionManagement(); - if (distributionManagement != null) { - return distributionManagement; - } - project = project.getParent(); + return url; } return null; } diff --git a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/GrafanaLinkEnricher.java b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/GrafanaLinkEnricher.java index f55d312522..7a92294d34 100644 --- a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/GrafanaLinkEnricher.java +++ b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/GrafanaLinkEnricher.java @@ -15,24 +15,19 @@ */ package io.fabric8.maven.enricher.deprecated; -import java.util.Collections; -import java.util.Map; - import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; +import java.util.Collections; +import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.project.MavenProject; - -import static io.fabric8.maven.core.util.MavenUtil.hasClass; /** */ public class GrafanaLinkEnricher extends BaseEnricher { - public GrafanaLinkEnricher(EnricherContext buildContext) { + public GrafanaLinkEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-deprecated-cd-grafana-link"); } @@ -54,18 +49,17 @@ public Map getAnnotations(Kind kind) { } private String findGrafanaLink() { - MavenProject project = getProject(); - String defaultDashboard = detectDefaultDashboard(project); + String defaultDashboard = detectDefaultDashboard(); String query = ""; String projectName = null; String version = null; // TODO - use the docker names which may differ from project metadata! if (StringUtils.isBlank(projectName)) { - projectName = project.getArtifactId(); + projectName = getContext().getArtifact().getArtifactId(); } if (StringUtils.isBlank(version)) { - version = project.getVersion(); + version = getContext().getArtifact().getVersion(); } if (StringUtils.isNotBlank(projectName)) { @@ -80,12 +74,12 @@ private String findGrafanaLink() { return String.format("dashboard/file/%s%s", defaultDashboard, query); } - protected String detectDefaultDashboard(MavenProject project) { + protected String detectDefaultDashboard() { String dashboard = getConfig(Config.metricsDashboard); if (StringUtils.isNotBlank(dashboard)) { return dashboard; } - if (hasClass(project, "org.apache.camel.CamelContext")) { + if (getContext().isClassInCompileClasspath(false,"org.apache.camel.CamelContext")) { return "camel-routes.json"; } return "kubernetes-pods.json"; diff --git a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/IconEnricher.java b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/IconEnricher.java index bca4833797..5c881c592d 100644 --- a/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/IconEnricher.java +++ b/enricher/deprecated/src/main/java/io/fabric8/maven/enricher/deprecated/IconEnricher.java @@ -16,6 +16,13 @@ package io.fabric8.maven.enricher.deprecated; +import com.google.common.io.Files; +import io.fabric8.maven.core.util.Configs; +import io.fabric8.maven.core.util.FileUtil; +import io.fabric8.maven.core.util.SpringBootConfigurationHelper; +import io.fabric8.maven.enricher.api.BaseEnricher; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.maven.enricher.api.Kind; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; @@ -23,25 +30,9 @@ import java.net.URLConnection; import java.util.Collections; import java.util.Map; - -import com.google.common.io.Files; -import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.core.util.FileUtil; -import io.fabric8.maven.core.util.MavenUtil; -import io.fabric8.maven.core.util.SpringBootConfigurationHelper; -import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; -import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; -import io.fabric8.maven.enricher.api.Kind; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.model.Scm; -import org.apache.maven.project.MavenProject; - -import static io.fabric8.maven.core.util.MavenUtil.hasClass; -import static io.fabric8.maven.core.util.MavenUtil.hasPlugin; -import static io.fabric8.maven.core.util.MavenUtil.hasPluginOfAnyGroupId; /** * Enricher for adding icons to descriptors @@ -71,10 +62,10 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public IconEnricher(EnricherContext buildContext) { + public IconEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-deprecated-icon"); - String baseDir = getProject().getBasedir().getAbsolutePath(); + String baseDir = getContext().getCurrentDir().getAbsolutePath(); templateTempDir = new File(getConfig(Config.templateTempDir, baseDir + "/target/fabric8/template-workdir")); appConfigDir = new File(getConfig(Config.sourceDir, baseDir + "/src/main/fabric8")); } @@ -151,32 +142,30 @@ protected String getIconUrl(String iconRef) { * @return the icon ref if we can detect one or return null */ private String getDefaultIconRef() { - MavenProject project = getProject(); - EnricherContext context = getContext(); - - if (hasClass(project, "io.fabric8.funktion.runtime.Main") || MavenUtil.hasDependencyOnAnyArtifactOfGroup(project, "io.fabric8.funktion")) { + if (getContext().isClassInCompileClasspath(false, "io.fabric8.funktion.runtime.Main") || + getContext().hasDependencyOnAnyArtifactOfGroup( "io.fabric8.funktion")) { return "funktion"; } - if (hasClass(project, "org.apache.camel.CamelContext")) { + if (getContext().isClassInCompileClasspath(false, "org.apache.camel.CamelContext")) { return "camel"; } - if (hasPluginOfAnyGroupId(project, SpringBootConfigurationHelper.SPRING_BOOT_MAVEN_PLUGIN_ARTIFACT_ID) || - hasClass(project, "org.springframework.boot.SpringApplication")) { + if (getContext().hasPluginOfAnyGroupId( SpringBootConfigurationHelper.SPRING_BOOT_MAVEN_PLUGIN_ARTIFACT_ID) || + getContext().isClassInCompileClasspath(false, "org.springframework.boot.SpringApplication")) { return "spring-boot"; } - if (hasClass(project, "org.springframework.core.Constants")) { + if (getContext().isClassInCompileClasspath(false, "org.springframework.core.Constants")) { return "spring"; } - if (hasClass(project, "org.vertx.java.core.Handler", "io.vertx.core.Handler")) { + if (getContext().isClassInCompileClasspath(false, "org.vertx.java.core.Handler", "io.vertx.core.Handler")) { return "vertx"; } - if (hasPlugin(project, "org.wildfly.swarm:wildfly-swarm-plugin") || - MavenUtil.hasDependencyOnAnyArtifactOfGroup(project, "org.wildfly.swarm")) { + if (getContext().hasPlugin("org.wildfly.swarm:wildfly-swarm-plugin") || + getContext().hasDependencyOnAnyArtifactOfGroup( "org.wildfly.swarm")) { return "wildfly-swarm"; } - if (hasPlugin(project, "io.thorntail:thorntail-maven-plugin") || - MavenUtil.hasDependencyOnAnyArtifactOfGroup(project, "io.thorntail")) { + if (getContext().hasPlugin( "io.thorntail:thorntail-maven-plugin") || + getContext().hasDependencyOnAnyArtifactOfGroup( "io.thorntail")) { // use the WildFly Swarm icon until there's a dedicated Thorntail icon // Thorntail is a new name of WildFly Swarm return "wildfly-swarm"; @@ -233,7 +222,7 @@ public boolean accept(File dir, String name) { private InputStream loadPluginResource(String iconRef) { InputStream answer = Thread.currentThread().getContextClassLoader().getResourceAsStream(iconRef); if (answer == null) { - answer = MavenUtil.getTestClassLoader(getProject()).getResourceAsStream(iconRef); + answer = getContext().getProjectClassLoader().getTestClassLoader().getResourceAsStream(iconRef); } if (answer == null) { answer = this.getClass().getResourceAsStream(iconRef); @@ -279,31 +268,36 @@ private String convertIconFileToURL(File iconFile, String iconRef) throws IOExce File rootProjectFolder = getRootProjectFolder(); if (rootProjectFolder != null) { String relativePath = FileUtil.getRelativePath(rootProjectFolder, iconSourceFile).toString(); - String relativeParentPath = FileUtil.getRelativePath(rootProjectFolder, getProject().getBasedir()).toString(); + String relativeParentPath = + FileUtil.getRelativePath(rootProjectFolder, getContext().getCurrentDir()).toString(); String urlPrefix = getConfig(Config.urlPrefix); if (StringUtils.isBlank(urlPrefix)) { - Scm scm = getProject().getScm(); - if (scm != null) { - String url = scm.getUrl(); - if (url != null) { - String[] prefixes = {"http://github.com/", "https://github.com/"}; - for (String prefix : prefixes) { - if (url.startsWith(prefix)) { - url = "https://cdn.rawgit.com/" + url.substring(prefix.length()); - break; + if (getContext() instanceof MavenEnricherContext) { + MavenEnricherContext mavenEnricherContext = (MavenEnricherContext) getContext(); + final org.apache.maven.model.Scm scm = mavenEnricherContext.getProject().getScm(); + if (scm != null) { + String url = scm.getUrl(); + if (url != null) { + String[] prefixes = {"http://github.com/", "https://github.com/"}; + for (String prefix : prefixes) { + if (url.startsWith(prefix)) { + url = "https://cdn.rawgit.com/" + url.substring(prefix.length()); + break; + } } + if (url.endsWith(relativeParentPath)) { + url = url.substring(0, url.length() - relativeParentPath.length()); + } + urlPrefix = url; } - if (url.endsWith(relativeParentPath)) { - url = url.substring(0, url.length() - relativeParentPath.length()); - } - urlPrefix = url; } } - } - if (StringUtils.isBlank(urlPrefix)) { - log.warn("No iconUrlPrefix defined or could be found via SCM in the pom.xml so cannot add an icon URL!"); - } else { - return String.format("%s/%s/%s", urlPrefix, getConfig(Config.branch), relativePath); + if (StringUtils.isBlank(urlPrefix)) { + log.warn( + "No iconUrlPrefix defined or could be found via SCM in the pom.xml so cannot add an icon URL!"); + } else { + return String.format("%s/%s/%s", urlPrefix, getConfig(Config.branch), relativePath); + } } } } else { @@ -322,16 +316,7 @@ private String convertIconFileToURL(File iconFile, String iconRef) throws IOExce * Returns the root project folder */ protected File getRootProjectFolder() { - File answer = null; - MavenProject project = getProject(); - while (project != null) { - File basedir = project.getBasedir(); - if (basedir != null) { - answer = basedir; - } - project = project.getParent(); - } - return answer; + return getContext().getRootDir(); } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/AbstractHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/AbstractHealthCheckEnricher.java index 44607580b7..291f6aab37 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/AbstractHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/AbstractHealthCheckEnricher.java @@ -21,14 +21,14 @@ import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enriches containers with health check probes. */ public abstract class AbstractHealthCheckEnricher extends BaseEnricher { - public AbstractHealthCheckEnricher(EnricherContext buildContext, String name) { + public AbstractHealthCheckEnricher(MavenEnricherContext buildContext, String name) { super(buildContext, name); } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricher.java index d8fbe3efaf..9e97ccee4d 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricher.java @@ -15,8 +15,6 @@ */ package io.fabric8.maven.enricher.fabric8; -import java.util.List; - import com.google.common.base.Objects; import io.fabric8.kubernetes.api.model.ContainerBuilder; import io.fabric8.kubernetes.api.model.ExecAction; @@ -26,7 +24,8 @@ import io.fabric8.maven.docker.config.HealthCheckConfiguration; import io.fabric8.maven.docker.config.HealthCheckMode; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.List; import static io.fabric8.maven.enricher.api.util.GoTimeUtil.durationSeconds; @@ -36,7 +35,7 @@ */ public class DockerHealthCheckEnricher extends AbstractHealthCheckEnricher { - public DockerHealthCheckEnricher(EnricherContext buildContext) { + public DockerHealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-healthcheck-docker"); } @@ -88,7 +87,7 @@ private ImageConfiguration getImageWithContainerName(String containerName) { List images = getImages(); if (images != null) { for (ImageConfiguration image : images) { - String imageContainerName = KubernetesResourceUtil.extractContainerName(getProject(), image); + String imageContainerName = KubernetesResourceUtil.extractContainerName(getContext().getArtifact(), image); if (Objects.equal(containerName, imageContainerName)) { return image; } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/KarafHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/KarafHealthCheckEnricher.java index b9fd060737..01f625d172 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/KarafHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/KarafHealthCheckEnricher.java @@ -17,9 +17,9 @@ import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.kubernetes.api.model.ProbeBuilder; -import io.fabric8.maven.enricher.api.EnricherContext; -import org.apache.maven.model.Plugin; -import org.codehaus.plexus.util.xml.Xpp3Dom; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.List; +import java.util.Map; /** * Enriches Karaf containers with health check probes. @@ -28,7 +28,7 @@ public class KarafHealthCheckEnricher extends AbstractHealthCheckEnricher { private static final int DEFAULT_HEALTH_CHECK_PORT = 8181; - public KarafHealthCheckEnricher(EnricherContext buildContext) { + public KarafHealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-healthcheck-karaf"); } @@ -48,24 +48,52 @@ protected Probe getLivenessProbe() { // private Probe discoverKarafProbe(String path, int initialDelay) { - for (Plugin plugin : this.getProject().getBuildPlugins()) { - if ("karaf-maven-plugin".equals(plugin.getArtifactId())) { - Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration(); - if (configuration == null) - return null; - Xpp3Dom startupFeatures = configuration.getChild("startupFeatures"); - if (startupFeatures == null) - return null; - - for (Xpp3Dom feature : startupFeatures.getChildren("feature")) { - if ("fabric8-karaf-checks".equals(feature.getValue())) { - // TODO: handle the case where the user changes the default port + final Map configurationValues = getContext().getConfiguration("karaf-maven-plugin"); + + if (configurationValues == null || configurationValues.isEmpty()) { + return null; + } + + + final Object startupFeatures = configurationValues.get("startupFeatures"); + + if (startupFeatures == null) { + return null; + } + + if (!(startupFeatures instanceof Map)) { + throw new IllegalArgumentException(String.format("For element %s was expected a complex object but a simple object was found of type %s and value %s", + "startupFeatures", startupFeatures.getClass(), startupFeatures.toString())); + } + + final Map startUpFeaturesObject = (Map) startupFeatures; + + final Object feature = startUpFeaturesObject.get("feature"); + + if (feature != null) { + + // It can be a single feature or a list of features + + if (feature instanceof List) { + final List features = (List) feature; + + for (String featureValue : features) { + if ("fabric8-karaf-checks".equals(featureValue)) { return new ProbeBuilder().withNewHttpGet(). - withNewPort(DEFAULT_HEALTH_CHECK_PORT).withPath(path).endHttpGet().withInitialDelaySeconds(initialDelay).build(); + withNewPort(DEFAULT_HEALTH_CHECK_PORT).withPath(path).endHttpGet().withInitialDelaySeconds(initialDelay).build(); } } + } else { + + String featureValue = (String) feature; + if ("fabric8-karaf-checks".equals(featureValue)) { + return new ProbeBuilder().withNewHttpGet(). + withNewPort(DEFAULT_HEALTH_CHECK_PORT).withPath(path).endHttpGet().withInitialDelaySeconds(initialDelay).build(); + } } + } + return null; } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricher.java index 8dd91d0507..4ecbb5aa16 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricher.java @@ -24,7 +24,7 @@ import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import org.apache.commons.lang3.StringUtils; @@ -43,7 +43,7 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public PrometheusEnricher(EnricherContext buildContext) { + public PrometheusEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/SpringBootHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/SpringBootHealthCheckEnricher.java index 8fa5fe4939..3888b5ba6d 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/SpringBootHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/SpringBootHealthCheckEnricher.java @@ -15,15 +15,13 @@ */ package io.fabric8.maven.enricher.fabric8; -import java.util.Properties; - import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.kubernetes.api.model.ProbeBuilder; import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.core.util.MavenUtil; import io.fabric8.maven.core.util.SpringBootConfigurationHelper; import io.fabric8.maven.core.util.SpringBootUtil; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.Properties; import org.apache.commons.lang3.StringUtils; @@ -34,7 +32,7 @@ public class SpringBootHealthCheckEnricher extends AbstractHealthCheckEnricher { public static final String ENRICHER_NAME = "f8-healthcheck-spring-boot"; - private static final String[] REQUIRED_CLASSES = { + protected static final String[] REQUIRED_CLASSES = { "org.springframework.boot.actuate.health.HealthIndicator", "org.springframework.web.context.support.GenericWebApplicationContext" }; @@ -52,7 +50,7 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public SpringBootHealthCheckEnricher(EnricherContext buildContext) { + public SpringBootHealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); } @@ -74,8 +72,8 @@ protected Probe getLivenessProbe() { protected Probe discoverSpringBootHealthCheck(Integer initialDelay, Integer period, Integer timeout) { try { - if (MavenUtil.hasAllClasses(this.getProject(), REQUIRED_CLASSES)) { - Properties properties = SpringBootUtil.getSpringBootApplicationProperties(this.getProject()); + if (getContext().isClassInCompileClasspath(true, REQUIRED_CLASSES)) { + Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProjectClassLoader().getCompileClassLoader()); return buildProbe(properties, initialDelay, period, timeout); } } catch (Exception ex) { @@ -85,7 +83,7 @@ protected Probe discoverSpringBootHealthCheck(Integer initialDelay, Integer peri } protected Probe buildProbe(Properties springBootProperties, Integer initialDelay, Integer period, Integer timeout) { - SpringBootConfigurationHelper propertyHelper = new SpringBootConfigurationHelper(SpringBootUtil.getSpringBootVersion(getContext().getProject())); + SpringBootConfigurationHelper propertyHelper = new SpringBootConfigurationHelper(getContext().getDependencyVersion(SpringBootConfigurationHelper.SPRING_BOOT_GROUP_ID, SpringBootConfigurationHelper.SPRING_BOOT_ARTIFACT_ID)); Integer managementPort = propertyHelper.getManagementPort(springBootProperties); boolean usingManagementPort = managementPort != null; diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/ThorntailV2HealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/ThorntailV2HealthCheckEnricher.java index f8b3997cb4..fc564b7235 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/ThorntailV2HealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/ThorntailV2HealthCheckEnricher.java @@ -18,16 +18,16 @@ import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.kubernetes.api.model.ProbeBuilder; import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.enricher.api.EnricherContext; - -import static io.fabric8.maven.core.util.MavenUtil.hasDependency; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enriches thorntail-v2 containers with health checks if the monitoring fraction is present. */ public class ThorntailV2HealthCheckEnricher extends AbstractHealthCheckEnricher { - public ThorntailV2HealthCheckEnricher(EnricherContext buildContext) { + public static final String IO_THORNTAIL = "io.thorntail"; + + public ThorntailV2HealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-healthcheck-thorntail-v2"); } @@ -62,13 +62,13 @@ protected Probe getLivenessProbe() { } private Probe discoverThorntailHealthCheck(int initialDelay) { - if (hasDependency(this.getProject(), "io.thorntail", "thorntail-kernel")) { + if (getContext().hasDependency(IO_THORNTAIL, "thorntail-kernel")) { // if there's thorntail-kernel, it's Thorntail v4 return null; } - if (hasDependency(this.getProject(), "io.thorntail", "monitor") - || hasDependency(this.getProject(), "io.thorntail", "microprofile-health")) { + if (getContext().hasDependency(IO_THORNTAIL, "monitor") + || getContext().hasDependency(IO_THORNTAIL, "microprofile-health")) { Integer port = getPort(); // scheme must be in upper case in k8s String scheme = getScheme().toUpperCase(); diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricher.java index 10f119764b..30d25fb2b4 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricher.java @@ -15,25 +15,20 @@ */ package io.fabric8.maven.enricher.fabric8; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Nullable; - import com.google.common.base.Function; import com.google.common.base.Optional; import io.fabric8.kubernetes.api.model.HTTPHeader; import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.kubernetes.api.model.ProbeBuilder; import io.fabric8.kubernetes.api.model.ProbeFluent; -import io.fabric8.maven.core.util.MavenUtil; -import io.fabric8.maven.enricher.api.EnricherContext; -import org.apache.maven.model.Plugin; -import org.codehaus.plexus.util.xml.Xpp3Dom; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; /** @@ -52,8 +47,8 @@ */ public class VertxHealthCheckEnricher extends AbstractHealthCheckEnricher { - private static final String VERTX_MAVEN_PLUGIN_GA = "io.fabric8:vertx-maven-plugin"; - private static final String VERTX_GROUPID = "io.vertx"; + static final String VERTX_MAVEN_PLUGIN_GA = "io.fabric8:vertx-maven-plugin"; + static final String VERTX_GROUPID = "io.vertx"; private static final int DEFAULT_MANAGEMENT_PORT = 8080; private static final String SCHEME_HTTP = "HTTP"; @@ -66,8 +61,9 @@ public String apply(@Nullable String input) { return input == null ? null : input.trim(); } }; + public static final String ERROR_MESSAGE = "Location of %s should return a String but found %s with value %s"; - public VertxHealthCheckEnricher(EnricherContext buildContext) { + public VertxHealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-healthcheck-vertx"); } @@ -81,10 +77,9 @@ protected Probe getLivenessProbe() { return discoverVertxHealthCheck(false); } - private boolean isApplicable() { - return MavenUtil.hasPlugin(getProject(), VERTX_MAVEN_PLUGIN_GA) - || MavenUtil.hasDependencyOnAnyArtifactOfGroup(getProject(), VERTX_GROUPID); + return getContext().hasPlugin(VERTX_MAVEN_PLUGIN_GA) + || getContext().hasDependencyOnAnyArtifactOfGroup(VERTX_GROUPID); } private String getSpecificPropertyName(boolean readiness, String attribute) { @@ -234,12 +229,12 @@ private Optional getStringValue(String attribute, boolean readiness) { String specific = getSpecificPropertyName(readiness, attribute); String generic = VERTX_HEALTH + attribute; // Check if we have the specific user property. - String property = getContext().getProject().getProperties().getProperty(specific); + String property = getContext().getProperties().getProperty(specific); if (property != null) { return Optional.of(property).transform(TRIM); } - property = getContext().getProject().getProperties().getProperty(generic); + property = getContext().getProperties().getProperty(generic); if (property != null) { return Optional.of(property).transform(TRIM); } @@ -266,20 +261,33 @@ private Optional> getListValue(String attribute, boolean readiness) attribute }; - Optional element = getElement(path); + Optional element = getElement(path); if (!element.isPresent()) { element = getElement(attribute); } - return element.transform(new Function>() { + return element.transform(new Function>() { @Override - public List apply(Xpp3Dom input) { - Xpp3Dom[] children = input.getChildren(); - List list = new ArrayList<>(); - for (Xpp3Dom child : children) { - list.add(child.getValue()); + public List apply(Object input) { + if (input instanceof Map) { + final Collection values = ((Map) input).values(); + List elements = new ArrayList<>(); + for (Object value : values) { + if (value instanceof List) { + List currentValues = (List) value; + elements.addAll(currentValues); + } else { + elements.add((String) value); + } + } + + return elements; + } else { + throw new IllegalArgumentException(String.format( + ERROR_MESSAGE, + attribute, input.getClass(), input.toString())); } - return list; + } }); } @@ -290,20 +298,18 @@ private Optional> getMapValue(String attribute, boolean read attribute }; - Optional element = getElement(path); + Optional element = getElement(path); if (!element.isPresent()) { element = getElement(attribute); } - return element.transform(new Function>() { - @Override - public Map apply(Xpp3Dom input) { - Xpp3Dom[] children = input.getChildren(); - Map map = new LinkedHashMap<>(); - for (Xpp3Dom child : children) { - map.put(child.getName(), child.getValue()); - } - return map; + return element.transform(input -> { + if (input instanceof Map) { + return (Map) input; + } else { + throw new IllegalArgumentException(String.format( + ERROR_MESSAGE, + attribute, input.getClass(), input.toString())); } }); } @@ -311,46 +317,47 @@ public Map apply(Xpp3Dom input) { private Optional getIntegerValue(String attribute, boolean readiness) { return getStringValue(attribute, readiness) - .transform(new Function() { - @Override - public Integer apply(String input) { - return Integer.valueOf(input); - } - }); + .transform(Integer::parseInt); } private Optional getValueFromConfig(String... keys) { - return getElement(keys).transform(new Function() { + return getElement(keys).transform(new Function() { @Override @Nullable - public String apply(Xpp3Dom input) { - return input.getValue(); + public String apply(Object input) { + if (input instanceof String) { + return (String) input; + } else { + throw new IllegalArgumentException(String.format( + ERROR_MESSAGE, + Arrays.toString(keys), input.getClass(), input.toString())); + } } }); } - private Optional getElement(String... path) { - Plugin plugin = getContext().getProject().getPlugin("io.fabric8:fabric8-maven-plugin"); - if (plugin == null) { - getLog().warn("Unable to find the fabric8-maven-plugin in the project, weird..."); + private Optional getElement(String... path) { + final Map configuration = getContext().getConfiguration("io.fabric8:fabric8-maven-plugin"); + if (configuration == null || configuration.isEmpty()) { return Optional.absent(); } - Xpp3Dom configuration = (Xpp3Dom) plugin.getConfiguration(); - if (configuration == null) { - return Optional.absent(); - } String[] roots = new String[]{"enricher", "config", "f8-healthcheck-vertx"}; List absolute = new ArrayList<>(); absolute.addAll(Arrays.asList(roots)); absolute.addAll(Arrays.asList(path)); - Xpp3Dom root = configuration; + Object root = configuration; for (String key : absolute) { - root = root.getChild(key); - if (root == null) { - return Optional.absent(); + + if (root instanceof Map) { + Map rootMap = (Map) root; + root = rootMap.get(key); + if (root == null) { + return Optional.absent(); + } } + } return Optional.of(root); } diff --git a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/WildFlySwarmHealthCheckEnricher.java b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/WildFlySwarmHealthCheckEnricher.java index 3db377e2c5..f6a828df90 100644 --- a/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/WildFlySwarmHealthCheckEnricher.java +++ b/enricher/fabric8/src/main/java/io/fabric8/maven/enricher/fabric8/WildFlySwarmHealthCheckEnricher.java @@ -18,16 +18,14 @@ import io.fabric8.kubernetes.api.model.Probe; import io.fabric8.kubernetes.api.model.ProbeBuilder; import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.enricher.api.EnricherContext; - -import static io.fabric8.maven.core.util.MavenUtil.hasDependency; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enriches wildfly-swarm containers with health checks if the monitoring fraction is present. */ public class WildFlySwarmHealthCheckEnricher extends AbstractHealthCheckEnricher { - public WildFlySwarmHealthCheckEnricher(EnricherContext buildContext) { + public WildFlySwarmHealthCheckEnricher(MavenEnricherContext buildContext) { super(buildContext, "f8-healthcheck-wildfly-swarm"); } @@ -62,8 +60,8 @@ protected Probe getLivenessProbe() { } private Probe discoverWildFlySwarmHealthCheck(int initialDelay) { - if (hasDependency(this.getProject(), "org.wildfly.swarm", "monitor") - || hasDependency(this.getProject(), "org.wildfly.swarm", "microprofile-health")) { + if (getContext().hasDependency("org.wildfly.swarm", "monitor") + || getContext().hasDependency("org.wildfly.swarm", "microprofile-health")) { Integer port = getPort(); // scheme must be in upper case in k8s String scheme = getScheme().toUpperCase(); diff --git a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/AbstractSpringBootHealthCheckEnricherSupport.java b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/AbstractSpringBootHealthCheckEnricherSupport.java index 22f2d5c6e3..3c32ecc6b8 100644 --- a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/AbstractSpringBootHealthCheckEnricherSupport.java +++ b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/AbstractSpringBootHealthCheckEnricherSupport.java @@ -15,11 +15,11 @@ */ package io.fabric8.maven.enricher.fabric8; +import io.fabric8.maven.enricher.api.util.ProjectClassLoader; +import java.net.URLClassLoader; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Properties; -import java.util.Set; import java.util.TreeMap; import io.fabric8.kubernetes.api.model.Probe; @@ -27,13 +27,11 @@ import io.fabric8.maven.core.util.MavenUtil; import io.fabric8.maven.core.util.SpringBootConfigurationHelper; import io.fabric8.maven.core.util.SpringBootUtil; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mock; import mockit.MockUp; import mockit.Mocked; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.project.MavenProject; import org.junit.Before; import org.junit.Test; @@ -50,7 +48,7 @@ public abstract class AbstractSpringBootHealthCheckEnricherSupport { @Mocked - protected EnricherContext context; + protected MavenEnricherContext context; protected SpringBootConfigurationHelper propertyHelper; @@ -59,17 +57,9 @@ public void init() { String version = getSpringBootVersion(); this.propertyHelper = new SpringBootConfigurationHelper(version); - final MavenProject project = new MavenProject(); - - Set artifacts = new HashSet<>(); - Artifact a = new DefaultArtifact("org.springframework.boot", "spring-boot", version, "compile", "jar", "", null); - a.setResolved(true); - artifacts.add(a); - - project.setArtifacts(artifacts); - new Expectations() {{ - context.getProject(); result = project; + context.getDependencyVersion(SpringBootConfigurationHelper.SPRING_BOOT_GROUP_ID, SpringBootConfigurationHelper.SPRING_BOOT_ARTIFACT_ID); + result = version; }}; } @@ -313,6 +303,15 @@ public void testDefaultInitialDelayForLivenessAndReadiness() { withAllRequiredClasses(); withProjectProperties(new Properties()); + new Expectations(){{ + context.isClassInCompileClasspath(true, SpringBootHealthCheckEnricher.REQUIRED_CLASSES); + result = true; + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader(), (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader()); + }}; + + Probe probe = enricher.getReadinessProbe(); assertNotNull(probe); assertEquals(10, probe.getInitialDelaySeconds().intValue()); @@ -334,9 +333,15 @@ public void testCustomInitialDelayForLivenessAndReadinessAndTimeout() { final ProcessorConfig config = new ProcessorConfig(null,null, globalConfig); new Expectations() {{ context.getConfig(); result = config; + context.isClassInCompileClasspath(true, SpringBootHealthCheckEnricher.REQUIRED_CLASSES); + result = true; + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader(), (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader()); }}; withAllRequiredClasses(); withProjectProperties(new Properties()); + withCompileClasslaoder(); SpringBootHealthCheckEnricher enricher = new SpringBootHealthCheckEnricher(context); @@ -368,10 +373,15 @@ public void testCustomPropertiesForLivenessAndReadiness() { final ProcessorConfig config = new ProcessorConfig(null,null, globalConfig); new Expectations() {{ context.getConfig(); result = config; + context.isClassInCompileClasspath(true, SpringBootHealthCheckEnricher.REQUIRED_CLASSES); + result = true; + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader(), (URLClassLoader) AbstractSpringBootHealthCheckEnricherSupport.class.getClassLoader()); }}; withAllRequiredClasses(); withProjectProperties(new Properties()); - + withCompileClasslaoder(); SpringBootHealthCheckEnricher enricher = new SpringBootHealthCheckEnricher(context); Probe probe = enricher.getReadinessProbe(); @@ -397,9 +407,18 @@ public boolean hasAllClasses(MavenProject project, String ... classNames) { private void withProjectProperties(final Properties properties) { new MockUp() { @Mock - public Properties getSpringBootApplicationProperties(MavenProject project) { + public Properties getSpringBootApplicationProperties(URLClassLoader urlClassLoader) { return properties; } }; } + + private void withCompileClasslaoder() { + new MockUp() { + @Mock + public URLClassLoader getCompileClassLoader(MavenProject project) { + return (URLClassLoader) this.getClass().getClassLoader(); + } + }; + } } diff --git a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricherTest.java b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricherTest.java index 80209de898..8c4cb84840 100644 --- a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricherTest.java +++ b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/DockerHealthCheckEnricherTest.java @@ -28,7 +28,7 @@ import io.fabric8.maven.docker.config.HealthCheckConfiguration; import io.fabric8.maven.docker.config.HealthCheckMode; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -46,7 +46,7 @@ public class DockerHealthCheckEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testEnrichFromSingleImage() throws Exception { diff --git a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricherTest.java b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricherTest.java index 491da9dc12..aa587affaa 100644 --- a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricherTest.java +++ b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/PrometheusEnricherTest.java @@ -24,7 +24,7 @@ import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import mockit.Expectations; import mockit.Mocked; @@ -39,7 +39,7 @@ public class PrometheusEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked ImageConfiguration imageConfiguration; diff --git a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricherTest.java b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricherTest.java index 1ea6edd69d..eeb00b6af1 100644 --- a/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricherTest.java +++ b/enricher/fabric8/src/test/java/io/fabric8/maven/enricher/fabric8/VertxHealthCheckEnricherTest.java @@ -15,20 +15,17 @@ */ package io.fabric8.maven.enricher.fabric8; +import io.fabric8.kubernetes.api.model.HTTPHeader; +import io.fabric8.kubernetes.api.model.Probe; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.maven.enricher.api.util.MavenConfigurationExtractor; import java.io.IOException; import java.io.StringReader; +import java.util.Map; import java.util.Properties; - -import io.fabric8.kubernetes.api.model.HTTPHeader; -import io.fabric8.kubernetes.api.model.Probe; -import io.fabric8.maven.enricher.api.EnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; -import org.apache.maven.model.Build; -import org.apache.maven.model.Model; -import org.apache.maven.model.Plugin; -import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -49,7 +46,7 @@ public class VertxHealthCheckEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testDefaultConfiguration() { @@ -57,7 +54,9 @@ public void testDefaultConfiguration() { final Properties props = new Properties(); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -74,7 +73,9 @@ public void testDefaultConfiguration_Enabled() { final Properties props = new Properties(); props.put("vertx.health.path", "/ping"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -102,7 +103,9 @@ public void testDifferentPathForLivenessAndReadiness() { props.put("vertx.health.readiness.path", "/ready"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -122,17 +125,8 @@ public void testDifferentPathForLivenessAndReadiness() { } - private MavenProject createFakeProject(String config) { - Model model = new Model(); - model.setArtifactId("some-artifact-id"); - model.setGroupId("some-group-id"); - model.setVersion("1.0"); - Build build = new Build(); - build.setOutputDirectory("target/classes"); - build.setDirectory("target"); - Plugin plugin = new Plugin(); - plugin.setArtifactId("fabric8-maven-plugin"); - plugin.setGroupId("io.fabric8"); + private Map createFakeConfig(String config) { + String content = "" + config + ""; @@ -142,25 +136,20 @@ private MavenProject createFakeProject(String config) { } catch (Exception e) { throw new RuntimeException(e); } - plugin.setConfiguration(dom); - build.addPlugin(plugin); - - Plugin vmp = new Plugin(); - vmp.setGroupId("io.fabric8"); - vmp.setArtifactId("vertx-maven-plugin"); - build.addPlugin(vmp); - model.setBuild(build); + return MavenConfigurationExtractor.extract(dom); - return new MavenProject(model); } @Test public void testWithCustomConfigurationComingFromConf() throws IOException, XmlPullParserException { - final MavenProject project = createFakeProject("health1234https"); + + final Map config = createFakeConfig("health1234https"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -182,14 +171,16 @@ public void testWithCustomConfigurationComingFromConf() throws IOException, XmlP @Test public void testWithCustomConfigurationForLivenessAndReadinessComingFromConf() { - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "health" + "1234" + "https" + "/ready"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -218,7 +209,9 @@ public void testCustomConfiguration() { props.put("vertx.health.port", " 8081 "); props.put("vertx.health.scheme", " https"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -238,12 +231,14 @@ public void testCustomConfiguration() { } @Test - public void testWithHttpHeaders() throws IOException, XmlPullParserException { - final MavenProject project = createFakeProject("health" + + public void testWithHttpHeaders() { + final Map config = createFakeConfig("health" + "XY"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -270,7 +265,9 @@ public void testDisabledUsingEmptyPath() { final Properties props = new Properties(); props.put("vertx.health.path", ""); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -288,7 +285,9 @@ public void testDisabledUsingNegativePort() { props.put("vertx.health.port", " -1 "); props.put("vertx.health.path", " /ping "); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -306,7 +305,9 @@ public void testDisabledUsingInvalidPort() { props.put("vertx.health.port", "not an integer"); props.put("vertx.health.path", " /ping "); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -333,7 +334,9 @@ public void testDisabledUsingPortName() { props.put("vertx.health.port-name", " health "); props.put("vertx.health.path", " /ping "); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -345,13 +348,15 @@ public void testDisabledUsingPortName() { @Test public void testDisabledUsingNegativePortUsingConfiguration() { - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "/ping" + "-1"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -370,7 +375,9 @@ public void testReadinessDisabled() { props.put("vertx.health.readiness.path", ""); props.put("vertx.health.path", "/ping"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -384,13 +391,15 @@ public void testReadinessDisabled() { @Test public void testReadinessDisabledUsingConfig() { - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "" + "/ping"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -410,7 +419,9 @@ public void testLivenessDisabledAndReadinessEnabled() { props.put("vertx.health.readiness.path", "/ping"); props.put("vertx.health.path", ""); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -424,13 +435,15 @@ public void testLivenessDisabledAndReadinessEnabled() { @Test public void testLivenessDisabledAndReadinessEnabledUsingConfig() { - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "/ping" + ""); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); @@ -451,7 +464,9 @@ public void testTCPSocketUsingUserProperties() { props.put("vertx.health.port", "1234"); props.put("vertx.health.readiness.port", "1235"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -467,14 +482,16 @@ public void testTCPSocketUsingUserProperties() { public void testTCPSocketUsingConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp" + "1234" + "1235"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -494,7 +511,9 @@ public void testTCPSocketUsingUserPropertiesAndPortName() { props.put("vertx.health.port-name", "health"); props.put("vertx.health.readiness.port-name", "ready"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -510,14 +529,16 @@ public void testTCPSocketUsingUserPropertiesAndPortName() { public void testTCPSocketUsingConfigAndPortName() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp" + "health" + "ready"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -536,7 +557,9 @@ public void testTCPSocketUsingUserPropertiesLivenessDisabled() { props.put("vertx.health.type", "tcp"); props.put("vertx.health.readiness.port", "1235"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -551,13 +574,15 @@ public void testTCPSocketUsingUserPropertiesLivenessDisabled() { public void testTCPSocketUsingConfigLivenessDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp" + "1235"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -576,7 +601,9 @@ public void testTCPSocketUsingUserPropertiesReadinessDisabled() { props.put("vertx.health.port", "1235"); props.put("vertx.health.readiness.port", "0"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -591,14 +618,16 @@ public void testTCPSocketUsingUserPropertiesReadinessDisabled() { public void testTCPSocketUsingConfigReadinessDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp" + "1235" + "-1"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -617,7 +646,9 @@ public void testTCPSocketUsingUserPropertiesIllegal() { props.put("vertx.health.port", "1235"); props.put("vertx.health.port-name", "health"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -628,14 +659,16 @@ public void testTCPSocketUsingUserPropertiesIllegal() { public void testTCPSocketUsingConfigIllegal() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp" + "1234foo" + "1235foo"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; try { @@ -661,7 +694,9 @@ public void testTCPSocketUsingUserPropertiesDisabled() { final Properties props = new Properties(); props.put("vertx.health.type", "tcp"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -675,12 +710,14 @@ public void testTCPSocketUsingUserPropertiesDisabled() { public void testTCPSocketUsingConfigDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "tcp"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -693,7 +730,7 @@ public void testTCPSocketUsingConfigDisabled() { public void testExecUsingConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "exec" + "" + "/bin/sh" + @@ -702,8 +739,10 @@ public void testExecUsingConfig() { ""); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -718,7 +757,7 @@ public void testExecUsingConfig() { public void testExecUsingConfigLivenessDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "exec" + "" + "/bin/sh" + @@ -728,8 +767,10 @@ public void testExecUsingConfigLivenessDisabled() { ""); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -743,7 +784,7 @@ public void testExecUsingConfigLivenessDisabled() { public void testExecUsingConfigReadinessDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "exec" + "" + "/bin/sh" + @@ -753,8 +794,10 @@ public void testExecUsingConfigReadinessDisabled() { ""); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -771,7 +814,9 @@ public void testExecUsingUserPropertiesDisabled() { final Properties props = new Properties(); props.put("vertx.health.type", "exec"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -785,12 +830,14 @@ public void testExecUsingUserPropertiesDisabled() { public void testExecUsingConfigDisabled() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "exec"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -806,7 +853,9 @@ public void testUnknownTypeUsingUserProperties() { final Properties props = new Properties(); props.put("vertx.health.type", "not a valid type"); new Expectations() {{ - context.getProject().getProperties(); + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); result = props; }}; @@ -830,12 +879,14 @@ public void testUnknownTypeUsingUserProperties() { public void testUnknownTypeUsingConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "not a valid type"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; try { @@ -857,17 +908,9 @@ public void testUnknownTypeUsingConfig() { public void testNotApplicableProject() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( - "execls"); - Build build = project.getBuild(); - Plugin plugin = build.getPluginsAsMap().get("io.fabric8:vertx-maven-plugin"); - build.removePlugin(plugin); - build.getPluginsAsMap().remove("io.fabric8:vertx-maven-plugin"); - project.setBuild(build); - new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = false; }}; Probe probe = enricher.getLivenessProbe(); @@ -880,7 +923,7 @@ public void testNotApplicableProject() { public void testThatWeCanUSeDifferentTypesForLivenessAndReadiness() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "" + " exec" + " ls" + @@ -889,8 +932,10 @@ public void testThatWeCanUSeDifferentTypesForLivenessAndReadiness() { " /ping" + ""); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getLivenessProbe(); @@ -905,7 +950,7 @@ public void testThatWeCanUSeDifferentTypesForLivenessAndReadiness() { public void testThatGenericUserPropertiesOverrideSpecificConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "" + " exec" + " ls" + @@ -916,11 +961,14 @@ public void testThatGenericUserPropertiesOverrideSpecificConfig() { Properties properties = new Properties(); properties.put("vertx.health.type", "tcp"); properties.put("vertx.health.port", "1234"); - project.getModel().setProperties(properties); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); + result = properties; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); @@ -940,18 +988,21 @@ public void testThatGenericUserPropertiesOverrideSpecificConfig() { public void testThatGenericUserPropertiesOverrideGenericConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "exec" + " ls" ); Properties properties = new Properties(); properties.put("vertx.health.type", "tcp"); properties.put("vertx.health.port", "1234"); - project.getModel().setProperties(properties); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); + result = properties; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); @@ -971,7 +1022,7 @@ public void testThatGenericUserPropertiesOverrideGenericConfig() { public void testThatSpecificUserPropertiesOverrideSpecificConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "" + " /ping" + "" + @@ -982,10 +1033,13 @@ public void testThatSpecificUserPropertiesOverrideSpecificConfig() { properties.put("vertx.health.readiness.type", "tcp"); properties.put("vertx.health.readiness.port", "1234"); properties.put("vertx.health.port", "1235"); - project.getModel().setProperties(properties); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); + result = properties; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); @@ -1005,16 +1059,19 @@ public void testThatSpecificUserPropertiesOverrideSpecificConfig() { public void testThatSpecificUserPropertiesOverrideGenericConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "/pinghttp"); Properties properties = new Properties(); properties.put("vertx.health.readiness.type", "tcp"); properties.put("vertx.health.readiness.port", "1234"); properties.put("vertx.health.port", "1235"); - project.getModel().setProperties(properties); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); + result = properties; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); @@ -1034,7 +1091,7 @@ public void testThatSpecificUserPropertiesOverrideGenericConfig() { public void testThatSpecificConfigOverrideGenericConfig() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "" + " /live" + "" + @@ -1045,8 +1102,10 @@ public void testThatSpecificConfigOverrideGenericConfig() { "/health" + "health"); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); @@ -1066,7 +1125,7 @@ public void testThatSpecificConfigOverrideGenericConfig() { public void testThatSpecificUserPropertiesOverrideGenericUserProperties() { VertxHealthCheckEnricher enricher = new VertxHealthCheckEnricher(context); - final MavenProject project = createFakeProject( + final Map config = createFakeConfig( "/pinghttp"); Properties properties = new Properties(); properties.put("vertx.health.readiness.type", "tcp"); @@ -1074,10 +1133,13 @@ public void testThatSpecificUserPropertiesOverrideGenericUserProperties() { properties.put("vertx.health.port", "1235"); properties.put("vertx.health.liveness.type", "tcp"); properties.put("vertx.health.liveness.port", "1236"); - project.getModel().setProperties(properties); new Expectations() {{ - context.getProject(); - result = project; + context.hasPlugin(VertxHealthCheckEnricher.VERTX_MAVEN_PLUGIN_GA); + result = true; + context.getProperties(); + result = properties; + context.getConfiguration("io.fabric8:fabric8-maven-plugin"); + result = config; }}; Probe probe = enricher.getReadinessProbe(); diff --git a/enricher/osio/src/main/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricher.java b/enricher/osio/src/main/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricher.java index 993533c8f5..e5ccb8b7cc 100644 --- a/enricher/osio/src/main/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricher.java +++ b/enricher/osio/src/main/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricher.java @@ -20,7 +20,7 @@ import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; /** @@ -41,7 +41,7 @@ public String def() { } } - public SpaceLabelEnricher(EnricherContext buildContext) { + public SpaceLabelEnricher(MavenEnricherContext buildContext) { super(buildContext, "osio-space-label"); } diff --git a/enricher/osio/src/test/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricherTest.java b/enricher/osio/src/test/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricherTest.java index c32115e239..8580b44107 100644 --- a/enricher/osio/src/test/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricherTest.java +++ b/enricher/osio/src/test/java/io/fabric8/maven/enricher/osio/SpaceLabelEnricherTest.java @@ -15,15 +15,14 @@ */ package io.fabric8.maven.enricher.osio; +import com.google.common.collect.ImmutableMap; +import io.fabric8.maven.core.config.ProcessorConfig; +import io.fabric8.maven.enricher.api.Kind; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.TreeMap; - -import com.google.common.collect.ImmutableMap; -import io.fabric8.maven.core.config.ProcessorConfig; -import io.fabric8.maven.enricher.api.EnricherContext; -import io.fabric8.maven.enricher.api.Kind; import mockit.Expectations; import mockit.Mock; import mockit.MockUp; @@ -40,7 +39,7 @@ public class SpaceLabelEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; private static final String SPACE_KEY = "fabric8.enricher.osio-space-label.space"; private static final String SPACE_VALUE = "test"; @@ -49,7 +48,7 @@ public class SpaceLabelEnricherTest { public void testDefaultConfiguration() { final Properties props = new Properties(); new Expectations() {{ - context.getProject().getProperties(); + context.getProperties(); result = props; }}; @@ -71,7 +70,7 @@ public void testLabelSystemProperty() { final Properties props = new Properties(); new Expectations() {{ - context.getProject().getProperties(); + context.getProperties(); result = props; }}; @@ -85,7 +84,7 @@ public void testLabelMavenProperty() { final Properties props = new Properties(); props.put(SPACE_KEY, SPACE_VALUE); new Expectations() {{ - context.getProject().getProperties(); + context.getProperties(); result = props; }}; diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DebugEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DebugEnricher.java index 063c219bab..be568190d8 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DebugEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DebugEnricher.java @@ -1,12 +1,12 @@ /** * Copyright 2016 Red Hat, Inc. - * + *

* Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or @@ -15,9 +15,6 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.ArrayList; -import java.util.List; - import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerPort; import io.fabric8.kubernetes.api.model.EnvVar; @@ -27,18 +24,19 @@ import io.fabric8.kubernetes.api.model.PodTemplateSpec; import io.fabric8.kubernetes.api.model.ReplicationController; import io.fabric8.kubernetes.api.model.ReplicationControllerSpec; -import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; -import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.api.model.apps.ReplicaSetSpec; +import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; +import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.DeploymentConfig; import io.fabric8.openshift.api.model.DeploymentConfigSpec; +import java.util.ArrayList; +import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.project.MavenProject; import static io.fabric8.maven.core.util.DebugConstants.ENV_VAR_JAVA_DEBUG; import static io.fabric8.maven.core.util.DebugConstants.ENV_VAR_JAVA_DEBUG_PORT; @@ -51,7 +49,7 @@ public class DebugEnricher extends BaseEnricher { public static final String ENABLE_DEBUG_MAVEN_PROPERTY = "fabric8.debug.enabled"; - public DebugEnricher(EnricherContext buildContext) { + public DebugEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-debug"); } @@ -70,19 +68,22 @@ public void addMissingResources(KubernetesListBuilder builder) { if (count > 0) { builder.withItems(items); } - log.verbose("Enabled debugging on " + count + " resource(s) thanks to the " + ENABLE_DEBUG_MAVEN_PROPERTY + " property"); + log.verbose("Enabled debugging on " + + count + + " resource(s) thanks to the " + + ENABLE_DEBUG_MAVEN_PROPERTY + + " property"); } else { - log.verbose("Debugging not enabled. To enable try setting the " + ENABLE_DEBUG_MAVEN_PROPERTY + " maven or system property to 'true'"); + log.verbose("Debugging not enabled. To enable try setting the " + + ENABLE_DEBUG_MAVEN_PROPERTY + + " maven or system property to 'true'"); } } private boolean debugEnabled() { - MavenProject project = getContext().getProject(); - if (project != null) { - String value = project.getProperties().getProperty(ENABLE_DEBUG_MAVEN_PROPERTY); - if (isTrueFlag(value)) { - return true; - }; + String value = getContext().getProperties().getProperty(ENABLE_DEBUG_MAVEN_PROPERTY); + if (value != null && isTrueFlag(value)) { + return true; } return isTrueFlag(System.getProperty(ENABLE_DEBUG_MAVEN_PROPERTY)); } @@ -91,7 +92,6 @@ private static boolean isTrueFlag(String value) { return StringUtils.isNotBlank(value) && value.equals("true"); } - private boolean enableDebug(HasMetadata entity) { if (entity instanceof Deployment) { Deployment resource = (Deployment) entity; @@ -132,7 +132,8 @@ private boolean enableDebugging(HasMetadata entity, PodTemplateSpec template) { if (env == null) { env = new ArrayList<>(); } - String remoteDebugPort = KubernetesResourceUtil.getEnvVar(env, ENV_VAR_JAVA_DEBUG_PORT, ENV_VAR_JAVA_DEBUG_PORT_DEFAULT); + String remoteDebugPort = + KubernetesResourceUtil.getEnvVar(env, ENV_VAR_JAVA_DEBUG_PORT, ENV_VAR_JAVA_DEBUG_PORT_DEFAULT); boolean enabled = false; if (KubernetesResourceUtil.setEnvVar(env, ENV_VAR_JAVA_DEBUG, "true")) { container.setEnv(env); @@ -147,7 +148,8 @@ private boolean enableDebugging(HasMetadata entity, PodTemplateSpec template) { enabled = true; } if (enabled) { - log.info("Enabling debug on " + KubernetesHelper.getKind(entity) + " " + KubernetesHelper.getName(entity) + " due to the property: " + ENABLE_DEBUG_MAVEN_PROPERTY); + log.info("Enabling debug on " + KubernetesHelper.getKind(entity) + " " + KubernetesHelper.getName( + entity) + " due to the property: " + ENABLE_DEBUG_MAVEN_PROPERTY); return true; } } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricher.java index 26352c3bf4..b26801485c 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricher.java @@ -15,13 +15,16 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.List; - import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.PodSpec; import io.fabric8.kubernetes.api.model.PodSpecBuilder; -import io.fabric8.kubernetes.api.model.apps.*; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentFluent; +import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; +import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSetFluent; +import io.fabric8.kubernetes.api.model.apps.StatefulSetSpec; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.handler.DaemonSetHandler; import io.fabric8.maven.core.handler.DeploymentHandler; @@ -35,7 +38,8 @@ import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.List; /** * Enrich with controller if not already present. @@ -75,10 +79,11 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public DefaultControllerEnricher(EnricherContext buildContext) { + public DefaultControllerEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-controller"); - HandlerHub handlers = new HandlerHub(buildContext.getProject()); + HandlerHub handlers = new HandlerHub(getContext().getProjectClassLoader().getCompileClassLoader(), + getContext().getBuildOutputDirectory(), getContext().getArtifact(), getContext().getProperties()); rcHandler = handlers.getReplicationControllerHandler(); rsHandler = handlers.getReplicaSetHandler(); deployHandler = handlers.getDeploymentHandler(); @@ -89,7 +94,7 @@ public DefaultControllerEnricher(EnricherContext buildContext) { @Override public void addMissingResources(KubernetesListBuilder builder) { - final String name = getConfig(Config.name, MavenUtil.createDefaultResourceName(getProject())); + final String name = getConfig(Config.name, MavenUtil.createDefaultResourceName(getContext().getArtifact().getArtifactId())); final ResourceConfig config = new ResourceConfig.Builder() .controllerName(name) .imagePullPolicy(getConfig(Config.pullPolicy)) diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricher.java index 0be88ae25e..21435eff34 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricher.java @@ -15,18 +15,6 @@ */ package io.fabric8.maven.enricher.standard; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import io.fabric8.ianaservicehelper.Helper; import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.IntOrString; @@ -44,7 +32,18 @@ import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.maven.shared.utils.StringUtils; /** @@ -92,7 +91,7 @@ private enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public DefaultServiceEnricher(EnricherContext buildContext) { + public DefaultServiceEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-service"); } @@ -121,7 +120,7 @@ private Service getDefaultService() { ServiceBuilder builder = new ServiceBuilder() .withNewMetadata() - .withName(getConfig(Config.name, MavenUtil.createDefaultResourceName(getProject()))) + .withName(getConfig(Config.name, MavenUtil.createDefaultResourceName(getContext().getArtifact().getArtifactId()))) .withLabels(extractLabels()) .endMetadata(); ServiceFluent.SpecNested specBuilder = builder.withNewSpec(); @@ -410,7 +409,7 @@ private ServicePort shiftOrNull(List ports) { private String getDefaultServiceName(Service defaultService) { String defaultServiceName = KubernetesHelper.getName(defaultService); if (StringUtils.isBlank(defaultServiceName)) { - defaultServiceName = getProject().getArtifactId(); + defaultServiceName = getContext().getArtifact().getArtifactId(); } return defaultServiceName; } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DependencyEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DependencyEnricher.java index be64dfb9dd..50ea5561bd 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DependencyEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DependencyEnricher.java @@ -15,6 +15,20 @@ */ package io.fabric8.maven.enricher.standard; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.google.common.base.Function; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.maven.core.util.Configs; +import io.fabric8.maven.core.util.KindAndName; +import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; +import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; +import io.fabric8.maven.enricher.api.BaseEnricher; +import io.fabric8.maven.enricher.api.Dependency; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.openshift.api.model.Template; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -30,22 +44,6 @@ import java.util.Objects; import java.util.Set; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.google.common.base.Function; -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.api.model.KubernetesList; -import io.fabric8.kubernetes.api.model.KubernetesListBuilder; -import io.fabric8.maven.core.util.Configs; -import io.fabric8.maven.core.util.KindAndName; -import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; -import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; -import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; -import io.fabric8.openshift.api.model.Template; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.MojoExecutionException; - /** * Enricher for embedding dependency descriptors to single package. * @@ -78,22 +76,21 @@ public String def() { } } - public DependencyEnricher(EnricherContext buildContext) { + public DependencyEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-dependency"); - addArtifactsWithYaml(buildContext, kubernetesDependencyArtifacts, DEPENDENCY_KUBERNETES_YAML); - addArtifactsWithYaml(buildContext, kubernetesTemplateDependencyArtifacts, DEPENDENCY_KUBERNETES_TEMPLATE_YAML); - addArtifactsWithYaml(buildContext, openshiftDependencyArtifacts, DEPENDENCY_OPENSHIFT_YAML); + addArtifactsWithYaml(kubernetesDependencyArtifacts, DEPENDENCY_KUBERNETES_YAML); + addArtifactsWithYaml(kubernetesTemplateDependencyArtifacts, DEPENDENCY_KUBERNETES_TEMPLATE_YAML); + addArtifactsWithYaml(openshiftDependencyArtifacts, DEPENDENCY_OPENSHIFT_YAML); } - private void addArtifactsWithYaml(EnricherContext buildContext, Set artifactSet, String dependencyYaml) { - Set artifacts = isIncludeTransitive() ? - buildContext.getProject().getArtifacts() : buildContext.getProject().getDependencyArtifacts(); + private void addArtifactsWithYaml(Set artifactSet, String dependencyYaml) { + final List artifacts = getContext().getDependencies(isIncludeTransitive()); - for (Artifact artifact : artifacts) { - if (Artifact.SCOPE_COMPILE.equals(artifact.getScope()) && "jar".equals(artifact.getType())) { - File file = artifact.getFile(); + for (Dependency artifact : artifacts) { + if ("compile".equals(artifact.getScope()) && "jar".equals(artifact.getType())) { + File file = artifact.getLocation(); try { URL url = new URL("jar:" + file.toURI().toURL() + "!/" + dependencyYaml); artifactSet.add(url); @@ -159,7 +156,7 @@ public Void apply(List items) { boolean isAppCatalog = false; try { isAppCatalog = getContext().runningWithGoal("fabric8:app-catalog"); - } catch (MojoExecutionException e) { + } catch (IllegalStateException e) { log.warn("Caught: %s", e); } getContext().getOpenshiftDependencyResources().addOpenShiftResources(items, isAppCatalog); diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricher.java index d44eb60ec0..d51a1d1df1 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricher.java @@ -15,12 +15,12 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.HashMap; -import java.util.Map; - import io.fabric8.maven.core.util.DockerServerUtil; import io.fabric8.maven.core.util.SecretConstants; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.DockerRegistryAuthentication; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.lang3.StringUtils; public class DockerRegistrySecretEnricher extends SecretEnricher { @@ -28,7 +28,7 @@ public class DockerRegistrySecretEnricher extends SecretEnricher { final private static String ENRICHER_NAME = "fmp-docker-registry-secret"; - public DockerRegistrySecretEnricher(EnricherContext buildContext) { + public DockerRegistrySecretEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); } @@ -39,7 +39,13 @@ protected String getAnnotationKey() { @Override protected Map generateData(String dockerId) { - String dockerSecret = DockerServerUtil.getDockerJsonConfigString(getContext().getSettings(), dockerId); + final DockerRegistryAuthentication dockerRegistryAuth = getContext().getDockerRegistryAuth(dockerId); + + if (dockerRegistryAuth == null) { + return null; + } + + String dockerSecret = DockerServerUtil.getDockerJsonConfigString(dockerId, dockerRegistryAuth.asMap()); if (StringUtils.isBlank(dockerSecret)) { return null; } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/GitEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/GitEnricher.java index d4b6d0b31a..f0e67f2015 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/GitEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/GitEnricher.java @@ -22,7 +22,7 @@ import io.fabric8.maven.core.util.GitUtil; import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; @@ -39,7 +39,7 @@ */ public class GitEnricher extends BaseEnricher { - public GitEnricher(EnricherContext buildContext) { + public GitEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-git"); } @@ -50,7 +50,7 @@ public Map getAnnotations(Kind kind) { try { if (kind.isController() || kind == Kind.SERVICE) { // Git annotations (if git is used as SCM) - repository = GitUtil.getGitRepository(getProject()); + repository = GitUtil.getGitRepository(getContext().getCurrentDir()); if (repository != null) { String branch = repository.getBranch(); if (branch != null) { diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/IANAServicePortNameEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/IANAServicePortNameEnricher.java index 61eaf722c6..ba2a251441 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/IANAServicePortNameEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/IANAServicePortNameEnricher.java @@ -22,7 +22,7 @@ import io.fabric8.kubernetes.api.model.ContainerPortBuilder; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import static io.fabric8.ianaservicehelper.Helper.serviceNames; @@ -30,7 +30,7 @@ * Enrich container ports with names with names of IANA registered services, if not already present. */ public class IANAServicePortNameEnricher extends BaseEnricher { - public IANAServicePortNameEnricher(EnricherContext buildContext) { + public IANAServicePortNameEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-ianaservice"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ImageEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ImageEnricher.java index 4a3c0b0f2c..0e8caab7df 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ImageEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ImageEnricher.java @@ -15,11 +15,6 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.EnvVar; @@ -29,16 +24,31 @@ import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; import io.fabric8.kubernetes.api.model.ReplicationControllerFluent; import io.fabric8.kubernetes.api.model.ReplicationControllerSpecFluent; -import io.fabric8.kubernetes.api.model.apps.*; +import io.fabric8.kubernetes.api.model.apps.DaemonSetBuilder; +import io.fabric8.kubernetes.api.model.apps.DaemonSetFluent; +import io.fabric8.kubernetes.api.model.apps.DaemonSetSpecFluent; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import io.fabric8.kubernetes.api.model.apps.DeploymentFluent; +import io.fabric8.kubernetes.api.model.apps.DeploymentSpecFluent; +import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder; +import io.fabric8.kubernetes.api.model.apps.ReplicaSetFluent; +import io.fabric8.kubernetes.api.model.apps.ReplicaSetSpecFluent; +import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSetFluent; +import io.fabric8.kubernetes.api.model.apps.StatefulSetSpecFluent; import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.maven.docker.config.ImageConfiguration; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.DeploymentConfigBuilder; import io.fabric8.openshift.api.model.DeploymentConfigFluent; import io.fabric8.openshift.api.model.DeploymentConfigSpecFluent; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import static io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil.extractContainerName; @@ -61,7 +71,7 @@ */ public class ImageEnricher extends BaseEnricher { - public ImageEnricher(EnricherContext buildContext) { + public ImageEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-image"); } @@ -226,7 +236,7 @@ private Container getContainer(int idx, List containers) { private void mergeContainerName(ImageConfiguration imageConfiguration, Container container) { if (StringUtils.isBlank(container.getName())) { - String containerName = extractContainerName(getProject(), imageConfiguration); + String containerName = extractContainerName(getContext().getArtifact(), imageConfiguration); log.verbose("Setting container name %s",containerName); container.setName(containerName); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricher.java index 1467d66acc..9add1c7829 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricher.java @@ -15,13 +15,12 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.HashMap; -import java.util.Map; - import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; import io.fabric8.maven.enricher.api.Kind; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.IssueManagement; import org.apache.maven.project.MavenProject; @@ -39,7 +38,7 @@ public class MavenIssueManagementEnricher extends BaseEnricher { static final String ENRICHER_NAME = "fmp-maven-issue-mgmt"; - public MavenIssueManagementEnricher(EnricherContext buildContext) { + public MavenIssueManagementEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); } @@ -47,15 +46,18 @@ public MavenIssueManagementEnricher(EnricherContext buildContext) { public Map getAnnotations(Kind kind) { Map annotations = new HashMap<>(); if (kind.isController() || kind == Kind.SERVICE) { - MavenProject rootProject = getProject(); - if (hasIssueManagement(rootProject)) { - IssueManagement issueManagement = rootProject.getIssueManagement(); - String system = issueManagement.getSystem(); - String url = issueManagement.getUrl(); - if (StringUtils.isNotEmpty(system) && StringUtils.isNotEmpty(url)) { - annotations.put(Fabric8Annotations.ISSUE_SYSTEM.value(), system); - annotations.put(Fabric8Annotations.ISSUE_TRACKER_URL.value(), url); - return annotations; + if (getContext() instanceof MavenEnricherContext) { + MavenEnricherContext mavenEnricherContext = (MavenEnricherContext) getContext(); + MavenProject rootProject = mavenEnricherContext.getProject(); + if (hasIssueManagement(rootProject)) { + IssueManagement issueManagement = rootProject.getIssueManagement(); + String system = issueManagement.getSystem(); + String url = issueManagement.getUrl(); + if (StringUtils.isNotEmpty(system) && StringUtils.isNotEmpty(url)) { + annotations.put(Fabric8Annotations.ISSUE_SYSTEM.value(), system); + annotations.put(Fabric8Annotations.ISSUE_TRACKER_URL.value(), url); + return annotations; + } } } } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenScmEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenScmEnricher.java index e20e53b42b..8165404ffc 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenScmEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MavenScmEnricher.java @@ -15,13 +15,12 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.HashMap; -import java.util.Map; - import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; import io.fabric8.maven.enricher.api.Kind; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.Scm; import org.apache.maven.project.MavenProject; @@ -41,7 +40,7 @@ public class MavenScmEnricher extends BaseEnricher { static final String ENRICHER_NAME = "fmp-maven-scm"; - public MavenScmEnricher(EnricherContext buildContext) { + public MavenScmEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); } @@ -49,17 +48,20 @@ public MavenScmEnricher(EnricherContext buildContext) { public Map getAnnotations(Kind kind) { Map annotations = new HashMap<>(); if (kind.isController() || kind == Kind.SERVICE) { - MavenProject rootProject = getProject(); - if (hasScm(rootProject)) { - Scm scm = rootProject.getScm(); - String url = scm.getUrl(); - String tag = scm.getTag(); + if (getContext() instanceof MavenEnricherContext) { + MavenEnricherContext mavenEnricherContext = (MavenEnricherContext) getContext(); + MavenProject rootProject = mavenEnricherContext.getProject(); + if (hasScm(rootProject)) { + Scm scm = rootProject.getScm(); + String url = scm.getUrl(); + String tag = scm.getTag(); - if (StringUtils.isNotEmpty(tag)) { - annotations.put(Fabric8Annotations.SCM_TAG.value(), tag); - } - if (StringUtils.isNotEmpty(url)) { - annotations.put(Fabric8Annotations.SCM_URL.value(), url); + if (StringUtils.isNotEmpty(tag)) { + annotations.put(Fabric8Annotations.SCM_TAG.value(), tag); + } + if (StringUtils.isNotEmpty(url)) { + annotations.put(Fabric8Annotations.SCM_URL.value(), url); + } } } } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MergeEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MergeEnricher.java index 2ab01c569b..7cb8a0d940 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MergeEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/MergeEnricher.java @@ -15,19 +15,17 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; -import org.apache.maven.plugin.MojoExecutionException; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Merges local resources with dependent resources which have the same name. @@ -42,7 +40,7 @@ */ public class MergeEnricher extends BaseEnricher { - public MergeEnricher(EnricherContext buildContext) { + public MergeEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-merge"); } @@ -90,7 +88,7 @@ private HasMetadata mergeEntities(HasMetadata item1, HasMetadata item2) { if (!getContext().runningWithGoal("fabric8:app-catalog")) { log.warn("Duplicate resources for %s %s from %s and %s", KubernetesHelper.getKind(item1), KubernetesHelper.getName(item1), KubernetesResourceUtil.getSourceUrlAnnotation(item1), KubernetesResourceUtil.getSourceUrlAnnotation(item2)); } - } catch (MojoExecutionException e) { + } catch (IllegalStateException e) { log.warn("Failed to check if generated an app-catalog: %s", e); } return null; diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/NameEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/NameEnricher.java index 27992bc548..776bea4934 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/NameEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/NameEnricher.java @@ -28,7 +28,7 @@ import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.MavenUtil; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import org.apache.commons.lang3.StringUtils; /** @@ -42,7 +42,7 @@ */ public class NameEnricher extends BaseEnricher { - public NameEnricher(EnricherContext buildContext) { + public NameEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-name"); } @@ -53,7 +53,7 @@ private enum Config implements Configs.Key { @Override public void addMissingResources(KubernetesListBuilder builder) { - final String defaultName = getConfig(Config.name, MavenUtil.createDefaultResourceName(getProject())); + final String defaultName = getConfig(Config.name, MavenUtil.createDefaultResourceName(getContext().getArtifact().getArtifactId())); builder.accept(new TypedVisitor() { @Override diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PodAnnotationEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PodAnnotationEnricher.java index 1eb16eff41..76f35e9f63 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PodAnnotationEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PodAnnotationEnricher.java @@ -25,14 +25,14 @@ import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; import io.fabric8.maven.core.util.MapUtil; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enricher which copies the annotation from a Deployment to the annotations of * container Pod spec. */ public class PodAnnotationEnricher extends BaseEnricher { - public PodAnnotationEnricher(EnricherContext buildContext) { + public PodAnnotationEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-pod-annotations"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PortNameEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PortNameEnricher.java index 59d58f041f..1c523d5538 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PortNameEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/PortNameEnricher.java @@ -23,13 +23,13 @@ import io.fabric8.kubernetes.api.model.ContainerPortBuilder; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enrich container ports with names with names of IANA registered services, if not already present. */ public class PortNameEnricher extends BaseEnricher { - public PortNameEnricher(EnricherContext buildContext) { + public PortNameEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-portname"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ProjectEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ProjectEnricher.java index 4b17149e1c..bb3212a12f 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ProjectEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/ProjectEnricher.java @@ -15,18 +15,17 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.HashMap; -import java.util.Map; - import io.fabric8.kubernetes.api.builder.TypedVisitor; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.MapUtil; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; -import org.apache.maven.project.MavenProject; +import java.util.HashMap; +import java.util.Map; /** * Add project labels to any object. @@ -57,7 +56,7 @@ private enum Config implements Configs.Key { } } - public ProjectEnricher(EnricherContext buildContext) { + public ProjectEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-project"); } @@ -83,21 +82,21 @@ private Map createLabels() { } private Map createLabels(boolean withoutVersion) { - MavenProject project = getProject(); Map ret = new HashMap<>(); boolean enableProjectLabel = Configs.asBoolean(getConfig(Config.useProjectLabel)); + final Artifact artifact = getContext().getArtifact(); if (enableProjectLabel) { - ret.put("project", project.getArtifactId()); + ret.put("project", artifact.getArtifactId()); } else { // default label is app - ret.put("app", project.getArtifactId()); + ret.put("app", artifact.getArtifactId()); } - ret.put("group", project.getGroupId()); + ret.put("group", artifact.getGroupId()); ret.put("provider", "fabric8"); if (!withoutVersion) { - ret.put("version", project.getVersion()); + ret.put("version", artifact.getVersion()); } return ret; } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RemoveBuildAnnotationsEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RemoveBuildAnnotationsEnricher.java index d2c447cbb9..612be3cb29 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RemoveBuildAnnotationsEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RemoveBuildAnnotationsEnricher.java @@ -22,7 +22,7 @@ import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import static io.fabric8.maven.core.util.Constants.RESOURCE_SOURCE_URL_ANNOTATION; @@ -31,7 +31,7 @@ */ public class RemoveBuildAnnotationsEnricher extends BaseEnricher { - public RemoveBuildAnnotationsEnricher(EnricherContext buildContext) { + public RemoveBuildAnnotationsEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-remove-build-annotations"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricher.java index 4894772643..17e92460d2 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricher.java @@ -20,7 +20,7 @@ import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * This enricher adds the 'revisionHistoryLimit' property to deployment spec of RCs / RSs for KuberNetes/OpenShift resource descriptors. @@ -40,7 +40,7 @@ enum Config implements Configs.Key { public String def() { return d; } } - public RevisionHistoryEnricher(EnricherContext buildContext) { + public RevisionHistoryEnricher(MavenEnricherContext buildContext) { super(buildContext, DEFAULT_NAME); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/SecretEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/SecretEnricher.java index 93e768fcc2..b8bd29482a 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/SecretEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/SecretEnricher.java @@ -22,11 +22,11 @@ import io.fabric8.kubernetes.api.model.SecretBuilder; import io.fabric8.maven.core.util.Base64Util; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; public abstract class SecretEnricher extends BaseEnricher { - public SecretEnricher(EnricherContext buildContext, String name) { + public SecretEnricher(MavenEnricherContext buildContext, String name) { super(buildContext, name); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricher.java index d2dccc1629..b176bbd80c 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricher.java @@ -35,7 +35,7 @@ import io.fabric8.maven.core.util.ResourceUtil; import io.fabric8.maven.docker.util.ImageName; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.ImageChangeTrigger; import io.fabric8.openshift.api.model.ImageChangeTriggerBuilder; @@ -63,7 +63,7 @@ private enum Config implements Configs.Key { } - public TriggersAnnotationEnricher(EnricherContext buildContext) { + public TriggersAnnotationEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-triggers-annotation"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricher.java index 5063afe13f..74a8de38e8 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricher.java @@ -25,7 +25,7 @@ import io.fabric8.kubernetes.api.model.*; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.util.InitContainerHandler; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; @@ -50,7 +50,7 @@ enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public VolumePermissionEnricher(EnricherContext buildContext) { + public VolumePermissionEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); initContainerHandler = new InitContainerHandler(buildContext.getLog()); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/WatchEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/WatchEnricher.java index 1d660c4b29..6521bd5297 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/WatchEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/WatchEnricher.java @@ -23,7 +23,7 @@ import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.DeploymentConfigBuilder; /** @@ -34,7 +34,7 @@ */ public class WatchEnricher extends BaseEnricher { - public WatchEnricher(EnricherContext buildContext) { + public WatchEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-watch"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricher.java index 9bb7e65a01..1dcf99a907 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricher.java @@ -23,7 +23,7 @@ import io.fabric8.kubernetes.api.model.*; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import io.fabric8.maven.enricher.api.util.InitContainerHandler; @@ -68,10 +68,10 @@ enum Config implements Configs.Key { public String def() { return d; } protected String d; } - public AutoTLSEnricher(EnricherContext buildContext) { + public AutoTLSEnricher(MavenEnricherContext buildContext) { super(buildContext, ENRICHER_NAME); - this.secretName = getConfig(Config.tlsSecretName, getProject().getArtifactId() + "-tls"); + this.secretName = getConfig(Config.tlsSecretName, getContext().getArtifact().getArtifactId() + "-tls"); this.initContainerHandler = new InitContainerHandler(buildContext.getLog()); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/ExposeEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/ExposeEnricher.java index 16f11d8198..bd25c95702 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/ExposeEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/ExposeEnricher.java @@ -30,14 +30,14 @@ import io.fabric8.kubernetes.api.model.ServiceSpec; import io.fabric8.maven.core.util.kubernetes.KubernetesHelper; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; /** * Enricher for enabling exposing of HTTP / HTTPS based services */ public class ExposeEnricher extends BaseEnricher { - public ExposeEnricher(EnricherContext buildContext) { + public ExposeEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-openshift-service-expose"); } diff --git a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/RouteEnricher.java b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/RouteEnricher.java index 87d248d425..6f3aa14918 100644 --- a/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/RouteEnricher.java +++ b/enricher/standard/src/main/java/io/fabric8/maven/enricher/standard/openshift/RouteEnricher.java @@ -31,7 +31,7 @@ import io.fabric8.kubernetes.api.model.ServiceSpec; import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; import io.fabric8.maven.enricher.api.BaseEnricher; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.Route; import io.fabric8.openshift.api.model.RouteBuilder; import io.fabric8.openshift.api.model.RoutePort; @@ -41,7 +41,7 @@ */ public class RouteEnricher extends BaseEnricher { - public RouteEnricher(EnricherContext buildContext) { + public RouteEnricher(MavenEnricherContext buildContext) { super(buildContext, "fmp-openshift-route"); } diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricherTest.java index a2ab287721..44381c131a 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultControllerEnricherTest.java @@ -15,19 +15,21 @@ */ package io.fabric8.maven.enricher.standard; -import java.util.Arrays; -import java.util.Collections; -import java.util.TreeMap; - import com.google.common.io.Files; import com.jayway.jsonpath.matchers.JsonPathMatchers; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.core.config.ProcessorConfig; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.core.util.ResourceUtil; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.maven.enricher.api.util.ProjectClassLoader; +import java.net.URLClassLoader; +import java.util.Arrays; +import java.util.Collections; +import java.util.TreeMap; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -47,7 +49,7 @@ public class DefaultControllerEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked ImageConfiguration imageConfiguration; @@ -91,17 +93,15 @@ protected void enrichAndAssert(int sizeOfObjects, int replicaCount) throws com.f } protected void setupExpectations(final BuildImageConfiguration buildConfig, final TreeMap controllerConfig) { + new Expectations() {{ - project.getArtifactId(); - result = "fmp-controller-test"; + context.getArtifact(); + result = new Artifact("", "fmp-controller-test", "0"); - project.getBuild().getOutputDirectory(); + context.getBuildOutputDirectory(); result = Files.createTempDir().getAbsolutePath(); - context.getProject(); - result = project; - context.getConfig(); result = new ProcessorConfig(null, null, Collections.singletonMap("fmp-controller", controllerConfig)); @@ -114,6 +114,9 @@ protected void setupExpectations(final BuildImageConfiguration buildConfig, fina context.getImages(); result = Arrays.asList(imageConfiguration); + + context.getProjectClassLoader(); + result = new ProjectClassLoader((URLClassLoader) DefaultControllerEnricherTest.class.getClassLoader(), (URLClassLoader) DefaultControllerEnricherTest.class.getClassLoader()); }}; } } diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricherTest.java index 8dfc2f9cf8..685f468cc8 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DefaultServiceEnricherTest.java @@ -26,7 +26,7 @@ import io.fabric8.maven.core.util.ResourceUtil; import io.fabric8.maven.docker.config.BuildImageConfiguration; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -49,7 +49,7 @@ public class DefaultServiceEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked ImageConfiguration imageConfiguration; diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DependencyEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DependencyEnricherTest.java index 3c54789dab..d1afa5b577 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DependencyEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DependencyEnricherTest.java @@ -20,6 +20,14 @@ * @since 06/11/17 */ +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.maven.core.util.KindAndName; +import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; +import io.fabric8.maven.docker.config.ImageConfiguration; +import io.fabric8.maven.enricher.api.Dependency; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; @@ -28,22 +36,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.api.model.KubernetesList; -import io.fabric8.kubernetes.api.model.KubernetesListBuilder; -import io.fabric8.maven.core.util.KindAndName; -import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; -import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.project.MavenProject; import org.junit.Test; import org.junit.runner.RunWith; @@ -55,7 +50,7 @@ public class DependencyEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked private ImageConfiguration imageConfiguration; @@ -107,21 +102,18 @@ private KubernetesListBuilder createResourcesForTest() throws IOException, URISy private void setupExpectations() { // Setup Mock behaviour new Expectations() {{ - context.getProject(); - result = project; - context.getProject().getArtifacts(); + context.getDependencies(true); result = getDummyArtifacts(); }}; } - private Set getDummyArtifacts() { - Set artifacts = new TreeSet<>(); + private List getDummyArtifacts() { + List artifacts = new ArrayList<>(); + - Artifact artifact = new DefaultArtifact("io.fabric8.tenant.apps", "jenkins", - "1.0.0-SNAPSHOT", "compile", "jar", null, new DefaultArtifactHandler("jar")); File aFile = new File(getClass().getResource(artifactFilePath).getFile()); - artifact.setFile(aFile); + Dependency artifact = new Dependency("jar", "compile", aFile); artifacts.add(artifact); return artifacts; } diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricherTest.java index f0da71ddb8..429aee79b5 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/DockerRegistrySecretEnricherTest.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.enricher.standard; +import io.fabric8.maven.enricher.api.DockerRegistryAuthentication; import java.util.HashMap; import java.util.Map; @@ -24,7 +25,7 @@ import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.SecretBuilder; import io.fabric8.maven.core.util.SecretConstants; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -42,7 +43,7 @@ public class DockerRegistrySecretEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; private String dockerUrl = "docker.io"; private String annotation = "maven.fabric8.io/dockerServerId"; @@ -52,8 +53,8 @@ public void testDockerRegistry() { new Expectations() { { { - context.getSettings(); - result = createSettings(); + context.getDockerRegistryAuth(dockerUrl); + result = createDockerRegistry(); } } }; @@ -77,8 +78,8 @@ public void testDockerRegistryWithBadKind() { new Expectations() { { { - context.getSettings(); - result = createSettings(); + context.getDockerRegistryAuth(dockerUrl); + result = createDockerRegistry(); } } }; @@ -101,8 +102,8 @@ public void testDockerRegistryWithBadAnnotation() { new Expectations() { { { - context.getSettings(); - returns(new Settings()); + context.getDockerRegistryAuth(dockerUrl); + result = createDockerRegistry(); } } }; @@ -144,9 +145,7 @@ private Server createBaseServer() { return server; } - public Settings createSettings() { - Settings settings = new Settings(); - settings.addServer(createBaseServer()); - return settings; + public DockerRegistryAuthentication createDockerRegistry() { + return new DockerRegistryAuthentication("username", "password", null); } } diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/ImageEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/ImageEnricherTest.java index b226c3f901..9aa5047f7a 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/ImageEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/ImageEnricherTest.java @@ -25,7 +25,7 @@ import io.fabric8.maven.core.config.ResourceConfig; import io.fabric8.maven.core.util.ResourceUtil; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -45,7 +45,7 @@ public class ImageEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked ImageConfiguration imageConfiguration; diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricherTest.java index 1614f095ba..060bae84a6 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenIssueManagementEnricherTest.java @@ -18,7 +18,7 @@ import java.util.Map; import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import mockit.Expectations; import mockit.Mocked; @@ -40,7 +40,7 @@ public class MavenIssueManagementEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testMavenIssueManagementAll() { diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenProjectEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenProjectEnricherTest.java index ca1858c4a5..06410969ca 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenProjectEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenProjectEnricherTest.java @@ -15,12 +15,13 @@ */ package io.fabric8.maven.enricher.standard; +import io.fabric8.maven.core.model.Artifact; import java.util.Map; import java.util.Properties; import io.fabric8.kubernetes.api.model.KubernetesList; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import mockit.Expectations; import mockit.Mocked; @@ -43,7 +44,7 @@ public class MavenProjectEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked private MavenProject mavenProject; @@ -51,15 +52,8 @@ public class MavenProjectEnricherTest { @Before public void setupExpectations() { new Expectations() {{ - context.getProject(); - result = mavenProject; - - mavenProject.getGroupId(); - result = "groupId"; - mavenProject.getArtifactId(); - result = "artifactId"; - mavenProject.getVersion(); - result = "version"; + context.getArtifact(); + result = new Artifact( "groupId", "artifactId", "version"); }}; } @@ -92,7 +86,7 @@ public void testOldStyleGeneratedResources() { final Properties properties = new Properties(); properties.setProperty("fabric8.enricher.fmp-project.useProjectLabel", "true"); new Expectations() {{ - mavenProject.getProperties(); + context.getProperties(); result = properties; }}; diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenScmEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenScmEnricherTest.java index 051c86074f..b41391e703 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenScmEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/MavenScmEnricherTest.java @@ -18,7 +18,7 @@ import java.util.Map; import io.fabric8.maven.core.util.kubernetes.Fabric8Annotations; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.Kind; import mockit.Expectations; import mockit.Mocked; @@ -40,7 +40,7 @@ public class MavenScmEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testMavenScmAll() { diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricherTest.java index 6aaf9b3a8c..e05231671b 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/RevisionHistoryEnricherTest.java @@ -25,8 +25,7 @@ import io.fabric8.maven.core.config.ProcessorConfig; import io.fabric8.maven.core.util.Configs; import io.fabric8.maven.core.util.ResourceUtil; -import io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -41,7 +40,7 @@ public class RevisionHistoryEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testDefaultRevisionHistoryLimit() throws JsonProcessingException { diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricherTest.java index 5f315d6f49..36799d91ed 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/TriggersAnnotationEnricherTest.java @@ -15,11 +15,6 @@ */ package io.fabric8.maven.enricher.standard; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerBuilder; @@ -28,8 +23,12 @@ import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.api.model.batch.Job; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.openshift.api.model.ImageChangeTrigger; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -50,7 +49,7 @@ public class TriggersAnnotationEnricherTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void testStatefulSetEnrichment() throws IOException { @@ -166,7 +165,7 @@ public void testConditionalStatefulSetEnrichment() throws IOException { final Properties props = new Properties(); props.put("fabric8.enricher.fmp-triggers-annotation.containers", "c2, c3, anotherc"); new Expectations() {{ - context.getProject().getProperties(); + context.getProperties(); result = props; }}; diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricherTest.java index fc65c21786..4bf165e3f3 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/VolumePermissionEnricherTest.java @@ -26,7 +26,7 @@ import io.fabric8.kubernetes.api.model.PodTemplateBuilder; import io.fabric8.kubernetes.api.model.VolumeMountBuilder; import io.fabric8.maven.core.config.ProcessorConfig; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -43,7 +43,7 @@ public class VolumePermissionEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; // ******************************* // Tests diff --git a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricherTest.java b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricherTest.java index 06bbbcde27..f6ced4e651 100644 --- a/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricherTest.java +++ b/enricher/standard/src/test/java/io/fabric8/maven/enricher/standard/openshift/AutoTLSEnricherTest.java @@ -15,20 +15,19 @@ */ package io.fabric8.maven.enricher.standard.openshift; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.PodTemplate; import io.fabric8.maven.core.config.PlatformMode; import io.fabric8.maven.core.config.ProcessorConfig; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.core.model.Artifact; import io.fabric8.maven.enricher.api.Kind; -import io.fabric8.maven.enricher.standard.openshift.AutoTLSEnricher; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; @@ -45,7 +44,7 @@ public class AutoTLSEnricherTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Mocked MavenProject project; @@ -83,15 +82,15 @@ public void testSecretName() throws Exception { // Setup mock behaviour new Expectations() { { - project.getProperties(); + context.getProperties(); result = projectProps; project.getArtifactId(); result = "projectA"; minTimes = 0; - context.getProject(); - result = project; context.getConfig(); result = config; + context.getArtifact(); + result = new Artifact("", "projectA", "0"); } }; @@ -164,13 +163,11 @@ public void testAdapt() throws Exception { // Setup mock behaviour new Expectations() { { - project.getProperties(); + context.getProperties(); result = projectProps; project.getArtifactId(); result = "projectA"; minTimes = 0; - context.getProject(); - result = project; context.getConfig(); result = config; } diff --git a/generator/spring-boot/src/main/java/io/fabric8/maven/generator/springboot/SpringBootGenerator.java b/generator/spring-boot/src/main/java/io/fabric8/maven/generator/springboot/SpringBootGenerator.java index 36e2772358..cf89879b91 100644 --- a/generator/spring-boot/src/main/java/io/fabric8/maven/generator/springboot/SpringBootGenerator.java +++ b/generator/spring-boot/src/main/java/io/fabric8/maven/generator/springboot/SpringBootGenerator.java @@ -90,7 +90,7 @@ protected Map getEnv(boolean prePackagePhase) throws MojoExecuti Map res = super.getEnv(prePackagePhase); if (getContext().isWatchMode()) { // adding dev tools token to env variables to prevent override during recompile - String secret = SpringBootUtil.getSpringBootApplicationProperties(getProject()).getProperty(SpringBootConfigurationHelper.DEV_TOOLS_REMOTE_SECRET); + String secret = SpringBootUtil.getSpringBootApplicationProperties(MavenUtil.getCompileClassLoader(getProject())).getProperty(SpringBootConfigurationHelper.DEV_TOOLS_REMOTE_SECRET); if (secret != null) { res.put(SpringBootConfigurationHelper.DEV_TOOLS_REMOTE_SECRET_ENV, secret); } @@ -118,7 +118,7 @@ protected boolean isFatJar() throws MojoExecutionException { @Override protected List extractPorts() { List answer = new ArrayList<>(); - Properties properties = SpringBootUtil.getSpringBootApplicationProperties(this.getProject()); + Properties properties = SpringBootUtil.getSpringBootApplicationProperties(MavenUtil.getCompileClassLoader(this.getProject())); SpringBootConfigurationHelper propertyHelper = new SpringBootConfigurationHelper(SpringBootUtil.getSpringBootVersion(getProject())); String port = properties.getProperty(propertyHelper.getServerPortPropertyKey(), DEFAULT_SERVER_PORT); addPortIfValid(answer, getConfig(JavaExecGenerator.Config.webPort, port)); @@ -130,7 +130,7 @@ protected List extractPorts() { // ============================================================================= private void ensureSpringDevToolSecretToken() throws MojoExecutionException { - Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getProject()); + Properties properties = SpringBootUtil.getSpringBootApplicationProperties(MavenUtil.getCompileClassLoader(getProject())); String remoteSecret = properties.getProperty(DEV_TOOLS_REMOTE_SECRET); if (Strings.isNullOrEmpty(remoteSecret)) { addSecretTokenToApplicationProperties(); diff --git a/plugin/src/main/java/io/fabric8/maven/plugin/enricher/EnricherManager.java b/plugin/src/main/java/io/fabric8/maven/plugin/enricher/EnricherManager.java index 4b8af38325..d02a348263 100644 --- a/plugin/src/main/java/io/fabric8/maven/plugin/enricher/EnricherManager.java +++ b/plugin/src/main/java/io/fabric8/maven/plugin/enricher/EnricherManager.java @@ -15,10 +15,6 @@ */ package io.fabric8.maven.plugin.enricher; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.google.common.base.Function; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.maven.core.config.MetaDataConfig; @@ -30,6 +26,9 @@ import io.fabric8.maven.enricher.api.Enricher; import io.fabric8.maven.enricher.api.EnricherContext; import io.fabric8.maven.enricher.api.Kind; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static io.fabric8.maven.plugin.enricher.EnricherManager.Extractor.ANNOTATION_EXTRACTOR; import static io.fabric8.maven.plugin.enricher.EnricherManager.Extractor.LABEL_EXTRACTOR; @@ -62,7 +61,7 @@ public EnricherManager(ResourceConfig resourceConfig, EnricherContext enricherCo PluginServiceFactory pluginFactory = new PluginServiceFactory<>(enricherContext); if (enricherContext.isUseProjectClasspath()) { - pluginFactory.addAdditionalClassLoader(ClassUtil.createProjectClassLoader(enricherContext.getProject(), enricherContext.getLog())); + pluginFactory.addAdditionalClassLoader(ClassUtil.createProjectClassLoader(enricherContext.getCompileClasspathElements(), enricherContext.getLog())); } this.log = enricherContext.getLog(); diff --git a/plugin/src/main/java/io/fabric8/maven/plugin/generator/GeneratorManager.java b/plugin/src/main/java/io/fabric8/maven/plugin/generator/GeneratorManager.java index 6f417f3601..6441991cab 100644 --- a/plugin/src/main/java/io/fabric8/maven/plugin/generator/GeneratorManager.java +++ b/plugin/src/main/java/io/fabric8/maven/plugin/generator/GeneratorManager.java @@ -24,6 +24,7 @@ import io.fabric8.maven.docker.util.Logger; import io.fabric8.maven.generator.api.Generator; import io.fabric8.maven.generator.api.GeneratorContext; +import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.plugin.MojoExecutionException; /** @@ -40,9 +41,13 @@ public static List generate(List imageCo List ret = imageConfigs; PluginServiceFactory pluginFactory = - genCtx.isUseProjectClasspath() ? - new PluginServiceFactory(genCtx, ClassUtil.createProjectClassLoader(genCtx.getProject(), genCtx.getLogger())) : + null; + try { + pluginFactory = genCtx.isUseProjectClasspath() ? + new PluginServiceFactory(genCtx, ClassUtil.createProjectClassLoader(genCtx.getProject().getCompileClasspathElements(), genCtx.getLogger())) : new PluginServiceFactory(genCtx); + } catch (DependencyResolutionRequiredException e) { + } List generators = pluginFactory.createServiceObjects("META-INF/fabric8/generator-default", diff --git a/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/BuildMojo.java b/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/BuildMojo.java index 3ecd200498..9c3c586e1a 100644 --- a/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/BuildMojo.java +++ b/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/BuildMojo.java @@ -15,6 +15,7 @@ */ package io.fabric8.maven.plugin.mojo.build; +import io.fabric8.maven.enricher.api.EnricherContext; import java.io.File; import java.io.IOException; import java.util.List; @@ -40,7 +41,7 @@ import io.fabric8.maven.docker.service.ServiceHub; import io.fabric8.maven.docker.util.EnvUtil; import io.fabric8.maven.docker.util.Task; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.generator.api.GeneratorContext; import io.fabric8.maven.plugin.enricher.EnricherManager; import io.fabric8.maven.plugin.generator.GeneratorManager; @@ -377,7 +378,7 @@ private ProcessorConfig extractGeneratorConfig() { // Get enricher context public EnricherContext getEnricherContext() { - return new EnricherContext.Builder() + return new MavenEnricherContext.Builder() .project(project) .session(session) .goalFinder(goalFinder) diff --git a/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/ResourceMojo.java b/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/ResourceMojo.java index 9bb090d5a3..20aa406df3 100644 --- a/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/ResourceMojo.java +++ b/plugin/src/main/java/io/fabric8/maven/plugin/mojo/build/ResourceMojo.java @@ -16,6 +16,7 @@ package io.fabric8.maven.plugin.mojo.build; import io.fabric8.maven.core.config.MappingConfig; +import io.fabric8.maven.core.model.Artifact; import java.io.File; import java.io.FileFilter; import java.io.IOException; @@ -72,7 +73,7 @@ import io.fabric8.maven.docker.util.EnvUtil; import io.fabric8.maven.docker.util.ImageNameFormatter; import io.fabric8.maven.docker.util.Logger; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; import io.fabric8.maven.enricher.api.util.InitContainerHandler; import io.fabric8.maven.enricher.standard.VolumePermissionEnricher; import io.fabric8.maven.generator.api.GeneratorContext; @@ -96,8 +97,12 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProjectHelper; +import org.apache.maven.settings.Server; +import org.apache.maven.settings.Settings; import org.apache.maven.shared.filtering.MavenFileFilter; import org.apache.maven.shared.filtering.MavenFilteringException; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.json.JSONObject; import static io.fabric8.maven.core.util.Constants.RESOURCE_APP_CATALOG_ANNOTATION; import static io.fabric8.maven.core.util.ResourceFileType.json; @@ -400,16 +405,12 @@ public void executeInternal() throws MojoExecutionException, MojoFailureExceptio clusterAccess = new ClusterAccess(namespace); updateKindFilenameMappings(); try { - lateInit(); - // Resolve the Docker image build configuration resolvedImages = getResolvedImages(images, log); - if (!skip && (!isPomProject() || hasFabric8Dir())) { // Extract and generate resources which can be a mix of Kubernetes and OpenShift resources KubernetesList resources = generateResources(resolvedImages); - // Adapt list to use OpenShift specific resource objects KubernetesList openShiftResources = convertToOpenShiftResources(resources); writeResources(openShiftResources, ResourceClassifier.OPENSHIFT, generateRoute); @@ -491,7 +492,8 @@ private void lateInit() throws MojoExecutionException { openShiftConverters.put("DeploymentConfig", new DeploymentConfigOpenShiftConverter(getOpenshiftDeployTimeoutSeconds())); openShiftConverters.put("Namespace", new NamespaceOpenShiftConverter()); - handlerHub = new HandlerHub(project); + handlerHub = new HandlerHub(MavenUtil.getCompileClassLoader(project), project.getBuild().getOutputDirectory(), + new Artifact(project.getGroupId(), project.getArtifactId(), project.getVersion()), project.getProperties()); } private boolean isOpenShiftMode() { @@ -598,7 +600,8 @@ private KubernetesList generateResources(List images) loadOpenShiftOverrideResources(); - EnricherContext.Builder ctxBuilder = new EnricherContext.Builder() + + MavenEnricherContext.Builder ctxBuilder = new MavenEnricherContext.Builder() .project(project) .session(session) .goalFinder(goalFinder) @@ -611,6 +614,8 @@ private KubernetesList generateResources(List images) if (resources != null) { ctxBuilder.namespace(resources.getNamespace()); } + + EnricherManager enricherManager = new EnricherManager(resources, ctxBuilder.build()); // Generate all resources from the main resource directory, configuration and enrich them accordingly @@ -628,7 +633,7 @@ private void loadOpenShiftOverrideResources() throws MojoExecutionException, IOE if (resourceDirOpenShiftOverride.isDirectory() && resourceDirOpenShiftOverride.exists()) { File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(resourceDirOpenShiftOverride); if (resourceFiles.length > 0) { - String defaultName = MavenUtil.createDefaultResourceName(project); + String defaultName = MavenUtil.createDefaultResourceName(project.getGroupId(), project.getArtifactId()); KubernetesListBuilder builder = KubernetesResourceUtil.readResourceFragmentsFrom( KubernetesResourceUtil.DEFAULT_RESOURCE_VERSIONING, defaultName, @@ -754,7 +759,7 @@ private Path getFirstComposeFile(File[] composeFile) { private KubernetesListBuilder readResourceFragments(File[] resourceFiles) throws IOException, MojoExecutionException { KubernetesListBuilder builder; - String defaultName = MavenUtil.createDefaultResourceName(project); + String defaultName = MavenUtil.createDefaultResourceName(project.getArtifactId()); builder = KubernetesResourceUtil.readResourceFragmentsFrom( KubernetesResourceUtil.DEFAULT_RESOURCE_VERSIONING, defaultName, @@ -1017,7 +1022,7 @@ private void addSecrets(KubernetesListBuilder builder) { // docker-registry if (secretConfig.getDockerServerId() != null) { - String dockerSecret = DockerServerUtil.getDockerJsonConfigString(settings, secretConfig.getDockerServerId()); + String dockerSecret = getDockerJsonConfigString(settings, secretConfig.getDockerServerId()); if (StringUtils.isBlank(dockerSecret)) { log.warn("Docker secret with id " + secretConfig.getDockerServerId() + " cannot be found in maven settings"); continue; @@ -1037,6 +1042,50 @@ private void addSecrets(KubernetesListBuilder builder) { } } + //Method used in MOJO + public String getDockerJsonConfigString(final Settings settings, final String serverId) { + Server server = getServer(settings, serverId); + if (server == null) { + return ""; + } + + Map auth = new HashMap<>(); + auth.put("username", server.getUsername()); + auth.put("password", server.getPassword()); + + String mail = getConfigurationValue(server, "email"); + if (StringUtils.isBlank(mail)) { + mail = "foo@foo.com"; + } + auth.put("email", mail); + + JSONObject json = new JSONObject() + .put(serverId, auth); + return json.toString(); + } + + public Server getServer(final Settings settings, final String serverId) { + if (settings == null || StringUtils.isBlank(serverId)) { + return null; + } + return settings.getServer(serverId); + } + + private String getConfigurationValue(final Server server, final String key) { + + final Xpp3Dom configuration = (Xpp3Dom) server.getConfiguration(); + if (configuration == null) { + return null; + } + + final Xpp3Dom node = configuration.getChild(key); + if (node == null) { + return null; + } + + return node.getValue(); + } + private void addController(KubernetesListBuilder builder, List images) { // TODO: Change to ReplicaSet ReplicationControllerHandler rcHandler = handlerHub.getReplicationControllerHandler(); diff --git a/plugin/src/main/java/io/fabric8/maven/plugin/watcher/WatcherManager.java b/plugin/src/main/java/io/fabric8/maven/plugin/watcher/WatcherManager.java index 8e7c881c92..6410d1c4ae 100644 --- a/plugin/src/main/java/io/fabric8/maven/plugin/watcher/WatcherManager.java +++ b/plugin/src/main/java/io/fabric8/maven/plugin/watcher/WatcherManager.java @@ -41,7 +41,7 @@ public static void watch(List ret, Set resource PluginServiceFactory pluginFactory = watcherCtx.isUseProjectClasspath() ? - new PluginServiceFactory<>(watcherCtx, ClassUtil.createProjectClassLoader(watcherCtx.getProject(), watcherCtx.getLogger())) : + new PluginServiceFactory<>(watcherCtx, ClassUtil.createProjectClassLoader(watcherCtx.getProject().getCompileClasspathElements(), watcherCtx.getLogger())) : new PluginServiceFactory<>(watcherCtx); boolean isOpenshift = OpenshiftHelper.isOpenShift(watcherCtx.getKubernetesClient()); diff --git a/plugin/src/test/java/io/fabric8/maven/plugin/enricher/EnricherManagerTest.java b/plugin/src/test/java/io/fabric8/maven/plugin/enricher/EnricherManagerTest.java index 3da7390df4..103c76764f 100644 --- a/plugin/src/test/java/io/fabric8/maven/plugin/enricher/EnricherManagerTest.java +++ b/plugin/src/test/java/io/fabric8/maven/plugin/enricher/EnricherManagerTest.java @@ -15,20 +15,28 @@ */ package io.fabric8.maven.plugin.enricher; -import java.util.*; - -import io.fabric8.kubernetes.api.model.*; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.maven.core.config.ProcessorConfig; import io.fabric8.maven.docker.config.ImageConfiguration; -import io.fabric8.maven.enricher.api.EnricherContext; +import io.fabric8.maven.enricher.api.MavenEnricherContext; +import io.fabric8.maven.enricher.api.util.ProjectClassLoader; +import java.net.URLClassLoader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; import mockit.Expectations; import mockit.Mocked; import mockit.integration.junit4.JMockit; import org.junit.Test; import org.junit.runner.RunWith; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; /** * @author roland @@ -38,13 +46,16 @@ public class EnricherManagerTest { @Mocked - private EnricherContext context; + private MavenEnricherContext context; @Test public void createDefaultResources() { new Expectations() {{ context.getConfig(); result = new ProcessorConfig(Arrays.asList("fmp-controller"), null, null); context.getImages(); result = new ImageConfiguration.Builder().alias("img1").name("img1").build(); + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) EnricherManagerTest.class.getClassLoader(), (URLClassLoader) EnricherManagerTest.class.getClassLoader()); }}; EnricherManager manager = new EnricherManager(null, context); @@ -57,6 +68,9 @@ public void createDefaultResources() { public void enrichEmpty() { new Expectations() {{ context.getConfig(); result = ProcessorConfig.EMPTY; + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) EnricherManagerTest.class.getClassLoader(), (URLClassLoader) EnricherManagerTest.class.getClassLoader()); }}; EnricherManager manager = new EnricherManager(null, context); @@ -69,6 +83,9 @@ public void enrichEmpty() { public void enrichSimple() { new Expectations() {{ context.getConfig(); result = new ProcessorConfig(Arrays.asList("fmp-project"),null,new HashMap()); + context.getProjectClassLoader(); + result = new ProjectClassLoader( + (URLClassLoader) EnricherManagerTest.class.getClassLoader(), (URLClassLoader) EnricherManagerTest.class.getClassLoader()); }}; EnricherManager manager = new EnricherManager(null, context); @@ -95,4 +112,5 @@ public void enrichSimple() { assertNotNull(labels); assertEquals("fabric8", labels.get("provider")); } + } diff --git a/watcher/standard/src/main/java/io/fabric8/maven/watcher/standard/SpringBootWatcher.java b/watcher/standard/src/main/java/io/fabric8/maven/watcher/standard/SpringBootWatcher.java index a8e9ceaae6..ec8428263e 100644 --- a/watcher/standard/src/main/java/io/fabric8/maven/watcher/standard/SpringBootWatcher.java +++ b/watcher/standard/src/main/java/io/fabric8/maven/watcher/standard/SpringBootWatcher.java @@ -53,6 +53,7 @@ import io.fabric8.maven.watcher.api.BaseWatcher; import io.fabric8.maven.watcher.api.WatcherContext; import org.apache.commons.lang3.StringUtils; +import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.project.MavenProject; import static io.fabric8.maven.core.util.SpringBootConfigurationHelper.DEV_TOOLS_REMOTE_SECRET; @@ -112,7 +113,7 @@ private String getPortForwardUrl(final Set resources) throws Except return null; } - Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject()); + Properties properties = SpringBootUtil.getSpringBootApplicationProperties(MavenUtil.getCompileClassLoader(getContext().getProject())); SpringBootConfigurationHelper propertyHelper = new SpringBootConfigurationHelper(SpringBootUtil.getSpringBootVersion(getContext().getProject())); int port = IoUtil.getFreeRandomPort(); @@ -173,7 +174,7 @@ private boolean isExposeService(Service service) { private void runRemoteSpringApplication(String url) { log.info("Running RemoteSpringApplication against endpoint: " + url); - Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject()); + Properties properties = SpringBootUtil.getSpringBootApplicationProperties(MavenUtil.getCompileClassLoader(getContext().getProject())); String remoteSecret = properties.getProperty(DEV_TOOLS_REMOTE_SECRET, System.getProperty(DEV_TOOLS_REMOTE_SECRET)); if (StringUtils.isBlank(remoteSecret)) { log.warn("There is no `%s` property defined in your src/main/resources/application.properties. Please add one!", DEV_TOOLS_REMOTE_SECRET); @@ -183,67 +184,75 @@ private void runRemoteSpringApplication(String url) { ClassLoader classLoader = getClass().getClassLoader(); if (classLoader instanceof URLClassLoader) { URLClassLoader pluginClassLoader = (URLClassLoader) classLoader; - URLClassLoader projectClassLoader = ClassUtil.createProjectClassLoader(getContext().getProject(), log); - URLClassLoader[] classLoaders = {projectClassLoader, pluginClassLoader}; - - StringBuilder buffer = new StringBuilder("java -cp "); - int count = 0; - for (URLClassLoader urlClassLoader : classLoaders) { - URL[] urLs = urlClassLoader.getURLs(); - for (URL u : urLs) { - if (count++ > 0) { - buffer.append(File.pathSeparator); - } - try { - URI uri = u.toURI(); - File file = new File(uri); - buffer.append(file.getCanonicalPath()); - } catch (Exception e) { - throw new IllegalStateException("Failed to create classpath: " + e, e); + try( + URLClassLoader projectClassLoader = + ClassUtil.createProjectClassLoader(getContext().getProject().getCompileClasspathElements(), log)) { + + URLClassLoader[] classLoaders = {projectClassLoader, pluginClassLoader}; + + StringBuilder buffer = new StringBuilder("java -cp "); + int count = 0; + for (URLClassLoader urlClassLoader : classLoaders) { + URL[] urLs = urlClassLoader.getURLs(); + for (URL u : urLs) { + if (count++ > 0) { + buffer.append(File.pathSeparator); + } + try { + URI uri = u.toURI(); + File file = new File(uri); + buffer.append(file.getCanonicalPath()); + } catch (Exception e) { + throw new IllegalStateException("Failed to create classpath: " + e, e); + } } } - } - // Add dev tools to the classpath (the main class is not read from BOOT-INF/lib) - try { - File devtools = getSpringBootDevToolsJar(getContext().getProject()); - buffer.append(File.pathSeparator); - buffer.append(devtools.getCanonicalPath()); - } catch (Exception e) { - throw new IllegalStateException("Failed to include devtools in the classpath: " + e, e); - } - buffer.append(" -Dspring.devtools.remote.secret="); - buffer.append(remoteSecret); - buffer.append(" org.springframework.boot.devtools.RemoteSpringApplication "); - buffer.append(url); - - try { - String command = buffer.toString(); - log.debug("Running: " + command); - final Process process = Runtime.getRuntime().exec(command); - - final AtomicBoolean outputEnabled = new AtomicBoolean(true); - Runtime.getRuntime().addShutdownHook(new Thread("fabric8:watch [spring-boot] shutdown hook") { - @Override - public void run() { - log.info("Terminating the Spring remote client..."); - outputEnabled.set(false); - process.destroy(); + // Add dev tools to the classpath (the main class is not read from BOOT-INF/lib) + try { + File devtools = getSpringBootDevToolsJar(getContext().getProject()); + buffer.append(File.pathSeparator); + buffer.append(devtools.getCanonicalPath()); + } catch (Exception e) { + throw new IllegalStateException("Failed to include devtools in the classpath: " + e, e); + } + + buffer.append(" -Dspring.devtools.remote.secret="); + buffer.append(remoteSecret); + buffer.append(" org.springframework.boot.devtools.RemoteSpringApplication "); + buffer.append(url); + + try { + String command = buffer.toString(); + log.debug("Running: " + command); + final Process process = Runtime.getRuntime().exec(command); + + final AtomicBoolean outputEnabled = new AtomicBoolean(true); + Runtime.getRuntime().addShutdownHook(new Thread("fabric8:watch [spring-boot] shutdown hook") { + @Override + public void run() { + log.info("Terminating the Spring remote client..."); + outputEnabled.set(false); + process.destroy(); + } + }); + Logger logger = new PrefixedLogger("Spring-Remote", log); + Thread stdOutPrinter = startOutputProcessor(logger, process.getInputStream(), false, outputEnabled); + Thread stdErrPrinter = startOutputProcessor(logger, process.getErrorStream(), true, outputEnabled); + int status = process.waitFor(); + stdOutPrinter.join(); + stdErrPrinter.join(); + if (status != 0) { + log.warn("Process returned status: %s", status); } - }); - Logger logger = new PrefixedLogger("Spring-Remote", log); - Thread stdOutPrinter = startOutputProcessor(logger, process.getInputStream(), false, outputEnabled); - Thread stdErrPrinter = startOutputProcessor(logger, process.getErrorStream(), true, outputEnabled); - int status = process.waitFor(); - stdOutPrinter.join(); - stdErrPrinter.join(); - if (status != 0) { - log.warn("Process returned status: %s", status); + } catch (Exception e) { + throw new RuntimeException("Failed to run RemoteSpringApplication: " + e, e); } - } catch (Exception e) { - throw new RuntimeException("Failed to run RemoteSpringApplication: " + e, e); + } catch (DependencyResolutionRequiredException e) { + log.warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e); + } catch (IOException e) { + log.warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e); } - } else { throw new IllegalStateException("ClassLoader must be a URLClassLoader but it is: " + classLoader.getClass().getName()); }