diff --git a/.gitignore b/.gitignore index 118ca45..3afdcc9 100644 --- a/.gitignore +++ b/.gitignore @@ -15,9 +15,11 @@ capybara-*.html /coverage/ .idea/ .env -versioneye-maven-plugin.iml -versioneye-maven-plugin.ipr -versioneye-maven-plugin.iws +*.iml +*.ipr +*.iws +*.log .classpath .project .settings +atlassian-ide-plugin.xml diff --git a/pom.xml b/pom.xml index e2ed719..05a4185 100644 --- a/pom.xml +++ b/pom.xml @@ -2,11 +2,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - - 3.1 - - com.versioneye versioneye-maven-plugin 3.11.4 @@ -50,14 +45,194 @@ + + ${maven.version} + + + 2.0.18 + 4.5.3 + 1.9.13 + 1.8 + ${java.version} + ${java.version} 3.5.0 - 1.9.13 - 4.5.3 + 2.8.1 + 3.0.24 + UTF-8 + UTF-8 + 1.7.25 + 2.20 + + + enforcer + + + + org.apache.maven.plugins + maven-enforcer-plugin + 1.4.1 + + + enforce-dependency-convergence + validate + + enforce + + + + + + + + true + + + commons-logging + log4j + log4j:log4j + slf4j-to-log4j + + jdom:jdom + + org.apache.commons:commons-io + + + + + + + + + + errorprone-compiler + + + + + maven-compiler-plugin + 3.6.1 + + javac-with-errorprone + true + + + + com.google.errorprone + error_prone_annotations + ${errorprone.compiler.version} + + + com.google.errorprone + error_prone_core + ${errorprone.compiler.version} + + + + org.codehaus.plexus + plexus-compiler-javac-errorprone + ${plexus.compiler.version} + + + org.codehaus.plexus + plexus-compiler-api + ${plexus.compiler.version} + + + org.codehaus.plexus + plexus-compiler-manager + ${plexus.compiler.version} + + + org.codehaus.plexus + plexus-utils + ${plexus.utils.version} + + + + + + + + + + + gpg + + + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + + org.apache.commons + commons-lang3 + 3.5 + + + org.apache.maven + maven-artifact + ${maven.version} + + + com.google.guava + guava + 21.0 + + + org.codehaus.plexus + plexus-utils + 3.0.24 + + + org.codehaus.plexus + plexus-component-annotations + 1.7.1 + + + + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + org.apache.maven maven-plugin-api @@ -84,10 +259,21 @@ jackson-mapper-lgpl ${jackson.version} + + org.apache.commons + commons-lang3 + 3.5 + org.apache.httpcomponents httpclient ${httpcomponents.version} + + + commons-logging + commons-logging + + org.apache.httpcomponents @@ -100,16 +286,46 @@ 6.11 test + + com.google.guava + guava + 21.0 + test + + + junit + junit + 4.12 + test + + + org.assertj + assertj-core + 3.6.2 + test + + + + + + maven-compiler-plugin + 3.6.1 + + + maven-surefire-plugin + ${surefire.version} + + + - com.versioneye versioneye-maven-plugin @@ -134,9 +350,6 @@ - - - org.sonatype.plugins nexus-staging-maven-plugin @@ -149,25 +362,6 @@ - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - - - sign-artifacts - verify - - sign - - - - - org.apache.maven.plugins maven-plugin-plugin @@ -199,6 +393,7 @@ attach-sources + verify jar-no-fork @@ -209,9 +404,11 @@ org.apache.maven.plugins maven-javadoc-plugin + 2.10.4 attach-javadocs + verify jar @@ -219,13 +416,25 @@ + + maven-dependency-plugin + 3.0.0 + + + maven-help-plugin + 2.2 + + + org.codehaus.mojo + versions-maven-plugin + 2.3 + - org.apache.maven.plugins maven-changelog-plugin 2.3 diff --git a/src/main/java/com/versioneye/CreateMojo.java b/src/main/java/com/versioneye/CreateMojo.java index 1594d39..6222d19 100644 --- a/src/main/java/com/versioneye/CreateMojo.java +++ b/src/main/java/com/versioneye/CreateMojo.java @@ -21,56 +21,56 @@ @Mojo( name = "create", defaultPhase = LifecyclePhase.PROCESS_SOURCES ) public class CreateMojo extends ProjectMojo { - @Parameter( property = "resource", defaultValue = "/projects?api_key=") - private String resource; - - - public void execute() throws MojoExecutionException, MojoFailureException { - try{ - setProxy(); - prettyPrintStart(); - - ByteArrayOutputStream jsonDependenciesStream = null; - if (transitiveDependencies == true){ - jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); - } else { - jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); - } - - if (jsonDependenciesStream == null){ - prettyPrint0End(); - return ; - } - - ProjectJsonResponse response = uploadDependencies(jsonDependenciesStream); - - if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())){ - mavenSession.getTopLevelProject().setContextValue("veye_project_id", response.getId()); - } - - merge( response.getId() ); - if (updatePropertiesAfterCreate) { - writeProperties( response ); - } - prettyPrint(response); - } catch( Exception exception ){ - throw new MojoExecutionException("Oh no! Something went wrong :-( " + - "Get in touch with the VersionEye guys and give them feedback." + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); - } + @Parameter( property = "resource", defaultValue = "/projects?api_key=") + private String resource; + + + public void execute() throws MojoExecutionException, MojoFailureException { + try{ + setProxy(); + prettyPrintStart(); + + ByteArrayOutputStream jsonDependenciesStream = null; + if (transitiveDependencies == true){ + jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); + } else { + jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); + } + + if (jsonDependenciesStream == null){ + prettyPrint0End(); + return ; + } + + ProjectJsonResponse response = uploadDependencies(jsonDependenciesStream); + + if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())){ + mavenSession.getTopLevelProject().setContextValue("veye_project_id", response.getId()); + } + + merge( response.getId() ); + if (updatePropertiesAfterCreate) { + writeProperties( response ); + } + prettyPrint(response); + } catch( Exception exception ){ + throw new MojoExecutionException("Oh no! Something went wrong :-( " + + "Get in touch with the VersionEye guys and give them feedback." + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } + } - private ProjectJsonResponse uploadDependencies(ByteArrayOutputStream outStream) throws Exception { - return createNewProject(resource, outStream); - } + private ProjectJsonResponse uploadDependencies(ByteArrayOutputStream outStream) throws Exception { + return createNewProject(resource, outStream); + } - private void prettyPrintStart(){ - getLog().info("."); - getLog().info("Starting to upload dependencies. This can take a couple seconds ... "); - getLog().info("."); - } + private void prettyPrintStart(){ + getLog().info("."); + getLog().info("Starting to upload dependencies. This can take a couple seconds ... "); + getLog().info("."); + } } diff --git a/src/main/java/com/versioneye/DeleteMojo.java b/src/main/java/com/versioneye/DeleteMojo.java index 5ee28cc..ddf9edc 100644 --- a/src/main/java/com/versioneye/DeleteMojo.java +++ b/src/main/java/com/versioneye/DeleteMojo.java @@ -1,21 +1,23 @@ package com.versioneye; - -import com.versioneye.utils.HttpUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import com.versioneye.utils.HttpUtils; + import java.io.File; +@SuppressWarnings({"WeakerAccess", "unused"}) @Mojo( name = "delete", defaultPhase = LifecyclePhase.PROCESS_SOURCES ) public class DeleteMojo extends ProjectMojo { @Parameter( property = "resource", defaultValue = "/projects") private String resource; + @Override public void execute() throws MojoExecutionException, MojoFailureException { try{ setProxy(); @@ -25,8 +27,8 @@ public void execute() throws MojoExecutionException, MojoFailureException { } catch( Exception exception ){ exception.printStackTrace(); throw new MojoExecutionException("Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } } @@ -38,13 +40,13 @@ protected void deleteProject() throws Exception { HttpUtils.delete(url); } - protected void deletePropertiesFile() throws Exception{ + protected void deletePropertiesFile() throws Exception { String propertiesPath = getPropertiesPath(); File file = new File(propertiesPath); file.delete(); } - protected void prettyPrintStart(){ + protected void prettyPrintStart() { getLog().info("."); getLog().info("Starting to delete this project from the VersionEye server. This can take a couple seconds ... "); getLog().info("."); diff --git a/src/main/java/com/versioneye/JsonMojo.java b/src/main/java/com/versioneye/JsonMojo.java index 49e9484..df7df81 100644 --- a/src/main/java/com/versioneye/JsonMojo.java +++ b/src/main/java/com/versioneye/JsonMojo.java @@ -1,19 +1,22 @@ package com.versioneye; -import com.versioneye.utils.JsonUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; +import com.versioneye.utils.JsonUtils; + import java.util.Map; /** * Writes all direct dependencies into a JSON file. */ +@SuppressWarnings("unused") @Mojo( name = "json", defaultPhase = LifecyclePhase.PROCESS_SOURCES ) public class JsonMojo extends ProjectMojo { + @Override public void execute() throws MojoExecutionException, MojoFailureException { try{ Map jsonMap = getDirectDependenciesJsonMap(nameStrategy); @@ -23,8 +26,8 @@ public void execute() throws MojoExecutionException, MojoFailureException { prettyPrintEnd(filePath); } catch( Exception exception ){ throw new MojoExecutionException( "Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception ); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception ); } } @@ -33,5 +36,4 @@ private void prettyPrintEnd(String pathToJson){ getLog().info("You find your json file here: " + pathToJson); getLog().info(""); } - } diff --git a/src/main/java/com/versioneye/LicenseCheckMojo.java b/src/main/java/com/versioneye/LicenseCheckMojo.java index bc8edc0..443cd6a 100644 --- a/src/main/java/com/versioneye/LicenseCheckMojo.java +++ b/src/main/java/com/versioneye/LicenseCheckMojo.java @@ -1,27 +1,32 @@ package com.versioneye; -import com.versioneye.dto.ProjectJsonResponse; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; +import com.versioneye.dto.ProjectJsonResponse; + import java.io.ByteArrayOutputStream; /** * Updates an existing project at VersionEye with the dependencies from the current project AND * ensures that all used licenses are on a whitelist. If that is not the case it breaks the build. */ +@SuppressWarnings("unused") @Mojo( name = "licenseCheck", defaultPhase = LifecyclePhase.VERIFY ) public class LicenseCheckMojo extends UpdateMojo { + @Override public void execute() throws MojoExecutionException, MojoFailureException { + try{ setProxy(); prettyPrintStart(); - ByteArrayOutputStream jsonDependenciesStream = null; - if (transitiveDependencies == true){ + ByteArrayOutputStream jsonDependenciesStream; + + if (transitiveDependencies){ jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); } else { jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); @@ -36,21 +41,20 @@ public void execute() throws MojoExecutionException, MojoFailureException { System.out.println(response.getLicenses_red()); if (response.getLicenses_red() > 0){ throw new MojoExecutionException("Some components violate the license whitelist! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } - if (response.getLicenses_unknown() > 0 && licenseCheckBreakByUnknown == true ){ + if (response.getLicenses_unknown() > 0 && licenseCheckBreakByUnknown) { throw new MojoExecutionException("Some components are without any license! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } prettyPrint( response ); } catch( Exception exception ){ exception.printStackTrace(); throw new MojoExecutionException("Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } } - } diff --git a/src/main/java/com/versioneye/ListMojo.java b/src/main/java/com/versioneye/ListMojo.java index 0d571ce..516bc66 100644 --- a/src/main/java/com/versioneye/ListMojo.java +++ b/src/main/java/com/versioneye/ListMojo.java @@ -1,31 +1,36 @@ package com.versioneye; -import com.versioneye.utils.DependencyUtils; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator; +import com.versioneye.utils.DependencyUtils; + import java.util.ArrayList; import java.util.List; /** * Lists all direct and recursive dependencies. */ +@SuppressWarnings("unused") @Mojo( name = "list", defaultPhase = LifecyclePhase.PROCESS_SOURCES ) public class ListMojo extends ProjectMojo { - public void execute() throws MojoExecutionException { + @Override + public void execute() throws MojoExecutionException, MojoFailureException { versionEyeOutput(); + try{ PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); DependencyNode root = getDependencyNode(nlg); List dependencies = DependencyUtils.collectAllDependencies(nlg.getDependencies(true)); List directDependencies = DependencyUtils.collectDirectDependencies(root.getChildren()); - List recursiveDependencies = new ArrayList(dependencies); + List recursiveDependencies = new ArrayList<>(dependencies); recursiveDependencies.removeAll(directDependencies); List deps = project.getDependencies(); produceNiceOutput(deps, recursiveDependencies); @@ -36,29 +41,31 @@ public void execute() throws MojoExecutionException { } } - private void produceNiceOutput(List directDependencies, List recursiveDependencies){ + private void produceNiceOutput(List directDependencies, List recursiveDependencies) { productNiceOutputForDirectDependencies(directDependencies); productNiceOutputForRecursiveDependencies(recursiveDependencies); produceNiceOutputSummary(directDependencies.size(), recursiveDependencies.size()); } - private void versionEyeOutput(){ + private void versionEyeOutput() { getLog().info(""); getLog().info("************* \\_/ VersionEye \\_/ *************"); getLog().info(""); } - private void productNiceOutputForDirectDependencies(List directDependencies){ + private void productNiceOutputForDirectDependencies(List directDependencies) { getLog().info(""); getLog().info(directDependencies.size() + " Direct Dependencies: "); getLog().info("--------------------"); + for (Dependency dependency : directDependencies){ getLog().info( dependency.getGroupId() + ":" + dependency.getArtifactId() + ":" + dependency.getVersion()); } + getLog().info(""); } - private void productNiceOutputForRecursiveDependencies(List recursiveDependencies){ + private void productNiceOutputForRecursiveDependencies(List recursiveDependencies) { getLog().info(""); getLog().info(recursiveDependencies.size() + " Transitive Dependencies: "); getLog().info("--------------------"); @@ -72,10 +79,9 @@ private void produceNiceOutputSummary(int directCount, int recursiveCount) { int allCount = directCount + recursiveCount; getLog().info(""); getLog().info(directCount + " Direct dependencies and " + - recursiveCount + " transitive dependencies. This project has " + - allCount + " dependencies."); + recursiveCount + " transitive dependencies. This project has " + + allCount + " dependencies."); getLog().info(""); getLog().info(""); } - } diff --git a/src/main/java/com/versioneye/PingMojo.java b/src/main/java/com/versioneye/PingMojo.java index ee67495..4c9e238 100644 --- a/src/main/java/com/versioneye/PingMojo.java +++ b/src/main/java/com/versioneye/PingMojo.java @@ -5,26 +5,30 @@ import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; -import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import javax.net.ssl.HttpsURLConnection; + /** * Ping the VersionEye API. Expects a pong in response. */ +@SuppressWarnings("unused") @Mojo( name = "ping", defaultPhase = LifecyclePhase.PROCESS_SOURCES ) public class PingMojo extends SuperMojo { - public void execute() throws MojoExecutionException, MojoFailureException { + @Override + public void execute() throws MojoExecutionException, MojoFailureException { try{ setProxy(); initTls(); InputStream inputStream = getInputStream(fetchBaseUrl() + apiPath + "/services/ping"); BufferedReader input = new BufferedReader( new InputStreamReader( inputStream ) ); - String line = ""; + String line; getLog().info(""); while((line = input.readLine())!=null){ getLog().info(line); @@ -33,12 +37,12 @@ public void execute() throws MojoExecutionException, MojoFailureException { input.close(); } catch (Exception ex){ throw new MojoExecutionException( "Oh no! The API or your internet connection seems to be down. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", ex ); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", ex ); } } - private InputStream getInputStream( String urlPath ) throws Exception { + private InputStream getInputStream( String urlPath ) throws IOException { URL url = new URL( urlPath ); if (urlPath.startsWith("https")){ System.out.println("https"); @@ -50,5 +54,4 @@ private InputStream getInputStream( String urlPath ) throws Exception { return urlConnection.getInputStream(); } } - } diff --git a/src/main/java/com/versioneye/ProjectMojo.java b/src/main/java/com/versioneye/ProjectMojo.java index 8e82397..9a26ac9 100644 --- a/src/main/java/com/versioneye/ProjectMojo.java +++ b/src/main/java/com/versioneye/ProjectMojo.java @@ -38,229 +38,229 @@ */ public class ProjectMojo extends SuperMojo { - protected ByteArrayOutputStream getTransitiveDependenciesJsonStream(String nameStrategy) throws Exception { - PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - DependencyNode root = getDependencyNode(nlg); - List transDependencies = nlg.getDependencies(true); - List directDependencies = DependencyUtils.collectDirectDependencies(root.getChildren()); - List dependencies = new ArrayList(); - for (org.eclipse.aether.graph.Dependency dependency : transDependencies) { - getLog().info(" scope: " + dependency.getScope()); - Dependency dep = new Dependency(); - Artifact artifact = dependency.getArtifact(); - dep.setGroupId(artifact.getGroupId()); - dep.setArtifactId(artifact.getArtifactId()); - dep.setVersion(artifact.getVersion()); - dep.setScope(dependency.getScope()); - if (directDependencies.contains(artifact)) { - dep.setScope(dependency.getScope() + "_direct"); - } else { - dep.setScope(dependency.getScope() + "_transitive"); - } - dependencies.add(dep); - } - JsonUtils jsonUtils = new JsonUtils(); - return jsonUtils.dependenciesToJson(project, dependencies, null, nameStrategy); + protected ByteArrayOutputStream getTransitiveDependenciesJsonStream(String nameStrategy) throws Exception { + PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); + DependencyNode root = getDependencyNode(nlg); + List transDependencies = nlg.getDependencies(true); + List directDependencies = DependencyUtils.collectDirectDependencies(root.getChildren()); + List dependencies = new ArrayList(); + for (org.eclipse.aether.graph.Dependency dependency : transDependencies) { + getLog().info(" scope: " + dependency.getScope()); + Dependency dep = new Dependency(); + Artifact artifact = dependency.getArtifact(); + dep.setGroupId(artifact.getGroupId()); + dep.setArtifactId(artifact.getArtifactId()); + dep.setVersion(artifact.getVersion()); + dep.setScope(dependency.getScope()); + if (directDependencies.contains(artifact)) { + dep.setScope(dependency.getScope() + "_direct"); + } else { + dep.setScope(dependency.getScope() + "_transitive"); + } + dependencies.add(dep); } + JsonUtils jsonUtils = new JsonUtils(); + return jsonUtils.dependenciesToJson(project, dependencies, null, nameStrategy); + } - protected ByteArrayOutputStream getDirectDependenciesJsonStream(String nameStrategy) throws Exception { - List plugins = new ArrayList(); - if (trackPlugins){ - plugins = getPluginsFromXml(); - } - - List dependencies = project.getDependencies(); - if (ignoreDependencyManagement == false && - project.getDependencyManagement() != null && - project.getDependencyManagement().getDependencies() != null && - project.getDependencyManagement().getDependencies().size() > 0){ - dependencies.addAll(project.getDependencyManagement().getDependencies()); - } - List filteredDependencies = filterForScopes(dependencies); - JsonUtils jsonUtils = new JsonUtils(); - return jsonUtils.dependenciesToJson(project, filteredDependencies, plugins, nameStrategy); + protected ByteArrayOutputStream getDirectDependenciesJsonStream(String nameStrategy) throws Exception { + List plugins = new ArrayList(); + if (trackPlugins){ + plugins = getPluginsFromXml(); } - protected Map getDirectDependenciesJsonMap(String nameStrategy) throws Exception { - List dependencies = project.getDependencies(); - if (dependencies == null || dependencies.isEmpty()){ - return null; - } else { - iterateThrough(dependencies); - } - JsonUtils jsonUtils = new JsonUtils(); - List> dependencyHashes = jsonUtils.getDependencyHashes(dependencies, project.getPluginManagement().getPlugins()); - return jsonUtils.getJsonPom(project, dependencyHashes, nameStrategy); + List dependencies = project.getDependencies(); + if (ignoreDependencyManagement == false && + project.getDependencyManagement() != null && + project.getDependencyManagement().getDependencies() != null && + project.getDependencyManagement().getDependencies().size() > 0){ + dependencies.addAll(project.getDependencyManagement().getDependencies()); } + List filteredDependencies = filterForScopes(dependencies); + JsonUtils jsonUtils = new JsonUtils(); + return jsonUtils.dependenciesToJson(project, filteredDependencies, plugins, nameStrategy); + } - protected ByteArrayOutputStream getDirectArtifactsJsonStream() throws Exception { - DependencyNode root = getDependencyNode(new PreorderNodeListGenerator()); - List directDependencies = DependencyUtils.collectDirectDependencies(root.getChildren()); - JsonUtils jsonUtils = new JsonUtils(); - return jsonUtils.artifactsToJson(directDependencies); + protected Map getDirectDependenciesJsonMap(String nameStrategy) throws Exception { + List dependencies = project.getDependencies(); + if (dependencies == null || dependencies.isEmpty()){ + return null; + } else { + iterateThrough(dependencies); } + JsonUtils jsonUtils = new JsonUtils(); + List> dependencyHashes = jsonUtils.getDependencyHashes(dependencies, project.getPluginManagement().getPlugins()); + return jsonUtils.getJsonPom(project, dependencyHashes, nameStrategy); + } - protected DependencyNode getDependencyNode(PreorderNodeListGenerator nlg) throws Exception { - CollectRequest collectRequest = DependencyUtils.getCollectRequest(project, repos, JavaScopes.RUNTIME); - DependencyNode root = system.collectDependencies(session, collectRequest).getRoot(); - DependencyRequest dependencyRequest = new DependencyRequest(root, null); - system.resolveDependencies(session, dependencyRequest); - root.accept(nlg); - return root; - } + protected ByteArrayOutputStream getDirectArtifactsJsonStream() throws Exception { + DependencyNode root = getDependencyNode(new PreorderNodeListGenerator()); + List directDependencies = DependencyUtils.collectDirectDependencies(root.getChildren()); + JsonUtils jsonUtils = new JsonUtils(); + return jsonUtils.artifactsToJson(directDependencies); + } - protected void prettyPrint0End() throws Exception { - getLog().info("."); - getLog().info("There are no dependencies in this project! - " + project.getId() ); - getLog().info("."); - } + protected DependencyNode getDependencyNode(PreorderNodeListGenerator nlg) throws Exception { + CollectRequest collectRequest = DependencyUtils.getCollectRequest(project, repos, JavaScopes.RUNTIME); + DependencyNode root = system.collectDependencies(session, collectRequest).getRoot(); + DependencyRequest dependencyRequest = new DependencyRequest(root, null); + system.resolveDependencies(session, dependencyRequest); + root.accept(nlg); + return root; + } - protected void prettyPrint(ProjectJsonResponse response) throws Exception { - getLog().info("."); - getLog().info("Project name: " + response.getName()); - getLog().info("Project id: " + response.getId()); - getLog().info("Dependencies: " + response.getDep_number()); - getLog().info("Outdated: " + response.getOut_number()); - for (ProjectDependency dependency : response.getDependencies() ){ - if (dependency.getOutdated() == false){ - continue; - } - getLog().info(" - " + dependency.getProd_key() + ":" + dependency.getVersion_requested() + " -> " + dependency.getVersion_current()); - } - getLog().info(""); - String projectID = (String) mavenSession.getTopLevelProject().getContextValue("veye_project_id"); - getLog().info("You can find your updated project here: " + fetchBaseUrl() + "/user/projects/" + projectID); - getLog().info(""); - } + protected void prettyPrint0End() throws Exception { + getLog().info("."); + getLog().info("There are no dependencies in this project! - " + project.getId() ); + getLog().info("."); + } - protected ProjectJsonResponse updateExistingProject(String resource, String projectId, ByteArrayOutputStream outStream) throws Exception { - String apiKey = fetchApiKey(); - String url = fetchBaseUrl() + apiPath + resource + "/" + projectId + "?api_key=" + apiKey; - Reader reader = HttpUtils.post(url, outStream.toByteArray(), "project_file", null, null, null, null); - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(reader, ProjectJsonResponse.class ); + protected void prettyPrint(ProjectJsonResponse response) throws Exception { + getLog().info("."); + getLog().info("Project name: " + response.getName()); + getLog().info("Project id: " + response.getId()); + getLog().info("Dependencies: " + response.getDep_number()); + getLog().info("Outdated: " + response.getOut_number()); + for (ProjectDependency dependency : response.getDependencies() ){ + if (dependency.getOutdated() == false){ + continue; + } + getLog().info(" - " + dependency.getProd_key() + ":" + dependency.getVersion_requested() + " -> " + dependency.getVersion_current()); } + getLog().info(""); + String projectID = (String) mavenSession.getTopLevelProject().getContextValue("veye_project_id"); + getLog().info("You can find your updated project here: " + fetchBaseUrl() + "/user/projects/" + projectID); + getLog().info(""); + } + protected ProjectJsonResponse updateExistingProject(String resource, String projectId, ByteArrayOutputStream outStream) throws Exception { + String apiKey = fetchApiKey(); + String url = fetchBaseUrl() + apiPath + resource + "/" + projectId + "?api_key=" + apiKey; + Reader reader = HttpUtils.post(url, outStream.toByteArray(), "project_file", null, null, null, null); + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(reader, ProjectJsonResponse.class ); + } - protected ProjectJsonResponse createNewProject(String resource, ByteArrayOutputStream outStream) throws Exception { - String apiKey = fetchApiKey(); - String url = fetchBaseUrl() + apiPath + resource + apiKey; - Reader reader = HttpUtils.post(url, outStream.toByteArray(), "upload", visibility, name, organisation, team); - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(reader, ProjectJsonResponse.class ); - } - protected void merge(String childId) { - if (mergeAfterCreate == false) { - return ; - } - try { - if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())){ - return ; - } + protected ProjectJsonResponse createNewProject(String resource, ByteArrayOutputStream outStream) throws Exception { + String apiKey = fetchApiKey(); + String url = fetchBaseUrl() + apiPath + resource + apiKey; + Reader reader = HttpUtils.post(url, outStream.toByteArray(), "upload", visibility, name, organisation, team); + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(reader, ProjectJsonResponse.class ); + } - String parentProjectId = (String) mavenSession.getTopLevelProject().getContextValue("veye_project_id"); - getLog().debug("parentProjectId: " + parentProjectId); - String url = fetchBaseUrl() + apiPath + "/projects/" + parentProjectId + "/merge/" + childId + "?api_key=" + fetchApiKey(); + protected void merge(String childId) { + if (mergeAfterCreate == false) { + return ; + } + try { + if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())){ + return ; + } - String response = HttpUtils.get(url); - getLog().debug("merge response: " + response); - } catch (Exception ex) { - getLog().error(ex); - } + String parentProjectId = (String) mavenSession.getTopLevelProject().getContextValue("veye_project_id"); + getLog().debug("parentProjectId: " + parentProjectId); + String url = fetchBaseUrl() + apiPath + "/projects/" + parentProjectId + "/merge/" + childId + "?api_key=" + fetchApiKey(); + + String response = HttpUtils.get(url); + getLog().debug("merge response: " + response); + } catch (Exception ex) { + getLog().error(ex); } + } - protected void writeProperties(ProjectJsonResponse response) throws Exception { - Properties properties = fetchProjectProperties(); - if (response.getId() != null) { - properties.setProperty("project_id", response.getId()); - } - PropertiesUtils utils = new PropertiesUtils(); - utils.writeProperties(properties, getPropertiesPath()); + protected void writeProperties(ProjectJsonResponse response) throws Exception { + Properties properties = fetchProjectProperties(); + if (response.getId() != null) { + properties.setProperty("project_id", response.getId()); } + PropertiesUtils utils = new PropertiesUtils(); + utils.writeProperties(properties, getPropertiesPath()); + } - private void iterateThrough(List dependencies){ - for(Dependency dep: dependencies){ - getLog().info(" - dependency: " + dep.getGroupId() + "/" + dep.getArtifactId() + " " + dep.getVersion()); - } + private void iterateThrough(List dependencies){ + for(Dependency dep: dependencies){ + getLog().info(" - dependency: " + dep.getGroupId() + "/" + dep.getArtifactId() + " " + dep.getVersion()); } + } - private List getPluginsFromXml(){ - List plugins = new ArrayList(); - try { - File pom = project.getModel().getPomFile(); + private List getPluginsFromXml(){ + List plugins = new ArrayList(); + try { + File pom = project.getModel().getPomFile(); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(pom); - XPathFactory xPathfactory = XPathFactory.newInstance(); - XPath xpath = xPathfactory.newXPath(); - XPathExpression expr = xpath.compile("//plugins/plugin"); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document doc = builder.parse(pom); + XPathFactory xPathfactory = XPathFactory.newInstance(); + XPath xpath = xPathfactory.newXPath(); + XPathExpression expr = xpath.compile("//plugins/plugin"); - NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); - for (int i = 0 ; i < nl.getLength() ; i++){ - Node node = nl.item(i); - Plugin plugin = new Plugin(); - fillPlugin(node, plugin); - if (plugin.getGroupId() != null && plugin.getArtifactId() != null){ - plugins.add(plugin); - } - } - } catch (Exception exc){ - getLog().error(exc); + NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); + for (int i = 0 ; i < nl.getLength() ; i++){ + Node node = nl.item(i); + Plugin plugin = new Plugin(); + fillPlugin(node, plugin); + if (plugin.getGroupId() != null && plugin.getArtifactId() != null){ + plugins.add(plugin); } - return plugins; + } + } catch (Exception exc){ + getLog().error(exc); } + return plugins; + } - private void fillPlugin(Node node, Plugin plugin){ - for (int xi = 0 ; xi < node.getChildNodes().getLength() ; xi++ ){ - Node child = node.getChildNodes().item(xi); - if (child == null){ - return ; - } - if (child.getNodeName().equals("groupId")){ - plugin.setGroupId(child.getTextContent().trim()); - } - if (child.getNodeName().equals("artifactId")){ - plugin.setArtifactId(child.getTextContent().trim()); - } - if (child.getNodeName().equals("version")){ - String version = parseVersionString( child.getTextContent().trim() ); - plugin.setVersion(version); - } - } + private void fillPlugin(Node node, Plugin plugin){ + for (int xi = 0 ; xi < node.getChildNodes().getLength() ; xi++ ){ + Node child = node.getChildNodes().item(xi); + if (child == null){ + return ; + } + if (child.getNodeName().equals("groupId")){ + plugin.setGroupId(child.getTextContent().trim()); + } + if (child.getNodeName().equals("artifactId")){ + plugin.setArtifactId(child.getTextContent().trim()); + } + if (child.getNodeName().equals("version")){ + String version = parseVersionString( child.getTextContent().trim() ); + plugin.setVersion(version); + } } + } - private String parseVersionString(String version){ - if (version.startsWith("${")){ - String verValue = version.replaceAll("\\$\\{", "").replaceAll("\\}", ""); - version = (String) project.getProperties().get(verValue); - } - return version; + private String parseVersionString(String version){ + if (version.startsWith("${")){ + String verValue = version.replaceAll("\\$\\{", "").replaceAll("\\}", ""); + version = (String) project.getProperties().get(verValue); } + return version; + } - private List filterForScopes(List dependencies){ - if (skipScopes == null || skipScopes.trim().isEmpty() || dependencies == null || dependencies.isEmpty()) - return dependencies; + private List filterForScopes(List dependencies){ + if (skipScopes == null || skipScopes.trim().isEmpty() || dependencies == null || dependencies.isEmpty()) + return dependencies; - String[] scopes = skipScopes.split(","); - List filtered = new ArrayList(); - for (Dependency dependency : dependencies){ - boolean ignoreScope = false; - for ( String scope : scopes ) { - if (scope != null && - dependency != null && - dependency.getScope() != null && - dependency.getScope().toLowerCase().equals(scope.toLowerCase())) - { - ignoreScope = true; - } - } - if (ignoreScope == false ){ - filtered.add(dependency); - } + String[] scopes = skipScopes.split(","); + List filtered = new ArrayList(); + for (Dependency dependency : dependencies){ + boolean ignoreScope = false; + for ( String scope : scopes ) { + if (scope != null && + dependency != null && + dependency.getScope() != null && + dependency.getScope().toLowerCase().equals(scope.toLowerCase())) + { + ignoreScope = true; } - return filtered; + } + if (ignoreScope == false ){ + filtered.add(dependency); + } } + return filtered; + } } diff --git a/src/main/java/com/versioneye/SecurityAndLicenseCheckMojo.java b/src/main/java/com/versioneye/SecurityAndLicenseCheckMojo.java index 054691e..7d21fa1 100644 --- a/src/main/java/com/versioneye/SecurityAndLicenseCheckMojo.java +++ b/src/main/java/com/versioneye/SecurityAndLicenseCheckMojo.java @@ -1,23 +1,27 @@ package com.versioneye; -import com.versioneye.dto.ProjectJsonResponse; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; +import com.versioneye.dto.ProjectJsonResponse; + import java.io.ByteArrayOutputStream; +@SuppressWarnings("unused") @Mojo( name = "securityAndLicenseCheck", defaultPhase = LifecyclePhase.VERIFY ) public class SecurityAndLicenseCheckMojo extends UpdateMojo { + @Override public void execute() throws MojoExecutionException, MojoFailureException { try{ setProxy(); prettyPrintStart(); - ByteArrayOutputStream jsonDependenciesStream = null; - if (transitiveDependencies == true){ + ByteArrayOutputStream jsonDependenciesStream; + + if (transitiveDependencies){ jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); } else { jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); @@ -32,28 +36,27 @@ public void execute() throws MojoExecutionException, MojoFailureException { System.out.println("sv_count: " + response.getSv_count()); if (response.getSv_count() > 0){ throw new MojoExecutionException("Some components have security vulnerabilities! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } System.out.println("licenses_red: " + response.getLicenses_red()); if (response.getLicenses_red() > 0){ throw new MojoExecutionException("Some components violate the license whitelist! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } - if (response.getLicenses_unknown() > 0 && licenseCheckBreakByUnknown == true ){ + if (response.getLicenses_unknown() > 0 && licenseCheckBreakByUnknown){ throw new MojoExecutionException("Some components are without any license! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } prettyPrint( response ); } catch( Exception exception ){ exception.printStackTrace(); throw new MojoExecutionException("Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } } - } diff --git a/src/main/java/com/versioneye/SecurityCheckMojo.java b/src/main/java/com/versioneye/SecurityCheckMojo.java index 711f1c4..e971297 100644 --- a/src/main/java/com/versioneye/SecurityCheckMojo.java +++ b/src/main/java/com/versioneye/SecurityCheckMojo.java @@ -1,23 +1,26 @@ package com.versioneye; -import com.versioneye.dto.ProjectJsonResponse; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; +import com.versioneye.dto.ProjectJsonResponse; + import java.io.ByteArrayOutputStream; +@SuppressWarnings("unused") @Mojo( name = "securityCheck", defaultPhase = LifecyclePhase.VERIFY ) public class SecurityCheckMojo extends UpdateMojo { + @Override public void execute() throws MojoExecutionException, MojoFailureException { try{ setProxy(); prettyPrintStart(); - ByteArrayOutputStream jsonDependenciesStream = null; - if (transitiveDependencies == true){ + ByteArrayOutputStream jsonDependenciesStream; + if (transitiveDependencies){ jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); } else { jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); @@ -32,15 +35,15 @@ public void execute() throws MojoExecutionException, MojoFailureException { System.out.println("sv_count: " + response.getSv_count()); if (response.getSv_count() > 0){ throw new MojoExecutionException("Some components have security vulnerabilities! " + - "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); + "More details here: " + fetchBaseUrl() + "/user/projects/" + response.getId() ); } prettyPrint( response ); } catch( Exception exception ){ exception.printStackTrace(); throw new MojoExecutionException("Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } } diff --git a/src/main/java/com/versioneye/SuperMojo.java b/src/main/java/com/versioneye/SuperMojo.java index 0fecb31..1d1134d 100644 --- a/src/main/java/com/versioneye/SuperMojo.java +++ b/src/main/java/com/versioneye/SuperMojo.java @@ -28,397 +28,397 @@ */ public class SuperMojo extends AbstractMojo { - protected static final String propertiesFile = "versioneye.properties"; + protected static final String propertiesFile = "versioneye.properties"; - @Component - protected RepositorySystem system; + @Component + protected RepositorySystem system; - @Component - protected MavenSession mavenSession; + @Component + protected MavenSession mavenSession; - @Parameter( defaultValue="${repositorySystemSession}" ) - protected RepositorySystemSession session; + @Parameter( defaultValue="${repositorySystemSession}" ) + protected RepositorySystemSession session; - @Parameter( defaultValue="${project}" ) - protected MavenProject project; + @Parameter( defaultValue="${project}" ) + protected MavenProject project; - @Parameter( defaultValue="${reactorProjects}" ) - protected List reactorProjects; + @Parameter( defaultValue="${reactorProjects}" ) + protected List reactorProjects; - @Parameter( defaultValue = "${project.remoteProjectRepositories}") - protected List repos; + @Parameter( defaultValue = "${project.remoteProjectRepositories}") + protected List repos; - @Parameter( defaultValue = "${basedir}", property = "basedir", required = true) - protected File projectDirectory; + @Parameter( defaultValue = "${basedir}", property = "basedir", required = true) + protected File projectDirectory; - @Parameter( defaultValue = "${project.build.directory}", property = "outputDir", required = true ) - protected File outputDirectory; + @Parameter( defaultValue = "${project.build.directory}", property = "outputDir", required = true ) + protected File outputDirectory; - @Parameter( defaultValue = "${user.home}" ) - protected File homeDirectory; + @Parameter( defaultValue = "${user.home}" ) + protected File homeDirectory; - @Parameter( property = "baseUrl", defaultValue = "https://www.versioneye.com" ) - protected String baseUrl; + @Parameter( property = "baseUrl", defaultValue = "https://www.versioneye.com" ) + protected String baseUrl; - @Parameter( property = "apiPath", defaultValue = "/api/v2" ) - protected String apiPath; + @Parameter( property = "apiPath", defaultValue = "/api/v2" ) + protected String apiPath; - @Parameter( property = "projectId" ) - protected String projectId; + @Parameter( property = "projectId" ) + protected String projectId; - @Parameter( property = "apiKey" ) - protected String apiKey; + @Parameter( property = "apiKey" ) + protected String apiKey; - @Parameter( property = "propertiesPath" ) - protected String propertiesPath = null; + @Parameter( property = "propertiesPath" ) + protected String propertiesPath = null; - @Parameter( property = "proxyHost" ) - protected String proxyHost = null; + @Parameter( property = "proxyHost" ) + protected String proxyHost = null; - @Parameter( property = "proxyPort" ) - protected String proxyPort = null; + @Parameter( property = "proxyPort" ) + protected String proxyPort = null; - @Parameter( property = "proxyUser" ) - protected String proxyUser = null; + @Parameter( property = "proxyUser" ) + protected String proxyUser = null; - @Parameter( property = "proxyPassword" ) - protected String proxyPassword = null; + @Parameter( property = "proxyPassword" ) + protected String proxyPassword = null; - @Parameter( property = "updatePropertiesAfterCreate" ) - protected boolean updatePropertiesAfterCreate = true; + @Parameter( property = "updatePropertiesAfterCreate" ) + protected boolean updatePropertiesAfterCreate = true; - @Parameter( property = "mergeAfterCreate" ) - protected boolean mergeAfterCreate = true; + @Parameter( property = "mergeAfterCreate" ) + protected boolean mergeAfterCreate = true; - @Parameter( property = "parentGroupId" ) - protected String parentGroupId = null; + @Parameter( property = "parentGroupId" ) + protected String parentGroupId = null; - @Parameter( property = "parentArtifactId" ) - protected String parentArtifactId = null; + @Parameter( property = "parentArtifactId" ) + protected String parentArtifactId = null; - @Parameter( property = "nameStrategy" ) - protected String nameStrategy = "name"; + @Parameter( property = "nameStrategy" ) + protected String nameStrategy = "name"; - @Parameter( property = "trackPlugins" ) - protected Boolean trackPlugins = Boolean.TRUE; + @Parameter( property = "trackPlugins" ) + protected Boolean trackPlugins = Boolean.TRUE; - @Parameter( property = "licenseCheckBreakByUnknown" ) - protected Boolean licenseCheckBreakByUnknown = Boolean.FALSE; + @Parameter( property = "licenseCheckBreakByUnknown" ) + protected Boolean licenseCheckBreakByUnknown = Boolean.FALSE; - @Parameter( property = "skipScopes" ) - protected String skipScopes = null; + @Parameter( property = "skipScopes" ) + protected String skipScopes = null; - @Parameter( property = "organisation" ) - protected String organisation = null; + @Parameter( property = "organisation" ) + protected String organisation = null; - @Parameter( property = "team" ) - protected String team = null; + @Parameter( property = "team" ) + protected String team = null; - @Parameter( property = "visibility" ) - protected String visibility = null; + @Parameter( property = "visibility" ) + protected String visibility = null; - @Parameter( property = "name" ) - protected String name = null; + @Parameter( property = "name" ) + protected String name = null; - @Parameter( property = "ignoreDependencyManagement" ) - protected boolean ignoreDependencyManagement = false; + @Parameter( property = "ignoreDependencyManagement" ) + protected boolean ignoreDependencyManagement = false; - @Parameter( property = "transitiveDependencies" ) - protected boolean transitiveDependencies = false; + @Parameter( property = "transitiveDependencies" ) + protected boolean transitiveDependencies = false; - protected Properties properties = null; // Properties in src/main/resources - protected Properties homeProperties = null; // Properties in ~/.m2/ + protected Properties properties = null; // Properties in src/main/resources + protected Properties homeProperties = null; // Properties in ~/.m2/ - public void execute() throws MojoExecutionException, MojoFailureException { } + public void execute() throws MojoExecutionException, MojoFailureException { } - protected String fetchApiKey() throws Exception { - if (apiKey != null && !apiKey.isEmpty() ) - return apiKey; + protected String fetchApiKey() throws Exception { + if (apiKey != null && !apiKey.isEmpty() ) + return apiKey; - apiKey = System.getenv().get("VERSIONEYE_API_KEY"); + apiKey = System.getenv().get("VERSIONEYE_API_KEY"); - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String key = getPropertyFromPath(propertiesPath, "api_key"); - if (key != null && !key.isEmpty()){ - apiKey = key; - } - - propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; - key = getPropertyFromPath(propertiesPath, "api_key"); - if (key != null && !key.isEmpty()){ - apiKey = key; - } - - propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; - key = getPropertyFromPath(propertiesPath, "api_key"); - if (key != null && !key.isEmpty()){ - apiKey = key; - } - - if (apiKey == null){ - getLog().error("API Key can not be found!"); - throw new Exception("API Key can not be found!"); - } + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String key = getPropertyFromPath(propertiesPath, "api_key"); + if (key != null && !key.isEmpty()){ + apiKey = key; + } - return apiKey; + propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; + key = getPropertyFromPath(propertiesPath, "api_key"); + if (key != null && !key.isEmpty()){ + apiKey = key; } + propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; + key = getPropertyFromPath(propertiesPath, "api_key"); + if (key != null && !key.isEmpty()){ + apiKey = key; + } - protected String fetchBaseUrl() throws Exception { - if (baseUrl != null && !baseUrl.isEmpty() ) - return baseUrl; + if (apiKey == null){ + getLog().error("API Key can not be found!"); + throw new Exception("API Key can not be found!"); + } - baseUrl = System.getenv().get("VERSIONEYE_BASE_URL"); + return apiKey; + } - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String key = getPropertyFromPath(propertiesPath, "base_url"); - if (key != null && !key.isEmpty()){ - baseUrl = key; - } - propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; - key = getPropertyFromPath(propertiesPath, "base_url"); - if (key != null && !key.isEmpty()){ - baseUrl = key; - } + protected String fetchBaseUrl() throws Exception { + if (baseUrl != null && !baseUrl.isEmpty() ) + return baseUrl; - propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; - key = getPropertyFromPath(propertiesPath, "base_url"); - if (key != null && !key.isEmpty()){ - baseUrl = key; - } + baseUrl = System.getenv().get("VERSIONEYE_BASE_URL"); - return baseUrl; + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String key = getPropertyFromPath(propertiesPath, "base_url"); + if (key != null && !key.isEmpty()){ + baseUrl = key; } - - protected String fetchProjectId() throws Exception { - if (projectId != null && !projectId.isEmpty() ) - return projectId; - - if (propertiesPath != null && !propertiesPath.isEmpty()){ - String project_id = getPropertyFromPath(propertiesPath, "project_id"); - if (project_id != null && !project_id.isEmpty()){ - projectId = project_id; - } - } - - String pPath1 = projectDirectory + "/src/qa/resources/" + propertiesFile; - String project_id = getPropertyFromPath(pPath1, "project_id"); - if (project_id != null && !project_id.isEmpty()){ - projectId = project_id; - propertiesPath = pPath1; - } - - String pPath2 = projectDirectory + "/src/main/resources/" + propertiesFile; - project_id = getPropertyFromPath(pPath2, "project_id"); - if (project_id != null && !project_id.isEmpty()){ - projectId = project_id; - propertiesPath = pPath2; - } - - if (projectId == null || projectId.isEmpty()){ - String msg = "Searched in [" + pPath1 + ", " + pPath2 + ", "+ propertiesPath +"] for project_id but could't find any."; - getLog().error(msg); - throw new MojoExecutionException(msg); - } - - return projectId; + propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; + key = getPropertyFromPath(propertiesPath, "base_url"); + if (key != null && !key.isEmpty()){ + baseUrl = key; } - - protected Properties fetchProjectProperties() throws Exception { - if (properties != null) - return properties; - String propertiesPath = getPropertiesPath(); - System.out.println("propertiesPath: " + propertiesPath); - File file = new File(propertiesPath); - if (!file.exists()) - createPropertiesFile(file); - PropertiesUtils propertiesUtils = new PropertiesUtils(); - properties = propertiesUtils.readProperties(propertiesPath); - return properties; + propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; + key = getPropertyFromPath(propertiesPath, "base_url"); + if (key != null && !key.isEmpty()){ + baseUrl = key; } + return baseUrl; + } - protected String getPropertiesPath() throws Exception { - if (this.propertiesPath != null && !this.propertiesPath.isEmpty()) - return this.propertiesPath; - String propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; - File file = new File(propertiesPath); - if (!file.exists()) { - propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; - new File(propertiesPath); - } - this.propertiesPath = propertiesPath; - return propertiesPath; - } + protected String fetchProjectId() throws Exception { + if (projectId != null && !projectId.isEmpty() ) + return projectId; - private void createPropertiesFile(File file) throws IOException { - File parent = file.getParentFile(); - if (!parent.exists()){ - File grandpa = parent.getParentFile(); - if (!grandpa.exists()){ - grandpa.mkdirs(); - } - parent.mkdirs(); - } - file.createNewFile(); + if (propertiesPath != null && !propertiesPath.isEmpty()){ + String project_id = getPropertyFromPath(propertiesPath, "project_id"); + if (project_id != null && !project_id.isEmpty()){ + projectId = project_id; + } } + String pPath1 = projectDirectory + "/src/qa/resources/" + propertiesFile; + String project_id = getPropertyFromPath(pPath1, "project_id"); + if (project_id != null && !project_id.isEmpty()){ + projectId = project_id; + propertiesPath = pPath1; + } - protected void initTls(){ - TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){ - public X509Certificate[] getAcceptedIssuers(){return null;} - public void checkClientTrusted(X509Certificate[] certs, String authType){} - public void checkServerTrusted(X509Certificate[] certs, String authType){} - }}; - try { - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, trustAllCerts, new SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } catch (Exception e) { - e.printStackTrace(); - } + String pPath2 = projectDirectory + "/src/main/resources/" + propertiesFile; + project_id = getPropertyFromPath(pPath2, "project_id"); + if (project_id != null && !project_id.isEmpty()){ + projectId = project_id; + propertiesPath = pPath2; } + if (projectId == null || projectId.isEmpty()){ + String msg = "Searched in [" + pPath1 + ", " + pPath2 + ", "+ propertiesPath +"] for project_id but could't find any."; + getLog().error(msg); + throw new MojoExecutionException(msg); + } - protected void setProxy(){ - try{ - proxyHost = fetchProxyHost(); - proxyPort = fetchProxyPort(); - proxyUser = fetchProxyUser(); - proxyPassword = fetchProxyPassword(); - - boolean emptyProxyHost = proxyHost == null || proxyHost.isEmpty(); - boolean emptyProxyPort = proxyPort == null || proxyPort.isEmpty(); - if (emptyProxyHost && emptyProxyPort){ - return ; - } - - System.setProperty("proxySet", "true"); - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - System.setProperty("https.proxyHost", proxyHost); - System.setProperty("https.proxyPort", proxyPort); - - boolean emptyProxyUser = proxyUser == null || proxyUser.isEmpty(); - boolean emptyProxyPass = proxyPassword == null || proxyPassword.isEmpty(); - if (emptyProxyUser && emptyProxyPass ) { - return ; - } - - System.setProperty("http.proxyUser", proxyUser); - System.setProperty("http.proxyPassword", proxyPassword); - System.setProperty("https.proxyUser", proxyUser); - System.setProperty("https.proxyPassword", proxyPassword); - } catch (Exception ex) { - ex.printStackTrace(); - } + return projectId; + } + + + protected Properties fetchProjectProperties() throws Exception { + if (properties != null) + return properties; + String propertiesPath = getPropertiesPath(); + System.out.println("propertiesPath: " + propertiesPath); + File file = new File(propertiesPath); + if (!file.exists()) + createPropertiesFile(file); + PropertiesUtils propertiesUtils = new PropertiesUtils(); + properties = propertiesUtils.readProperties(propertiesPath); + return properties; + } + + + protected String getPropertiesPath() throws Exception { + if (this.propertiesPath != null && !this.propertiesPath.isEmpty()) + return this.propertiesPath; + String propertiesPath = projectDirectory + "/src/qa/resources/" + propertiesFile; + File file = new File(propertiesPath); + if (!file.exists()) { + propertiesPath = projectDirectory + "/src/main/resources/" + propertiesFile; + new File(propertiesPath); + } + this.propertiesPath = propertiesPath; + return propertiesPath; + } + + + private void createPropertiesFile(File file) throws IOException { + File parent = file.getParentFile(); + if (!parent.exists()){ + File grandpa = parent.getParentFile(); + if (!grandpa.exists()){ + grandpa.mkdirs(); + } + parent.mkdirs(); } + file.createNewFile(); + } + + + protected void initTls(){ + TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){ + public X509Certificate[] getAcceptedIssuers(){return null;} + public void checkClientTrusted(X509Certificate[] certs, String authType){} + public void checkServerTrusted(X509Certificate[] certs, String authType){} + }}; + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + protected void setProxy(){ + try{ + proxyHost = fetchProxyHost(); + proxyPort = fetchProxyPort(); + proxyUser = fetchProxyUser(); + proxyPassword = fetchProxyPassword(); + + boolean emptyProxyHost = proxyHost == null || proxyHost.isEmpty(); + boolean emptyProxyPort = proxyPort == null || proxyPort.isEmpty(); + if (emptyProxyHost && emptyProxyPort){ + return ; + } + + System.setProperty("proxySet", "true"); + System.setProperty("http.proxyHost", proxyHost); + System.setProperty("http.proxyPort", proxyPort); + System.setProperty("https.proxyHost", proxyHost); + System.setProperty("https.proxyPort", proxyPort); + + boolean emptyProxyUser = proxyUser == null || proxyUser.isEmpty(); + boolean emptyProxyPass = proxyPassword == null || proxyPassword.isEmpty(); + if (emptyProxyUser && emptyProxyPass ) { + return ; + } + + System.setProperty("http.proxyUser", proxyUser); + System.setProperty("http.proxyPassword", proxyPassword); + System.setProperty("https.proxyUser", proxyUser); + System.setProperty("https.proxyPassword", proxyPassword); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - private String fetchProxyHost(){ - if (proxyHost != null && !proxyHost.isEmpty()){ - return proxyHost; - } - try{ - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String host = getPropertyFromPath(propertiesPath, "proxyHost"); - if (host != null && !host.isEmpty()){ - proxyHost = host; - return proxyHost; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - String host = System.getenv().get("VERSIONEYE_PROXY_HOST"); - if (host != null && !host.isEmpty()){ - proxyHost = host; - return proxyHost; - } - return null; + private String fetchProxyHost(){ + if (proxyHost != null && !proxyHost.isEmpty()){ + return proxyHost; } - - private String fetchProxyPort(){ - if (proxyPort != null && !proxyPort.isEmpty()){ - return proxyPort; - } - try{ - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String port = getPropertyFromPath(propertiesPath, "proxyPort"); - if (port != null && !port.isEmpty()){ - proxyPort = port; - return proxyPort; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - String port = System.getenv().get("VERSIONEYE_PROXY_PORT"); - if (port != null && !port.isEmpty()){ - proxyPort = port; - return proxyPort; - } - return null; + try{ + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String host = getPropertyFromPath(propertiesPath, "proxyHost"); + if (host != null && !host.isEmpty()){ + proxyHost = host; + return proxyHost; + } + } catch (Exception ex) { + ex.printStackTrace(); } - - private String fetchProxyUser(){ - if (proxyUser != null && !proxyUser.isEmpty()){ - return proxyUser; - } - try{ - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String user = getPropertyFromPath(propertiesPath, "proxyUser"); - if (user != null && !user.isEmpty()){ - proxyUser = user; - return proxyUser; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - String user = System.getenv().get("VERSIONEYE_PROXY_USER"); - if (user != null && !user.isEmpty()){ - proxyUser = user; - return proxyUser; - } - return null; + String host = System.getenv().get("VERSIONEYE_PROXY_HOST"); + if (host != null && !host.isEmpty()){ + proxyHost = host; + return proxyHost; } + return null; + } - private String fetchProxyPassword(){ - if (proxyPassword != null && !proxyPassword.isEmpty()){ - return proxyPassword; - } - try{ - String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; - String pass = getPropertyFromPath(propertiesPath, "proxyPassword"); - if (pass != null && !pass.isEmpty()){ - proxyPassword = pass; - return proxyPassword; - } - } catch (Exception ex) { - ex.printStackTrace(); - } - String password = System.getenv().get("VERSIONEYE_PROXY_PASSWORD"); - if (password != null && !password.isEmpty()){ - proxyPassword = password; - return proxyPassword; - } - return null; + private String fetchProxyPort(){ + if (proxyPort != null && !proxyPort.isEmpty()){ + return proxyPort; + } + try{ + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String port = getPropertyFromPath(propertiesPath, "proxyPort"); + if (port != null && !port.isEmpty()){ + proxyPort = port; + return proxyPort; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + String port = System.getenv().get("VERSIONEYE_PROXY_PORT"); + if (port != null && !port.isEmpty()){ + proxyPort = port; + return proxyPort; } + return null; + } + private String fetchProxyUser(){ + if (proxyUser != null && !proxyUser.isEmpty()){ + return proxyUser; + } + try{ + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String user = getPropertyFromPath(propertiesPath, "proxyUser"); + if (user != null && !user.isEmpty()){ + proxyUser = user; + return proxyUser; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + String user = System.getenv().get("VERSIONEYE_PROXY_USER"); + if (user != null && !user.isEmpty()){ + proxyUser = user; + return proxyUser; + } + return null; + } - private String getPropertyFromPath(String propertiesPath, String propertiesKey ) throws Exception { - File file = new File(propertiesPath); - if (file.exists()){ - PropertiesUtils propertiesUtils = new PropertiesUtils(); - Properties homeProperties = propertiesUtils.readProperties(propertiesPath); - return homeProperties.getProperty(propertiesKey); - } else { - getLog().debug("File " + propertiesPath + " does not exist"); - } - return null; + private String fetchProxyPassword(){ + if (proxyPassword != null && !proxyPassword.isEmpty()){ + return proxyPassword; + } + try{ + String propertiesPath = homeDirectory + "/.m2/" + propertiesFile; + String pass = getPropertyFromPath(propertiesPath, "proxyPassword"); + if (pass != null && !pass.isEmpty()){ + proxyPassword = pass; + return proxyPassword; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + String password = System.getenv().get("VERSIONEYE_PROXY_PASSWORD"); + if (password != null && !password.isEmpty()){ + proxyPassword = password; + return proxyPassword; + } + return null; + } + + + private String getPropertyFromPath(String propertiesPath, String propertiesKey ) throws Exception { + File file = new File(propertiesPath); + if (file.exists()){ + PropertiesUtils propertiesUtils = new PropertiesUtils(); + Properties homeProperties = propertiesUtils.readProperties(propertiesPath); + return homeProperties.getProperty(propertiesKey); + } else { + getLog().debug("File " + propertiesPath + " does not exist"); } + return null; + } } diff --git a/src/main/java/com/versioneye/UpdateMojo.java b/src/main/java/com/versioneye/UpdateMojo.java index 3291e61..f70ca63 100644 --- a/src/main/java/com/versioneye/UpdateMojo.java +++ b/src/main/java/com/versioneye/UpdateMojo.java @@ -1,31 +1,33 @@ package com.versioneye; -import com.versioneye.dto.ProjectJsonResponse; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import com.versioneye.dto.ProjectJsonResponse; + import java.io.ByteArrayOutputStream; /** * Updates an existing project at VersionEye with the dependencies from the current project. */ +@SuppressWarnings("WeakerAccess") @Mojo( name = "update", defaultPhase = LifecyclePhase.PACKAGE ) public class UpdateMojo extends ProjectMojo { @Parameter( property = "resource", defaultValue = "/projects") private String resource; - + @Override public void execute() throws MojoExecutionException, MojoFailureException { try{ setProxy(); prettyPrintStart(); - ByteArrayOutputStream jsonDependenciesStream = null; - if (transitiveDependencies == true){ + ByteArrayOutputStream jsonDependenciesStream; + if (transitiveDependencies){ jsonDependenciesStream = getTransitiveDependenciesJsonStream(nameStrategy); } else { jsonDependenciesStream = getDirectDependenciesJsonStream(nameStrategy); @@ -41,8 +43,8 @@ public void execute() throws MojoExecutionException, MojoFailureException { } catch( Exception exception ){ exception.printStackTrace(); throw new MojoExecutionException("Oh no! Something went wrong. " + - "Get in touch with the VersionEye guys and give them feedback. " + - "You find them on Twitter at https//twitter.com/VersionEye. ", exception); + "Get in touch with the VersionEye guys and give them feedback. " + + "You find them on Twitter at https//twitter.com/VersionEye. ", exception); } } @@ -50,7 +52,7 @@ public void execute() throws MojoExecutionException, MojoFailureException { protected ProjectJsonResponse uploadDependencies(ByteArrayOutputStream outStream) throws Exception { try { String projectId = fetchProjectId(); - if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())){ + if (mavenSession.getTopLevelProject().getId().equals(mavenSession.getCurrentProject().getId())) { mavenSession.getTopLevelProject().setContextValue("veye_project_id", projectId); } return updateExistingProject(resource, projectId, outStream); @@ -65,12 +67,9 @@ protected ProjectJsonResponse uploadDependencies(ByteArrayOutputStream outStream } } - - protected void prettyPrintStart(){ + protected void prettyPrintStart() { getLog().info("."); getLog().info("Starting to update dependencies to server. This can take a couple seconds ... "); getLog().info("."); } - - } diff --git a/src/main/java/com/versioneye/dto/ErrorJsonResponse.java b/src/main/java/com/versioneye/dto/ErrorJsonResponse.java index 41783c0..75c6572 100644 --- a/src/main/java/com/versioneye/dto/ErrorJsonResponse.java +++ b/src/main/java/com/versioneye/dto/ErrorJsonResponse.java @@ -12,8 +12,8 @@ public String getError() { return error; } + @SuppressWarnings("unused") public void setError(String error) { this.error = error; } - } diff --git a/src/main/java/com/versioneye/dto/ProjectDependency.java b/src/main/java/com/versioneye/dto/ProjectDependency.java index d553ae4..95b14c9 100644 --- a/src/main/java/com/versioneye/dto/ProjectDependency.java +++ b/src/main/java/com/versioneye/dto/ProjectDependency.java @@ -3,6 +3,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties; +@SuppressWarnings("unused") @JsonIgnoreProperties(ignoreUnknown = true) public class ProjectDependency { diff --git a/src/main/java/com/versioneye/dto/ProjectJsonResponse.java b/src/main/java/com/versioneye/dto/ProjectJsonResponse.java index 4a62c44..a477b02 100644 --- a/src/main/java/com/versioneye/dto/ProjectJsonResponse.java +++ b/src/main/java/com/versioneye/dto/ProjectJsonResponse.java @@ -5,6 +5,7 @@ /** * Java representation of the project JSON response from VersionEye API. */ +@SuppressWarnings("unused") @JsonIgnoreProperties(ignoreUnknown = true) public class ProjectJsonResponse { @@ -16,6 +17,8 @@ public class ProjectJsonResponse { private Integer licenses_unknown = 0; private Integer sv_count = 0; + private ProjectDependency[] dependencies; + public Integer getSv_count() { return sv_count; } @@ -24,8 +27,6 @@ public void setSv_count(Integer sv_count) { this.sv_count = sv_count; } - private ProjectDependency[] dependencies; - public Integer getLicenses_red() { return licenses_red; } diff --git a/src/main/java/com/versioneye/utils/CollectionUtils.java b/src/main/java/com/versioneye/utils/CollectionUtils.java new file mode 100644 index 0000000..03293f0 --- /dev/null +++ b/src/main/java/com/versioneye/utils/CollectionUtils.java @@ -0,0 +1,20 @@ +package com.versioneye.utils; + +import java.util.Collection; + +/** + * @author glick + */ +@SuppressWarnings("WeakerAccess") +public class CollectionUtils +{ + private CollectionUtils() {} + + public static boolean collectionIsEmpty(Collection collection) { + return collection == null || collection.isEmpty(); + } + + public static boolean collectionNotEmpty(Collection collection) { + return !collectionIsEmpty(collection); + } +} diff --git a/src/main/java/com/versioneye/utils/DependencyUtils.java b/src/main/java/com/versioneye/utils/DependencyUtils.java index acde8ad..4e33449 100644 --- a/src/main/java/com/versioneye/utils/DependencyUtils.java +++ b/src/main/java/com/versioneye/utils/DependencyUtils.java @@ -10,35 +10,41 @@ import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; /** * Utility methods for Maven Dependencies. */ public class DependencyUtils { - public static List collectAllDependencies(List dependencies) { - List result = new ArrayList(dependencies.size()); - for (Dependency dependency : dependencies) { - result.add(dependency.getArtifact()); - } - return result; - } + private DependencyUtils() {} + + public static List collectAllDependencies(List dependencies) { + List result = new ArrayList<>(dependencies.size()); - public static List collectDirectDependencies(List dependencies) { - List result = new ArrayList(dependencies.size()); - for (DependencyNode dependencyNode : dependencies) { - result.add(dependencyNode.getDependency().getArtifact()); - } - return result; + for (Dependency dependency : dependencies) { + result.add(dependency.getArtifact()); } - public static CollectRequest getCollectRequest(MavenProject project, List repos, String scope){ - Artifact a = new DefaultArtifact( project.getArtifact().toString() ); - DefaultArtifact pom = new DefaultArtifact( a.getGroupId(), a.getArtifactId(), "pom", a.getVersion() ); - CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRoot(new Dependency(pom, scope )); - collectRequest.setRepositories(repos); - return collectRequest; + return result; + } + + public static List collectDirectDependencies(List dependencies) { + List result = new ArrayList<>(dependencies.size()); + + for (DependencyNode dependencyNode : dependencies) { + result.add(dependencyNode.getDependency().getArtifact()); } + return result; + } + + public static CollectRequest getCollectRequest(MavenProject project, List repos, String scope){ + Artifact a = new DefaultArtifact( project.getArtifact().toString() ); + DefaultArtifact pom = new DefaultArtifact( a.getGroupId(), a.getArtifactId(), "pom", a.getVersion() ); + CollectRequest collectRequest = new CollectRequest(); + collectRequest.setRoot(new Dependency(pom, scope )); + collectRequest.setRepositories(repos); + return collectRequest; + } } diff --git a/src/main/java/com/versioneye/utils/HttpUtils.java b/src/main/java/com/versioneye/utils/HttpUtils.java index 9d86b1d..07dd4aa 100644 --- a/src/main/java/com/versioneye/utils/HttpUtils.java +++ b/src/main/java/com/versioneye/utils/HttpUtils.java @@ -1,6 +1,5 @@ package com.versioneye.utils; -import com.versioneye.dto.ErrorJsonResponse; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; @@ -16,6 +15,9 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.SystemDefaultHttpClient; import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.plexus.util.StringUtils; + +import com.versioneye.dto.ErrorJsonResponse; import java.io.BufferedReader; import java.io.InputStream; @@ -26,11 +28,12 @@ /** * Methods to deal with the HTTP protocol. */ +@SuppressWarnings("WeakerAccess") public class HttpUtils { - public static Integer ONE_SECOND = 1000; - public static Integer ONE_MINUTE = ONE_SECOND * 60; - public static Integer TEN_MINUTE = ONE_MINUTE * 10; + public static final Integer ONE_SECOND = 1000; + public static final Integer ONE_MINUTE = ONE_SECOND * 60; + public static final Integer TEN_MINUTE = ONE_MINUTE * 10; public static String get(String url) throws Exception { HttpURLConnection con = createConnection(url); @@ -40,14 +43,13 @@ public static String get(String url) throws Exception { con.setReadTimeout(TEN_MINUTE); con.setRequestProperty("User-Agent", "VersionEye Maven Plugin"); - int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; - StringBuffer response = new StringBuffer(); + StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } @@ -62,16 +64,16 @@ public static Reader post(String url, byte[] data, String dataName, String visib MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart(dataName, byteArrayBody); - if (visibility != null && !visibility.isEmpty()) + if (StringUtils.isNotBlank(visibility)) multipartEntity.addPart("visibility", new StringBody(visibility)); - if (name != null && !name.isEmpty()) + if (StringUtils.isNotBlank(name)) multipartEntity.addPart("name", new StringBody(name)); - if (orga_name != null && !orga_name.isEmpty()) + if (StringUtils.isNotBlank(orga_name)) multipartEntity.addPart("orga_name", new StringBody(orga_name)); - if (team != null && !team.isEmpty()) + if (StringUtils.isNotBlank(team)) multipartEntity.addPart("team_name", new StringBody(team)); httpPost.setEntity(multipartEntity); @@ -92,6 +94,7 @@ public static Reader post(String url, byte[] data, String dataName, String visib public static String delete(String url) throws Exception { HttpURLConnection con = createConnection(url); setProxyAuthIfAvailable(); + con.setRequestMethod("GET"); con.setConnectTimeout(TEN_MINUTE); con.setReadTimeout(TEN_MINUTE); @@ -104,7 +107,7 @@ public static String delete(String url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; - StringBuffer response = new StringBuffer(); + StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } @@ -112,7 +115,6 @@ public static String delete(String url) throws Exception { return response.toString(); } - private static String getErrorMessage(HttpResponse response) throws Exception { String errorMsg = getErrorFromJson(response); if (errorMsg != null){ @@ -121,7 +123,7 @@ private static String getErrorMessage(HttpResponse response) throws Exception { return getPureBodyString(response); } - private static String getErrorFromJson(HttpResponse response){ + private static String getErrorFromJson(HttpResponse response) { try { ObjectMapper mapper = new ObjectMapper(); ErrorJsonResponse error = mapper.readValue(response.getEntity().getContent(), ErrorJsonResponse.class); @@ -132,12 +134,12 @@ private static String getErrorFromJson(HttpResponse response){ } } - private static String getPureBodyString(HttpResponse response){ + private static String getPureBodyString(HttpResponse response) { try { InputStream content = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader( content ) ); String inputLine; - StringBuffer body = new StringBuffer(); + StringBuilder body = new StringBuilder(); while ((inputLine = in.readLine()) != null) { body.append(inputLine); } @@ -147,7 +149,6 @@ private static String getPureBodyString(HttpResponse response){ exception.printStackTrace(); return ""; } - } private static HttpClient createHttpClient(){ @@ -200,5 +201,4 @@ private static void setProxyAuthIfAvailable(){ Authenticator.setDefault(new ProxyAuthenticator(user, pass)); } } - } diff --git a/src/main/java/com/versioneye/utils/JsonUtils.java b/src/main/java/com/versioneye/utils/JsonUtils.java index dc20d30..b3dbcef 100644 --- a/src/main/java/com/versioneye/utils/JsonUtils.java +++ b/src/main/java/com/versioneye/utils/JsonUtils.java @@ -1,5 +1,6 @@ package com.versioneye.utils; +import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; @@ -10,18 +11,28 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStream; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Methods to deal with JSON. */ +@SuppressWarnings("WeakerAccess") public class JsonUtils { - public ByteArrayOutputStream dependenciesToJson(MavenProject project, List dependencies, List plugins, String nameStrategy) throws Exception { - List> dependencyHashes = new ArrayList>(); - if ((dependencies != null && !dependencies.isEmpty()) - || (plugins != null && !plugins.isEmpty())) { + private static final String VERSION = "version"; + private static final String NAME = "name"; + private static final String SCOPE = "scope"; + + public ByteArrayOutputStream dependenciesToJson(MavenProject project, List dependencies, List plugins, String nameStrategy) throws + IOException { + List> dependencyHashes = new ArrayList<>(); + if ((CollectionUtils.collectionNotEmpty(dependencies)) || (CollectionUtils.collectionNotEmpty(plugins))) { dependencyHashes = getDependencyHashes(dependencies, plugins); } ByteArrayOutputStream outstream = new ByteArrayOutputStream(); @@ -29,94 +40,105 @@ public ByteArrayOutputStream dependenciesToJson(MavenProject project, List directDependencies) throws Exception { + public ByteArrayOutputStream artifactsToJson(List directDependencies) throws IOException { List> hashes = getHashes(directDependencies); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); toJson(outstream, hashes); return outstream; } - public void dependenciesToJsonFile(String name, Map directDependencies, String file) throws Exception { + @SuppressWarnings("UnusedParameters") + public void dependenciesToJsonFile(String name, Map directDependencies, String file) throws IOException { File targetFile = getTargetFile(file); toJson(new FileOutputStream(targetFile), directDependencies); } - public void dependenciesToJsonFile(MavenProject project, List directDependencies, String file, String nameStrategy) throws Exception { + @SuppressWarnings("unused") + public void dependenciesToJsonFile(MavenProject project, List directDependencies, String file, String nameStrategy) throws IOException { List> dependencyHashes = getHashes(directDependencies); File targetFile = getTargetFile(file); toJson(new FileOutputStream(targetFile), getJsonPom(project, dependencyHashes, nameStrategy)); } - public static void toJson(OutputStream output, Object input) throws Exception { + public static void toJson(OutputStream output, Object input) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.writeValue(output, input); } - public List> getHashes(List directDependencies){ - List> hashes = (List>) new Vector>(directDependencies.size()); + public List> getHashes(List directDependencies) { + List> hashes = new ArrayList<>(directDependencies.size()); hashes.addAll( generateHashForJsonOutput( directDependencies)); return hashes; } - public List> getDependencyHashes(List directDependencies, List plugins){ - List> hashes = (List>) new Vector>(); - if (directDependencies != null && directDependencies.size() > 0){ + public List> getDependencyHashes(List directDependencies, List plugins) { + + List> hashes = new ArrayList<>(); + + if (CollectionUtils.collectionNotEmpty(directDependencies)) { hashes.addAll( generateHashFromDependencyList( directDependencies)); } - if (plugins != null && plugins.size() > 0){ + + if (CollectionUtils.collectionNotEmpty(plugins)) { hashes.addAll( generateHashFromPluginList(plugins)); } + return hashes; } public static List> generateHashForJsonOutput(List input) { - List> output = new Vector>(input.size()); + List> output = new ArrayList<>(input.size()); for (Artifact artifact : input) { - HashMap hash = new HashMap(2); - hash.put("version", artifact.getVersion()); - hash.put("name", artifact.getGroupId() + ":" + artifact.getArtifactId()); - output.add(hash); + Map map = new HashMap<>(2); + map.put(VERSION, artifact.getVersion()); + map.put(NAME, artifact.getGroupId() + ":" + artifact.getArtifactId()); + output.add(map); } return output; } public static List> generateHashFromDependencyList(List input) { - if (input == null || input.isEmpty()){ - return null; + if (CollectionUtils.collectionIsEmpty(input)){ + return Collections.emptyList(); } - List> output = new Vector>(input.size()); + + List> output = new ArrayList<>(input.size()); + for (Dependency dependency : input) { - HashMap hash = new HashMap(2); - hash.put("version", dependency.getVersion()); - hash.put("name", dependency.getGroupId() + ":" + dependency.getArtifactId()); - hash.put("scope", dependency.getScope() ); - output.add(hash); + Map map = new HashMap<>(2); + map.put(VERSION, dependency.getVersion()); + map.put(NAME, dependency.getGroupId() + ":" + dependency.getArtifactId()); + map.put(SCOPE, dependency.getScope() ); + output.add(map); } + return output; } public static List> generateHashFromPluginList(List input) { - if (input == null || input.isEmpty()){ - return null; + if (CollectionUtils.collectionIsEmpty(input)){ + return Collections.emptyList(); } - List> output = new Vector>(input.size()); + + List> output = new ArrayList<>(input.size()); for (Plugin plugin : input) { - HashMap hash = new HashMap(2); - hash.put("version", plugin.getVersion()); - hash.put("name", plugin.getGroupId() + ":" + plugin.getArtifactId()); - hash.put("scope", "plugin" ); - output.add(hash); + Map map = new HashMap<>(2); + map.put(VERSION, plugin.getVersion()); + map.put(NAME, plugin.getGroupId() + ":" + plugin.getArtifactId()); + map.put(SCOPE, "plugin" ); + output.add(map); } + return output; } public Map getJsonPom(MavenProject project, List> dependencyHashes, String nameStrategy){ - Map pom = new HashMap(); - pom.put("name", getNameFor(project, nameStrategy)); + Map pom = new HashMap<>(); + pom.put(NAME, getNameFor(project, nameStrategy)); pom.put("group_id", project.getGroupId()); pom.put("artifact_id", project.getArtifactId()); - pom.put("version", project.getVersion()); + pom.put(VERSION, project.getVersion()); pom.put("language", "Java"); pom.put("prod_type", "Maven2"); pom.put("licenses", project.getLicenses()); @@ -126,22 +148,30 @@ public Map getJsonPom(MavenProject project, List "); + System.exit(1); + } + try { + SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(args[0], Integer.parseInt(args[1])); + + InputStream in = sslsocket.getInputStream(); + OutputStream out = sslsocket.getOutputStream(); + + // Write a test byte to get a reaction :) + out.write(1); + + while (in.available() > 0) { + System.out.print(in.read()); + } + System.out.println("Successfully connected"); + + } catch (Exception exception) { + exception.printStackTrace(); + } + } +} diff --git a/src/test/java/com/versioneye/utils/CollectionUtilsTest.java b/src/test/java/com/versioneye/utils/CollectionUtilsTest.java new file mode 100644 index 0000000..0c865cc --- /dev/null +++ b/src/test/java/com/versioneye/utils/CollectionUtilsTest.java @@ -0,0 +1,37 @@ +package com.versioneye.utils; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author glick + */ +public class CollectionUtilsTest +{ + @Test + public void testNullList() { + List nullList = null; + + assertThat(CollectionUtils.collectionIsEmpty(nullList)).isTrue(); + } + + @Test + public void testEmptyList() { + List emptyList = new ArrayList(); + + assertThat(CollectionUtils.collectionIsEmpty(emptyList)).isTrue(); + } + + @Test + public void demonstrateNonEmptyList() { + List hasContent = Arrays.asList("abcd", "efgh"); + + assertThat(CollectionUtils.collectionIsEmpty(hasContent)).isFalse(); + assertThat(CollectionUtils.collectionNotEmpty(hasContent)).isTrue(); + } +} diff --git a/src/test/java/com/versioneye/utils/HttpUtilsTest.java b/src/test/java/com/versioneye/utils/HttpUtilsTest.java index 770958a..5c9641f 100644 --- a/src/test/java/com/versioneye/utils/HttpUtilsTest.java +++ b/src/test/java/com/versioneye/utils/HttpUtilsTest.java @@ -30,4 +30,10 @@ public void postTestData() throws Exception{ HttpUtils.post(url, outstream.toByteArray(), "project_file", null, null, null, null); } + @Test + public void myProjectTest() throws Exception { + + String url = "https://www.versioneye.com/api/v2/projects/570d35bffcd19a0045440b35?api_key=1d207d70adb7021e7bc9"; + } + }