Skip to content

Commit

Permalink
[MINSTALL-192] - Code cleanups
Browse files Browse the repository at this point in the history
 * Reversed inverse logic
 * readingPomFromJarFile
   simplyfied a lot.
   - replaced IOUtil.copy with Files.copy()
   - Usage of try-with-resources instead of manually calling .close()
 * Removed StringUtils replaced with a Predicate.
  • Loading branch information
khmarbaise committed Oct 24, 2023
1 parent 429ad5b commit 30d2b53
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 115 deletions.
138 changes: 48 additions & 90 deletions src/main/java/org/apache/maven/plugins/install/InstallFileMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.util.Enumeration;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
Expand All @@ -43,10 +43,6 @@
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.XmlStreamReader;
import org.codehaus.plexus.util.xml.XmlStreamWriter;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.eclipse.aether.DefaultRepositoryCache;
import org.eclipse.aether.DefaultRepositorySystemSession;
Expand All @@ -61,6 +57,9 @@
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.eclipse.aether.util.artifact.SubArtifact;

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

/**
* Installs a file in the local repository.
*
Expand Down Expand Up @@ -162,6 +161,10 @@ public class InstallFileMojo extends AbstractMojo {
@Parameter(property = "localRepositoryPath")
private File localRepositoryPath;

private static final Predicate<String> IS_EMPTY = s -> isNull(s) || s.isEmpty();

private static final Predicate<String> IS_POM_PACKAGING = "pom"::equals;

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (!file.exists()) {
Expand Down Expand Up @@ -192,17 +195,17 @@ public void execute() throws MojoExecutionException, MojoFailureException {

File temporaryPom = null;

if (pomFile != null) {
processModel(readModel(pomFile));
} else {
if (pomFile == null) {
temporaryPom = readingPomFromJarFile();
if (!Boolean.TRUE.equals(generatePom)) {
pomFile = temporaryPom;
getLog().debug("Using JAR embedded POM as pomFile");
}
} else {
processModel(readModel(pomFile));
}

if (groupId == null || artifactId == null || version == null || packaging == null) {
if (isNull(groupId) || isNull(artifactId) || isNull(version) || isNull(packaging)) {
throw new MojoExecutionException("The artifact information is incomplete: 'groupId', 'artifactId', "
+ "'version' and 'packaging' are required.");
}
Expand All @@ -213,13 +216,11 @@ public void execute() throws MojoExecutionException, MojoFailureException {

InstallRequest installRequest = new InstallRequest();

boolean isFilePom = classifier == null && "pom".equals(packaging);
boolean isFilePom = isNull(classifier) && IS_POM_PACKAGING.test(packaging);
if (!isFilePom) {
ArtifactType artifactType =
repositorySystemSession.getArtifactTypeRegistry().get(packaging);
if (artifactType != null
&& (classifier == null || classifier.isEmpty())
&& !StringUtils.isEmpty(artifactType.getClassifier())) {
if (nonNull(artifactType) && IS_EMPTY.test(classifier) && !IS_EMPTY.test(artifactType.getClassifier())) {
classifier = artifactType.getClassifier();
}
}
Expand All @@ -236,17 +237,17 @@ public void execute() throws MojoExecutionException, MojoFailureException {
+ LS + LS + "File in question is: " + file + LS);
}

if (!"pom".equals(packaging)) {
if (pomFile != null) {
installRequest.addArtifact(new SubArtifact(mainArtifact, "", "pom", pomFile));
} else {
if (!IS_POM_PACKAGING.test(packaging)) {
if (isNull(pomFile)) {
if (Boolean.TRUE.equals(generatePom) || (generatePom == null && !pomLocalFile.exists())) {
temporaryPom = generatePomFile();
getLog().debug("Installing generated POM");
installRequest.addArtifact(new SubArtifact(mainArtifact, "", "pom", temporaryPom));
} else if (generatePom == null) {
getLog().debug("Skipping installation of generated POM, already present in local repository");
}
} else {
installRequest.addArtifact(new SubArtifact(mainArtifact, "", "pom", pomFile));
}
}

Expand All @@ -270,70 +271,40 @@ public void execute() throws MojoExecutionException, MojoFailureException {
}
}

private File readingPomFromJarFile() throws MojoExecutionException {
File pomFile = null;

JarFile jarFile = null;
try {
Pattern pomEntry = Pattern.compile("META-INF/maven/.*/pom\\.xml");

jarFile = new JarFile(file);

Enumeration<JarEntry> jarEntries = jarFile.entries();

while (jarEntries.hasMoreElements()) {
JarEntry entry = jarEntries.nextElement();

if (pomEntry.matcher(entry.getName()).matches()) {
getLog().debug("Loading " + entry.getName());
private static final Pattern POM_ENTRY_PATTERN = Pattern.compile("META-INF/maven/.*/pom\\.xml");

InputStream pomInputStream = null;
OutputStream pomOutputStream = null;
private static final Predicate<JarEntry> IS_POM_ENTRY =
entry -> POM_ENTRY_PATTERN.matcher(entry.getName()).matches();

try {
pomInputStream = jarFile.getInputStream(entry);
private File readingPomFromJarFile() throws MojoExecutionException {

String base = file.getName();
if (base.indexOf('.') > 0) {
base = base.substring(0, base.lastIndexOf('.'));
}
pomFile = File.createTempFile(base, ".pom");
String base = file.getName();
if (base.contains(".")) {
base = base.substring(0, base.lastIndexOf('.'));
}

pomOutputStream = Files.newOutputStream(pomFile.toPath());
try (JarFile jarFile = new JarFile(file)) {

IOUtil.copy(pomInputStream, pomOutputStream);
JarEntry pomEntry = jarFile.stream().filter(IS_POM_ENTRY).findAny().orElse(null);

pomOutputStream.close();
pomOutputStream = null;
if (isNull(pomEntry)) {
// This means there is no entry which matches the "pom.xml"...(or in other words: not packaged by Maven)
getLog().info("pom.xml not found in " + file.getName());
return null;
}

pomInputStream.close();
pomInputStream = null;
Path tempPomFile = Files.createTempFile(base, ".pom");

processModel(readModel(pomFile));
Files.copy(jarFile.getInputStream(pomEntry), tempPomFile, StandardCopyOption.REPLACE_EXISTING);

break;
} finally {
IOUtil.close(pomInputStream);
IOUtil.close(pomOutputStream);
}
}
}
getLog().debug("Loading " + pomEntry.getName());
processModel(readModel(tempPomFile.toFile()));
return tempPomFile.toFile();

if (pomFile == null) {
getLog().info("pom.xml not found in " + file.getName());
}
} catch (IOException e) {
// ignore, artifact not packaged by Maven
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
// we did our best
}
}
return null;
}
return pomFile;
}

/**
Expand All @@ -344,21 +315,14 @@ private File readingPomFromJarFile() throws MojoExecutionException {
* @throws MojoExecutionException If the POM could not be parsed.
*/
private Model readModel(File pomFile) throws MojoExecutionException {
Reader reader = null;
try {
reader = new XmlStreamReader(pomFile);
final Model model = new MavenXpp3Reader().read(reader);
reader.close();
reader = null;
return model;
try (InputStream reader = Files.newInputStream(pomFile.toPath())) {
return new MavenXpp3Reader().read(reader);
} catch (FileNotFoundException e) {
throw new MojoExecutionException("File not found " + pomFile, e);
} catch (IOException e) {
throw new MojoExecutionException("Error reading POM " + pomFile, e);
} catch (XmlPullParserException e) {
throw new MojoExecutionException("Error parsing POM " + pomFile, e);
} finally {
IOUtil.close(reader);
}
}

Expand Down Expand Up @@ -419,21 +383,15 @@ private Model generateModel() {
*/
private File generatePomFile() throws MojoExecutionException {
Model model = generateModel();

Writer writer = null;
try {
File pomFile = File.createTempFile("mvninstall", ".pom");

writer = new XmlStreamWriter(pomFile);
new MavenXpp3Writer().write(writer, model);
writer.close();
writer = null;
File tempPomFile = File.createTempFile("mvninstall", ".pom");

return pomFile;
try (OutputStream writer = Files.newOutputStream(tempPomFile.toPath())) {
new MavenXpp3Writer().write(writer, model);
return tempPomFile;
}
} catch (IOException e) {
throw new MojoExecutionException("Error writing temporary POM file: " + e.getMessage(), e);
} finally {
IOUtil.close(writer);
}
}

Expand Down
41 changes: 16 additions & 25 deletions src/main/java/org/apache/maven/plugins/install/InstallMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@
package org.apache.maven.plugins.install;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.maven.RepositoryUtils;
import org.apache.maven.execution.MavenSession;
Expand Down Expand Up @@ -122,15 +123,15 @@ public void execute() throws MojoExecutionException {
getLog().info("Skipping artifact installation");
putState(State.SKIPPED);
} else {
if (!installAtEnd) {
if (installAtEnd) {
getLog().info("Deferring install for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ project.getVersion() + " at end");
putState(State.TO_BE_INSTALLED);
} else {
InstallRequest request = new InstallRequest();
processProject(project, request);
installProject(request);
putState(State.INSTALLED);
} else {
getLog().info("Deferring install for " + project.getGroupId() + ":" + project.getArtifactId() + ":"
+ project.getVersion() + " at end");
putState(State.TO_BE_INSTALLED);
}
}

Expand All @@ -149,35 +150,25 @@ public void execute() throws MojoExecutionException {
}

private boolean allProjectsMarked(List<MavenProject> allProjectsUsingPlugin) {
for (MavenProject reactorProject : allProjectsUsingPlugin) {
if (!hasState(reactorProject)) {
return false;
}
}
return true;
return allProjectsUsingPlugin.stream().allMatch(this::hasState);
}

private final Predicate<MavenProject> hasMavenInstallPluginExecution =
rp -> hasExecution(rp.getPlugin("org.apache.maven.plugins:maven-install-plugin"));

private List<MavenProject> getAllProjectsUsingPlugin() {
ArrayList<MavenProject> result = new ArrayList<>();
for (MavenProject reactorProject : reactorProjects) {
if (hasExecution(reactorProject.getPlugin("org.apache.maven.plugins:maven-install-plugin"))) {
result.add(reactorProject);
}
}
return result;
return reactorProjects.stream().filter(hasMavenInstallPluginExecution).collect(Collectors.toList());
}

private final Predicate<PluginExecution> havingGoals = pe -> !pe.getGoals().isEmpty();
private final Predicate<PluginExecution> nonePhase = pe -> !"none".equalsIgnoreCase(pe.getPhase());

private boolean hasExecution(Plugin plugin) {
if (plugin == null) {
return false;
}

for (PluginExecution execution : plugin.getExecutions()) {
if (!execution.getGoals().isEmpty() && !"none".equalsIgnoreCase(execution.getPhase())) {
return true;
}
}
return false;
return plugin.getExecutions().stream().filter(havingGoals).anyMatch(nonePhase);
}

private void installProject(InstallRequest request) throws MojoExecutionException {
Expand Down

0 comments on commit 30d2b53

Please sign in to comment.