From 4dd64923672680fecd599ae8ec379b0995aab762 Mon Sep 17 00:00:00 2001 From: Olivier Lamy Date: Sat, 14 Aug 2021 15:04:02 +1000 Subject: [PATCH] java 1.8 mandatory amd some codebase update Signed-off-by: Olivier Lamy --- mrm-api/pom.xml | 4 +- .../codehaus/mojo/mrm/api/AbstractEntry.java | 14 +- .../codehaus/mojo/mrm/api/BaseFileSystem.java | 6 +- .../codehaus/mojo/mrm/api/maven/Artifact.java | 19 +- .../mojo/mrm/plugin/FactoryHelper.java | 4 +- mrm-maven-plugin/pom.xml | 4 +- .../mojo/mrm/maven/ProxyArtifactStore.java | 110 +++-------- .../mojo/mrm/plugin/AbstractStartMojo.java | 4 +- .../mojo/mrm/plugin/FileSystemServer.java | 68 ++----- mrm-servlet/pom.xml | 4 +- .../mojo/mrm/impl/CompositeFileSystem.java | 28 ++- .../mojo/mrm/impl/DiskFileSystem.java | 5 +- .../mojo/mrm/impl/MemoryFileSystem.java | 37 +--- .../org/codehaus/mojo/mrm/impl/Utils.java | 82 ++++---- .../mrm/impl/digest/AutoDigestFileSystem.java | 19 +- .../mrm/impl/digest/MD5DigestFileEntry.java | 20 +- .../mrm/impl/digest/SHA1DigestFileEntry.java | 28 +-- .../impl/maven/ArchetypeCatalogFileEntry.java | 9 +- .../mrm/impl/maven/ArtifactFileEntry.java | 12 +- .../impl/maven/ArtifactStoreFileSystem.java | 43 +--- .../impl/maven/CompositeArtifactStore.java | 187 ++++++++---------- .../mrm/impl/maven/DiskArtifactStore.java | 128 +++++------- .../impl/maven/FileSystemArtifactStore.java | 86 +++----- .../mrm/impl/maven/MemoryArtifactStore.java | 84 +++----- .../mrm/impl/maven/MetadataFileEntry.java | 8 +- .../mrm/impl/maven/MockArtifactStore.java | 87 +++----- .../codehaus/mojo/mrm/plugin/HostedRepo.java | 5 +- .../codehaus/mojo/mrm/plugin/LocalRepo.java | 5 +- .../codehaus/mojo/mrm/plugin/MockRepo.java | 5 +- .../mojo/mrm/servlet/FileSystemServlet.java | 71 +++---- mrm-webapp/pom.xml | 4 +- pom.xml | 8 +- 32 files changed, 405 insertions(+), 793 deletions(-) diff --git a/mrm-api/pom.xml b/mrm-api/pom.xml index c7aa014c..5b1ac28a 100644 --- a/mrm-api/pom.xml +++ b/mrm-api/pom.xml @@ -22,12 +22,12 @@ org.codehaus.mojo mrm - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT mrm-api - Mock Repository Manager: API + Mock Repository Manager :: API diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/AbstractEntry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/AbstractEntry.java index 8b044f8a..5a64af2c 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/AbstractEntry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/AbstractEntry.java @@ -16,6 +16,7 @@ package org.codehaus.mojo.mrm.api; +import java.util.Objects; import java.util.Stack; /** @@ -119,12 +120,7 @@ public boolean equals( Object o ) { return false; } - if ( parent != null ? !parent.equals( abstractEntry.parent ) : abstractEntry.parent != null ) - { - return false; - } - - return true; + return Objects.equals(parent, abstractEntry.parent); } /** @@ -154,7 +150,7 @@ public String toString() */ public final String toPath() { - Stack stack = new Stack(); + Stack stack = new Stack<>(); Entry root = getFileSystem().getRoot(); Entry entry = this; do @@ -163,8 +159,8 @@ public final String toPath() entry = entry.getParent(); } while ( entry != null && !root.equals( entry ) ); - - StringBuffer buf = new StringBuffer(); + + StringBuilder buf = new StringBuilder(); while ( stack.size() > 1 ) { buf.append( stack.pop() ); diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileSystem.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileSystem.java index 09016e8b..921cdf78 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileSystem.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileSystem.java @@ -89,11 +89,11 @@ protected Entry get( DirectoryEntry parent, String name ) Entry[] entries = listEntries( parent ); if ( entries != null ) { - for ( int i = 0; i < entries.length; i++ ) + for (Entry entry : entries) { - if ( name.equals( entries[i].getName() ) ) + if (name.equals(entry.getName())) { - return entries[i]; + return entry; } } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/Artifact.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/Artifact.java index 54d20a84..bd480487 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/Artifact.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/Artifact.java @@ -20,6 +20,7 @@ import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Objects; import java.util.TimeZone; /** @@ -122,14 +123,6 @@ public final class Artifact private Artifact( String groupId, String artifactId, String version, String classifier, String type, Long timestamp, Integer buildNumber ) { - groupId.getClass(); - artifactId.getClass(); - version.getClass(); - type.getClass(); - if ( timestamp != null ) - { - buildNumber.getClass(); - } this.groupId = groupId; this.artifactId = artifactId; this.version = version; @@ -154,7 +147,7 @@ private Artifact( String groupId, String artifactId, String version, String clas public Artifact( String groupId, String artifactId, String version, String classifier, String type, long timestamp, int buildNumber ) { - this( groupId, artifactId, version, classifier, type, new Long( timestamp ), new Integer( buildNumber ) ); + this( groupId, artifactId, version, classifier, type, Long.valueOf( timestamp ), Integer.valueOf( buildNumber ) ); } /** @@ -393,15 +386,15 @@ public boolean equals( Object o ) { return false; } - if ( classifier != null ? !classifier.equals( artifact.classifier ) : artifact.classifier != null ) + if (!Objects.equals(classifier, artifact.classifier)) { return false; } - if ( buildNumber != null ? !buildNumber.equals( artifact.buildNumber ) : artifact.buildNumber != null ) + if (!Objects.equals(buildNumber, artifact.buildNumber)) { return false; } - if ( timestamp != null ? !timestamp.equals( artifact.timestamp ) : artifact.timestamp != null ) + if (!Objects.equals(timestamp, artifact.timestamp)) { return false; } @@ -440,7 +433,7 @@ public boolean equalSnapshots( Artifact artifact ) { return false; } - if ( classifier != null ? !classifier.equals( artifact.classifier ) : artifact.classifier != null ) + if (!Objects.equals(classifier, artifact.classifier)) { return false; } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelper.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelper.java index 98798f14..ff6449a7 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelper.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelper.java @@ -90,9 +90,9 @@ public interface FactoryHelper Log getLog(); /** - * Returns the {@ ArchetypeManager} + * Returns the {@link ArchetypeManager} * - * @return The {@ ArchetypeManager} + * @return The {@link ArchetypeManager} * @since 1.0 */ ArchetypeManager getArchetypeManager(); diff --git a/mrm-maven-plugin/pom.xml b/mrm-maven-plugin/pom.xml index 074d7808..ca5c8f9a 100644 --- a/mrm-maven-plugin/pom.xml +++ b/mrm-maven-plugin/pom.xml @@ -22,13 +22,13 @@ org.codehaus.mojo mrm - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT mrm-maven-plugin maven-plugin - Mock Repository Manager: Maven Plugin + Mock Repository Manager :: Maven Plugin ${mavenVersion} diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStore.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStore.java index 03652b38..840b6b36 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStore.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStore.java @@ -47,10 +47,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; /** * An {@link org.codehaus.mojo.mrm.api.maven.ArtifactStore} that serves content from a running Maven instance. @@ -104,7 +105,7 @@ public class ProxyArtifactStore /** * A cache of what artifacts are present. */ - private final Map> children = new HashMap>(); + private final Map> children = new HashMap<>(); /** * Creates a new instance. @@ -129,7 +130,7 @@ public ProxyArtifactStore( RepositoryMetadataManager repositoryMetadataManager, this.artifactResolver = artifactResolver; this.archetypeManager = archetypeManager; this.log = log; - remoteRepositories = new ArrayList(); + remoteRepositories = new ArrayList<>(); remoteRepositories.addAll( remoteArtifactRepositories ); remoteRepositories.addAll( remotePluginRepositories ); try @@ -139,10 +140,7 @@ public ProxyArtifactStore( RepositoryMetadataManager repositoryMetadataManager, catch ( InvalidVersionSpecificationException e ) { // must never happen... so if it does make sure we stop - IllegalStateException ise = - new IllegalStateException( "[0,] should always be a valid version specification" ); - ise.initCause( e ); - throw ise; + throw new IllegalStateException( "[0,] should always be a valid version specification", e ); } } @@ -155,12 +153,7 @@ private synchronized void addResolved( Artifact artifact ) { String path = artifact.getGroupId().replace( '.', '/' ) + '/' + artifact.getArtifactId() + "/" + artifact.getVersion(); - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { - artifactMapper = new HashMap(); - this.children.put( path, artifactMapper ); - } + Map artifactMapper = this.children.computeIfAbsent(path, k -> new HashMap<>()); artifactMapper.put( artifact.getName(), artifact ); addResolved( path ); } @@ -176,22 +169,12 @@ private synchronized void addResolved( String path ) { String name = path.substring( index + 1 ); path = path.substring( 0, index ); - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { - artifactMapper = new HashMap(); - this.children.put( path, artifactMapper ); - } + Map artifactMapper = this.children.computeIfAbsent(path, k -> new HashMap<>()); artifactMapper.put( name, null ); } if ( !StringUtils.isEmpty( path ) ) { - Map artifactMapper = this.children.get( "" ); - if ( artifactMapper == null ) - { - artifactMapper = new HashMap(); - this.children.put( "", artifactMapper ); - } + Map artifactMapper = this.children.computeIfAbsent("", k -> new HashMap<>()); artifactMapper.put( path, null ); } } @@ -207,15 +190,9 @@ public synchronized Set getGroupIds( String parentGroupId ) { return Collections.emptySet(); } - Set result = new HashSet(); - for ( Map.Entry e : artifactMapper.entrySet() ) - { - if ( e.getValue() == null ) - { - result.add( e.getKey() ); - } - } - return result; + return artifactMapper.entrySet().stream().filter( entry -> entry.getValue() == null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** @@ -229,15 +206,9 @@ public synchronized Set getArtifactIds( String groupId ) { return Collections.emptySet(); } - Set result = new HashSet(); - for ( Map.Entry e : artifactMapper.entrySet() ) - { - if ( e.getValue() == null ) - { - result.add( e.getKey() ); - } - } - return result; + return artifactMapper.entrySet().stream().filter(entry -> entry.getValue()==null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** @@ -251,15 +222,9 @@ public synchronized Set getVersions( String groupId, String artifactId ) { return Collections.emptySet(); } - Set result = new HashSet(); - for ( Map.Entry e : artifactMapper.entrySet() ) - { - if ( e.getValue() == null ) - { - result.add( e.getKey() ); - } - } - return result; + return artifactMapper.entrySet().stream().filter(entry -> entry.getValue()==null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** @@ -273,15 +238,9 @@ public synchronized Set getArtifacts( String groupId, String artifactI { return Collections.emptySet(); } - Set result = new HashSet(); - for ( Artifact a : artifactMapper.values() ) - { - if ( a != null ) - { - result.add( a ); - } - } - return result; + return artifactMapper.values().stream().filter(Objects::nonNull) + .collect( Collectors.toSet() ); + } /** @@ -307,15 +266,11 @@ public long getLastModified( Artifact artifact ) } catch ( org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) { - ArtifactNotFoundException anfe = new ArtifactNotFoundException( artifact ); - anfe.initCause( e ); - throw anfe; + throw new ArtifactNotFoundException( artifact , e ); } catch ( ArtifactResolutionException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; + throw new IOException( e.getMessage(), e ); } } @@ -346,9 +301,7 @@ public long getSize( Artifact artifact ) } catch ( ArtifactResolutionException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; + throw new IOException( e.getMessage(), e ); } } @@ -376,15 +329,11 @@ public InputStream get( Artifact artifact ) catch ( org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) { ArtifactNotFoundException anfe = new ArtifactNotFoundException( artifact, e ); -// Causes a java.lang.IllegalStateException: Can't overwrite cause -// anfe.initCause( e ); throw anfe; } catch ( ArtifactResolutionException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; + throw new IOException( e.getMessage(), e ); } } @@ -419,17 +368,16 @@ public Metadata getMetadata( String path ) if ( version != null && version.endsWith( "-SNAPSHOT" ) && !StringUtils.isEmpty( artifactId ) && !StringUtils.isEmpty( groupId ) ) { - final org.apache.maven.artifact.Artifact artifact = + org.apache.maven.artifact.Artifact artifact = artifactFactory.createDependencyArtifact( groupId, artifactId, VersionRange.createFromVersion( version ), "pom", null, "compile" ); - final SnapshotArtifactRepositoryMetadata artifactRepositoryMetadata = - new SnapshotArtifactRepositoryMetadata( artifact ); + SnapshotArtifactRepositoryMetadata artifactRepositoryMetadata = new SnapshotArtifactRepositoryMetadata( artifact ); try { repositoryMetadataManager.resolve( artifactRepositoryMetadata, remoteRepositories, localRepository ); - final Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata(); + Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata(); if ( artifactMetadata.getVersioning() != null && artifactMetadata.getVersioning().getSnapshot() != null ) { @@ -472,9 +420,9 @@ public Metadata getMetadata( String path ) groupId = index == -1 ? null : path.substring( 0, index ).replace( '/', '.' ); if ( !StringUtils.isEmpty( artifactId ) && !StringUtils.isEmpty( groupId ) ) { - final org.apache.maven.artifact.Artifact artifact = + org.apache.maven.artifact.Artifact artifact = artifactFactory.createDependencyArtifact( groupId, artifactId, anyVersion, "pom", null, "compile" ); - final ArtifactRepositoryMetadata artifactRepositoryMetadata = new ArtifactRepositoryMetadata( artifact ); + ArtifactRepositoryMetadata artifactRepositoryMetadata = new ArtifactRepositoryMetadata( artifact ); try { repositoryMetadataManager.resolve( artifactRepositoryMetadata, remoteRepositories, localRepository ); diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractStartMojo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractStartMojo.java index ba185e7e..6759fdd3 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractStartMojo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractStartMojo.java @@ -89,7 +89,7 @@ protected ArtifactStore createArtifactStore() return createProxyArtifactStore(); } getLog().info( "Configuring Mock Repository Manager..." ); - List stores = new ArrayList(); + List stores = new ArrayList<>(); if ( repositories == null || repositories.length == 0 ) { repositories = new ArtifactStoreFactory[]{ new ProxyRepo() }; @@ -104,7 +104,7 @@ protected ArtifactStore createArtifactStore() getLog().info( " " + artifactStoreFactory.toString() ); stores.add( artifactStoreFactory.newInstance() ); } - ArtifactStore[] artifactStores = (ArtifactStore[]) stores.toArray( new ArtifactStore[stores.size()] ); + ArtifactStore[] artifactStores = stores.toArray(new ArtifactStore[0]); return artifactStores.length == 1 ? artifactStores[0] : new CompositeArtifactStore( artifactStores ); } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemServer.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemServer.java index 45bd79da..2a757710 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemServer.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemServer.java @@ -24,7 +24,6 @@ import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; -import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; @@ -260,22 +259,17 @@ private final class Worker */ public void run() { - try - { - Server server = new Server( requestedPort ); - try - { - Context root = new Context( server, "/", Context.SESSIONS ); - root.addServlet( new ServletHolder( new FileSystemServlet( fileSystem, settingsServletPath ) ), "/*" ); + try { + Server server = new Server(requestedPort); + try { + Context root = new Context(server, "/", Context.SESSIONS); + root.addServlet(new ServletHolder(new FileSystemServlet(fileSystem, settingsServletPath)), "/*"); server.start(); - synchronized ( lock ) - { + synchronized (lock) { boundPort = 0; Connector[] connectors = server.getConnectors(); - for ( int i = 0; i < connectors.length; i++ ) - { - if ( connectors[i].getLocalPort() > 0 ) - { + for (int i = 0; i < connectors.length; i++) { + if (connectors[i].getLocalPort() > 0) { boundPort = connectors[i].getLocalPort(); break; } @@ -284,41 +278,17 @@ public void run() started = true; lock.notifyAll(); } - } - catch ( IOException e ) - { - synchronized ( lock ) - { - problem = e; - } - throw e; - } - catch ( InterruptedException e ) - { - synchronized ( lock ) - { + } catch (Exception e) { + synchronized (lock) { problem = e; } throw e; } - catch ( Exception e ) - { - synchronized ( lock ) - { - problem = e; - } - throw e; - } - synchronized ( lock ) - { - while ( !finishing ) - { - try - { - lock.wait( 500 ); - } - catch ( InterruptedException e ) - { + synchronized (lock) { + while (!finishing) { + try { + lock.wait(500); + } catch (InterruptedException e) { // ignore } } @@ -326,14 +296,6 @@ public void run() server.stop(); server.join(); } - catch ( IOException e ) - { - // ignore - } - catch ( InterruptedException e ) - { - // ignore - } catch ( Exception e ) { // ignore diff --git a/mrm-servlet/pom.xml b/mrm-servlet/pom.xml index 12ed7e62..c532fa51 100644 --- a/mrm-servlet/pom.xml +++ b/mrm-servlet/pom.xml @@ -22,12 +22,12 @@ org.codehaus.mojo mrm - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT mrm-servlet - Mock Repository Manager: Servlet + Mock Repository Manager :: Servlet diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/CompositeFileSystem.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/CompositeFileSystem.java index b6fc6a37..796750bc 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/CompositeFileSystem.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/CompositeFileSystem.java @@ -24,7 +24,9 @@ import java.io.IOException; import java.io.InputStream; +import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; /** @@ -65,7 +67,6 @@ public class CompositeFileSystem */ public CompositeFileSystem( FileSystem[] delegates ) { - delegates.getClass(); this.delegates = delegates; } @@ -74,7 +75,7 @@ public CompositeFileSystem( FileSystem[] delegates ) */ public Entry[] listEntries( DirectoryEntry directory ) { - Map result = new TreeMap(); + Map result = new TreeMap<>(); for ( FileSystem delegate : delegates ) { Entry[] entries = delegate.listEntries( DefaultDirectoryEntry.equivalent( delegate, directory ) ); @@ -99,7 +100,7 @@ else if ( entry instanceof FileEntry ) } } } - return (Entry[]) result.values().toArray( new Entry[result.size()] ); + return result.values().toArray(new Entry[0]); } /** @@ -107,20 +108,13 @@ else if ( entry instanceof FileEntry ) */ public Entry get( String path ) { - for ( FileSystem delegate : delegates ) - { - Entry entry = delegate.get( path ); - if ( entry == null ) - { - continue; - } - if ( entry instanceof DirectoryEntry ) - { - return DefaultDirectoryEntry.equivalent( this, (DirectoryEntry) entry ); - } - return entry; - } - return null; + return Arrays.stream(delegates).map(fileSystem -> fileSystem.get(path)) + .filter(Objects::nonNull) + .filter(entry -> entry instanceof DirectoryEntry) + .map(entry -> DefaultDirectoryEntry.equivalent( this, (DirectoryEntry) entry )) + .findFirst() + .orElse(null); + } /** diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileSystem.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileSystem.java index ed822c45..ced54919 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileSystem.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileSystem.java @@ -86,6 +86,7 @@ public Entry[] listEntries( DirectoryEntry directory ) return null; } File[] files = file.listFiles(); + Entry[] result = new Entry[files.length]; for ( int i = 0; i < files.length; i++ ) { @@ -119,7 +120,7 @@ public long getLastModified( DirectoryEntry entry ) */ private File toFile( Entry entry ) { - Stack stack = new Stack(); + Stack stack = new Stack<>(); Entry entryRoot = entry.getFileSystem().getRoot(); while ( entry != null && !entryRoot.equals( entry ) ) { @@ -140,7 +141,7 @@ else if ( !".".equals( name ) ) File file = this.root; while ( !stack.empty() ) { - file = new File( file, (String) stack.pop() ); + file = new File( file, stack.pop() ); } return file; } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileSystem.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileSystem.java index d9e7d0ac..b32792e1 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileSystem.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileSystem.java @@ -45,7 +45,7 @@ public class MemoryFileSystem * * @since 1.0 */ - private final Map> contents = new HashMap>(); + private final Map> contents = new HashMap<>(); /** * Create a new empty file system. @@ -54,7 +54,7 @@ public class MemoryFileSystem */ public MemoryFileSystem() { - contents.put( getRoot(), new ArrayList() ); + contents.put( getRoot(), new ArrayList<>() ); } /** @@ -67,7 +67,7 @@ public synchronized Entry[] listEntries( DirectoryEntry directory ) { return null; } - return entries.toArray( new Entry[entries.size()] ); + return entries.toArray(new Entry[0]); } /** @@ -85,6 +85,7 @@ public long getLastModified( DirectoryEntry directoryEntry ) lastModified = Math.max( lastModified, entry.getLastModified() ); } } + return lastModified; } @@ -93,20 +94,10 @@ public long getLastModified( DirectoryEntry directoryEntry ) */ protected synchronized Entry get( DirectoryEntry parent, String name ) { - parent.getClass(); List parentEntries = contents.get( parent ); - if ( parentEntries == null ) - { - return null; - } - for ( Entry entry : parentEntries ) - { - if ( name.equals( entry.getName() ) ) - { - return entry; - } - } - return null; + return parentEntries == null ? null : + parentEntries.stream().filter(entry -> name.equals(entry.getName())).findFirst().orElse(null); + } /** @@ -114,7 +105,6 @@ protected synchronized Entry get( DirectoryEntry parent, String name ) */ public synchronized DirectoryEntry mkdir( DirectoryEntry parent, String name ) { - parent.getClass(); parent = getNormalizedParent( parent ); List entries = getEntriesList( parent ); for ( Entry entry : entries ) @@ -139,12 +129,11 @@ public synchronized DirectoryEntry mkdir( DirectoryEntry parent, String name ) public synchronized FileEntry put( DirectoryEntry parent, String name, InputStream content ) throws IOException { - parent.getClass(); parent = getNormalizedParent( parent ); List entries = getEntriesList( parent ); for ( Iterator i = entries.iterator(); i.hasNext(); ) { - Entry entry = (Entry) i.next(); + Entry entry = i.next(); if ( name.equals( entry.getName() ) ) { if ( entry instanceof FileEntry ) @@ -190,13 +179,7 @@ private DirectoryEntry getNormalizedParent( DirectoryEntry parent ) */ private synchronized List getEntriesList( DirectoryEntry directory ) { - List entries = contents.get( directory ); - if ( entries == null ) - { - entries = new ArrayList(); - contents.put( directory, entries ); - } - return entries; + return contents.computeIfAbsent(directory, k -> new ArrayList<>()); } /** @@ -224,7 +207,7 @@ public synchronized void remove( Entry entry ) } for ( Iterator i = entries.iterator(); i.hasNext(); ) { - Entry e = (Entry) i.next(); + Entry e = i.next(); if ( entry.equals( e ) ) { if ( e instanceof DirectoryEntry ) diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/Utils.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/Utils.java index 6fc53ebd..531e7a1f 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/Utils.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/Utils.java @@ -25,6 +25,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; @@ -70,7 +71,7 @@ else if ( content instanceof File ) } else { - return new ByteArrayInputStream( content.toString().getBytes( "UTF-8" ) ); + return new ByteArrayInputStream( content.toString().getBytes(StandardCharsets.UTF_8) ); } } @@ -85,16 +86,16 @@ public static byte[] newEmptyJarContent() throws IOException { byte[] emptyJar; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final Manifest manifest = new Manifest(); - manifest.getMainAttributes().putValue( "Manifest-Version", "1.0" ); - manifest.getMainAttributes().putValue( "Archiver-Version", "1.0" ); - manifest.getMainAttributes().putValue( "Created-By", "Mock Repository Maven Plugin" ); - JarOutputStream jos = new JarOutputStream( bos, manifest ); - jos.close(); - bos.close(); - emptyJar = bos.toByteArray(); - return emptyJar; + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + final Manifest manifest = new Manifest(); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + manifest.getMainAttributes().putValue("Archiver-Version", "1.0"); + manifest.getMainAttributes().putValue("Created-By", "Mock Repository Maven Plugin"); + try (JarOutputStream jos = new JarOutputStream(bos, manifest)) { + emptyJar = bos.toByteArray(); + return emptyJar; + } + } } /** @@ -111,22 +112,22 @@ public static byte[] newEmptyMavenPluginJarContent( String groupId, String artif throws IOException { byte[] emptyJar; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final Manifest manifest = new Manifest(); - manifest.getMainAttributes().putValue( "Manifest-Version", "1.0" ); - manifest.getMainAttributes().putValue( "Archiver-Version", "1.0" ); - manifest.getMainAttributes().putValue( "Created-By", "Mock Repository Maven Plugin" ); - JarOutputStream jos = new JarOutputStream( bos, manifest ); - JarEntry entry = new JarEntry( "META-INF/maven/plugin.xml" ); - jos.putNextEntry( entry ); - jos.write( - ( "" + groupId + "" + artifactId + "" + version - + "" ).getBytes() ); - jos.closeEntry(); - jos.close(); - bos.close(); - emptyJar = bos.toByteArray(); - return emptyJar; + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + final Manifest manifest = new Manifest(); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + manifest.getMainAttributes().putValue("Archiver-Version", "1.0"); + manifest.getMainAttributes().putValue("Created-By", "Mock Repository Maven Plugin"); + try (JarOutputStream jos = new JarOutputStream(bos, manifest)) { + JarEntry entry = new JarEntry("META-INF/maven/plugin.xml"); + jos.putNextEntry(entry); + jos.write( + ("" + groupId + "" + artifactId + "" + version + + "").getBytes()); + jos.closeEntry(); + emptyJar = bos.toByteArray(); + return emptyJar; + } + } } /** @@ -220,12 +221,12 @@ public static String getGroupId( Model model ) public static String urlEncodePath( String path ) throws UnsupportedEncodingException { - StringBuffer buf = new StringBuffer( path.length() + 64 ); + StringBuilder buf = new StringBuilder( path.length() + 64 ); int last = 0; for ( int i = path.indexOf( '/' ); i != -1; i = path.indexOf( '/', last ) ) { buf.append( urlEncodePathSegment( path.substring( last, i ) ) ); - buf.append( path.substring( i, Math.min( path.length(), i + 1 ) ) ); + buf.append(path, i, Math.min( path.length(), i + 1 )); last = i + 1; } buf.append( path.substring( last ) ); @@ -243,12 +244,10 @@ public static String urlEncodePath( String path ) public static String urlEncodePathSegment( String pathSegment ) throws UnsupportedEncodingException { - StringBuffer buf = new StringBuffer( pathSegment.length() + 64 ); - byte[] chars = pathSegment.getBytes( "UTF-8" ); - for ( int i = 0; i < chars.length; i++ ) - { - switch ( chars[i] ) - { + StringBuilder buf = new StringBuilder( pathSegment.length() + 64 ); + byte[] chars = pathSegment.getBytes(StandardCharsets.UTF_8); + for (byte aChar : chars) { + switch (aChar) { case '$': case '-': case '_': @@ -321,18 +320,17 @@ public static String urlEncodePathSegment( String pathSegment ) case 'x': case 'y': case 'z': - buf.append( (char) chars[i] ); + buf.append((char) aChar); break; case ' ': - buf.append( '+' ); + buf.append('+'); break; default: - buf.append( '%' ); - if ( ( chars[i] & 0xf0 ) == 0 ) - { - buf.append( '0' ); + buf.append('%'); + if ((aChar & 0xf0) == 0) { + buf.append('0'); } - buf.append( Integer.toHexString( chars[i] & 0xff ) ); + buf.append(Integer.toHexString(aChar & 0xff)); break; } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/AutoDigestFileSystem.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/AutoDigestFileSystem.java index 416241fb..752c95fe 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/AutoDigestFileSystem.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/AutoDigestFileSystem.java @@ -18,12 +18,14 @@ import java.io.IOException; import java.io.InputStream; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.codehaus.mojo.mrm.api.BaseFileSystem; @@ -82,12 +84,9 @@ public AutoDigestFileSystem( FileSystem backing ) public AutoDigestFileSystem( FileSystem backing, DigestFileEntryFactory[] digestFactories ) { this.backing = backing; - Map map = new HashMap( digestFactories.length ); - for ( DigestFileEntryFactory factory : digestFactories ) - { - map.put( factory.getType(), factory ); - } - this.digestFactories = Collections.unmodifiableMap( map ); + this.digestFactories = + Collections.unmodifiableMap(Arrays.stream(digestFactories) + .collect(Collectors.toMap(DigestFileEntryFactory::getType, factory -> factory))); } /** @@ -95,9 +94,9 @@ public AutoDigestFileSystem( FileSystem backing, DigestFileEntryFactory[] digest */ public Entry[] listEntries( DirectoryEntry directory ) { - Map result = new TreeMap(); - Map missing = new HashMap(); - Set present = new HashSet(); + Map result = new TreeMap<>(); + Map missing = new HashMap<>(); + Set present = new HashSet<>(); Entry[] entries = backing.listEntries( DefaultDirectoryEntry.equivalent( backing, directory ) ); for ( Entry entry : entries ) { @@ -135,7 +134,7 @@ else if ( entry instanceof DirectoryEntry ) } } } - return result.values().toArray( new Entry[result.size()] ); + return result.values().toArray(new Entry[0]); } /** diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java index 27f92f3e..23cf4218 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/MD5DigestFileEntry.java @@ -16,7 +16,6 @@ package org.codehaus.mojo.mrm.impl.digest; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.mojo.mrm.api.BaseFileEntry; import org.codehaus.mojo.mrm.api.DirectoryEntry; @@ -103,40 +102,25 @@ public InputStream getInputStream() private byte[] getContent() throws IOException { - InputStream is = null; try { MessageDigest digest = MessageDigest.getInstance( "MD5" ); digest.reset(); byte[] buffer = new byte[8192]; int read; - try + try (InputStream is = entry.getInputStream()) { - is = entry.getInputStream(); while ( ( read = is.read( buffer ) ) > 0 ) { digest.update( buffer, 0, read ); } } - catch ( IOException e ) - { - if ( is != null ) - { - throw e; - } - } final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" ); return md5.getBytes(); } catch ( NoSuchAlgorithmException e ) { - IOException ioe = new IOException( "Unable to calculate hash" ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( is ); + throw new IOException( "Unable to calculate hash", e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/SHA1DigestFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/SHA1DigestFileEntry.java index fd6549e3..51374e78 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/SHA1DigestFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/SHA1DigestFileEntry.java @@ -105,40 +105,22 @@ public InputStream getInputStream() private byte[] getContent() throws IOException { - InputStream is = null; - try + try (InputStream is = entry.getInputStream()) { MessageDigest digest = MessageDigest.getInstance( "SHA1" ); digest.reset(); byte[] buffer = new byte[8192]; int read; - try + while ( ( read = is.read( buffer ) ) > 0 ) { - is = entry.getInputStream(); - while ( ( read = is.read( buffer ) ) > 0 ) - { - digest.update( buffer, 0, read ); - } + digest.update( buffer, 0, read ); } - catch ( IOException e ) - { - if ( is != null ) - { - throw e; - } - } - final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 40, "0" ); + String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 40, "0" ); return md5.getBytes(); } catch ( NoSuchAlgorithmException e ) { - IOException ioe = new IOException( "Unable to calculate hash" ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( is ); + throw new IOException( "Unable to calculate hash", e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntry.java index ef7c366f..8d9b5813 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntry.java @@ -59,7 +59,6 @@ public class ArchetypeCatalogFileEntry * * @param fileSystem the file system. * @param parent the parent directory. - * @param path the path of the metadata. * @param store the artifact store. * @since 1.0 */ @@ -85,9 +84,7 @@ public long getSize() } catch ( ArchetypeCatalogNotFoundException e ) { - IOException ioe = new IOException( "File not found" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "File not found", e); } } @@ -123,9 +120,7 @@ public long getLastModified() } catch ( ArchetypeCatalogNotFoundException e ) { - IOException ioe = new IOException( "File not found" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "File not found", e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactFileEntry.java index fbd38fdb..de62649c 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactFileEntry.java @@ -86,9 +86,7 @@ public long getSize() } catch ( ArtifactNotFoundException e ) { - IOException ioe = new IOException( "Artifact does not exist" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "Artifact does not exist", e); } } @@ -104,9 +102,7 @@ public InputStream getInputStream() } catch ( ArtifactNotFoundException e ) { - IOException ioe = new IOException( "Artifact does not exist" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "Artifact does not exist", e); } } @@ -122,9 +118,7 @@ public long getLastModified() } catch ( ArtifactNotFoundException e ) { - IOException ioe = new IOException( "Artifact does not exist" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "Artifact does not exist", e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystem.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystem.java index 6fab8d76..3cb88eaa 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystem.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystem.java @@ -20,7 +20,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; -import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashSet; @@ -134,7 +133,7 @@ public Entry[] listEntries( DirectoryEntry directory ) { if ( getRoot().equals( directory ) ) { - Set rootGroupIds = new TreeSet( store.getGroupIds( "" ) ); + Set rootGroupIds = new TreeSet<>( store.getGroupIds( "" ) ); Entry[] result = new Entry[rootGroupIds.size()]; int index = 0; for ( String name : rootGroupIds ) @@ -143,8 +142,8 @@ public Entry[] listEntries( DirectoryEntry directory ) } return result; } - List result = new ArrayList(); - Set names = new HashSet(); + List result = new ArrayList<>(); + Set names = new HashSet<>(); String path = directory.toPath(); try @@ -157,11 +156,7 @@ public Entry[] listEntries( DirectoryEntry directory ) names.add( entry.getName() ); } } - catch ( MetadataNotFoundException e ) - { - // ignore - } - catch ( IOException e ) + catch ( MetadataNotFoundException | IOException e ) { // ignore } @@ -170,7 +165,7 @@ public Entry[] listEntries( DirectoryEntry directory ) // get all the groupId's that start with this groupId String groupIdPrefix = groupId + "."; - Set groupIds = new TreeSet( store.getGroupIds( groupId ) ); + Set groupIds = new TreeSet<>( store.getGroupIds( groupId ) ); for ( String name : groupIds ) { if ( !names.contains( name ) ) @@ -224,14 +219,8 @@ public Entry[] listEntries( DirectoryEntry directory ) } // sort - Collections.sort( result, new Comparator() - { - public int compare( Entry o1, Entry o2 ) - { - return ( o1 ).getName().compareTo( ( o2 ).getName() ); - } - } ); - return result.toArray( new Entry[result.size()] ); + result.sort(Comparator.comparing(Entry::getName)); + return result.toArray(new Entry[0]); } /** @@ -313,11 +302,7 @@ else if ( ARCHETYPE_CATALOG.matcher( path ).matches() ) store.get( artifact ); return new ArtifactFileEntry( this, parent, artifact, store ); } - catch ( IOException e ) - { - return null; - } - catch ( ArtifactNotFoundException e ) + catch ( IOException | ArtifactNotFoundException e ) { return null; } @@ -343,11 +328,7 @@ else if ( ARCHETYPE_CATALOG.matcher( path ).matches() ) store.get( artifact ); return new ArtifactFileEntry( this, parent, artifact, store ); } - catch ( IOException e ) - { - return null; - } - catch ( ArtifactNotFoundException e ) + catch ( IOException | ArtifactNotFoundException e ) { return null; } @@ -382,11 +363,7 @@ else if ( ARCHETYPE_CATALOG.matcher( path ).matches() ) store.get( artifact ); return new ArtifactFileEntry( this, parent, artifact, store ); } - catch ( ArtifactNotFoundException e ) - { - return null; - } - catch ( IOException e ) + catch ( ArtifactNotFoundException | IOException e ) { return null; } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStore.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStore.java index d4a9b276..c46d65b4 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStore.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStore.java @@ -60,7 +60,6 @@ public class CompositeArtifactStore */ public CompositeArtifactStore( ArtifactStore[] stores ) { - stores.getClass(); this.stores = stores; } @@ -69,15 +68,16 @@ public CompositeArtifactStore( ArtifactStore[] stores ) */ public Set getGroupIds( String parentGroupId ) { - Set result = new TreeSet(); - for ( int i = 0; i < stores.length; i++ ) + Set result = new TreeSet<>(); + for (ArtifactStore store : stores) { - Set groupIds = stores[i].getGroupIds( parentGroupId ); - if ( groupIds != null ) + Set groupIds = store.getGroupIds(parentGroupId); + if (groupIds != null) { - result.addAll( groupIds ); + result.addAll(groupIds); } } + return result; } @@ -86,13 +86,13 @@ public Set getGroupIds( String parentGroupId ) */ public Set getArtifactIds( String groupId ) { - Set result = new TreeSet(); - for ( int i = 0; i < stores.length; i++ ) + Set result = new TreeSet<>(); + for (ArtifactStore store : stores) { - Set artifactIds = stores[i].getArtifactIds( groupId ); - if ( artifactIds != null ) + Set artifactIds = store.getArtifactIds(groupId); + if (artifactIds != null) { - result.addAll( artifactIds ); + result.addAll(artifactIds); } } return result; @@ -103,13 +103,13 @@ public Set getArtifactIds( String groupId ) */ public Set getVersions( String groupId, String artifactId ) { - Set result = new TreeSet(); - for ( int i = 0; i < stores.length; i++ ) + Set result = new TreeSet<>(); + for (ArtifactStore store : stores) { - Set versions = stores[i].getVersions( groupId, artifactId ); - if ( versions != null ) + Set versions = store.getVersions(groupId, artifactId); + if (versions != null) { - result.addAll( versions ); + result.addAll(versions); } } return result; @@ -120,13 +120,13 @@ public Set getVersions( String groupId, String artifactId ) */ public Set getArtifacts( String groupId, String artifactId, String version ) { - Set result = new TreeSet(); - for ( int i = 0; i < stores.length; i++ ) + Set result = new TreeSet<>(); + for (ArtifactStore store : stores) { - Set artifacts = stores[i].getArtifacts( groupId, artifactId, version ); - if ( artifacts != null ) + Set artifacts = store.getArtifacts(groupId, artifactId, version); + if (artifacts != null) { - result.addAll( artifacts ); + result.addAll(artifacts); } } return result; @@ -138,13 +138,13 @@ public Set getArtifacts( String groupId, String artifactId, String ver public long getLastModified( Artifact artifact ) throws IOException, ArtifactNotFoundException { - for ( int i = 0; i < stores.length; i++ ) + for (ArtifactStore store : stores) { try { - return stores[i].getLastModified( artifact ); + return store.getLastModified(artifact); } - catch ( ArtifactNotFoundException e ) + catch (ArtifactNotFoundException e) { // ignore } @@ -158,13 +158,12 @@ public long getLastModified( Artifact artifact ) public long getSize( Artifact artifact ) throws IOException, ArtifactNotFoundException { - for ( int i = 0; i < stores.length; i++ ) + for (ArtifactStore store : stores) { try { - return stores[i].getSize( artifact ); - } - catch ( ArtifactNotFoundException e ) + return store.getSize(artifact); + } catch (ArtifactNotFoundException e) { // ignore } @@ -178,14 +177,12 @@ public long getSize( Artifact artifact ) public InputStream get( Artifact artifact ) throws IOException, ArtifactNotFoundException { - for ( int i = 0; i < stores.length; i++ ) + for (ArtifactStore store : stores) { try { - return stores[i].get( artifact ); - } - catch ( ArtifactNotFoundException e ) - { + return store.get(artifact); + } catch (ArtifactNotFoundException e) { // ignore } } @@ -209,109 +206,92 @@ public Metadata getMetadata( String path ) { boolean found = false; Metadata result = new Metadata(); - Set pluginArtifactIds = new HashSet(); - Set snapshotVersions = new HashSet(); - for ( int i = 0; i < stores.length; i++ ) + Set pluginArtifactIds = new HashSet<>(); + Set snapshotVersions = new HashSet<>(); + for (ArtifactStore store : stores) { - try - { - Metadata partial = stores[i].getMetadata( path ); - if ( StringUtils.isEmpty( result.getArtifactId() ) && !StringUtils.isEmpty( partial.getArtifactId() ) ) + try { + Metadata partial = store.getMetadata(path); + if (StringUtils.isEmpty(result.getArtifactId()) && !StringUtils.isEmpty(partial.getArtifactId())) { - result.setArtifactId( partial.getArtifactId() ); + result.setArtifactId(partial.getArtifactId()); found = true; } - if ( StringUtils.isEmpty( result.getGroupId() ) && !StringUtils.isEmpty( partial.getGroupId() ) ) + if (StringUtils.isEmpty(result.getGroupId()) && !StringUtils.isEmpty(partial.getGroupId())) { - result.setGroupId( partial.getGroupId() ); + result.setGroupId(partial.getGroupId()); found = true; } - if ( StringUtils.isEmpty( result.getVersion() ) && !StringUtils.isEmpty( partial.getVersion() ) ) + if (StringUtils.isEmpty(result.getVersion()) && !StringUtils.isEmpty(partial.getVersion())) { - result.setVersion( partial.getVersion() ); + result.setVersion(partial.getVersion()); found = true; } - if ( partial.getPlugins() != null && !partial.getPlugins().isEmpty() ) + if (partial.getPlugins() != null && !partial.getPlugins().isEmpty()) { - for ( Plugin plugin : partial.getPlugins() ) + for (Plugin plugin : partial.getPlugins()) { - if ( !pluginArtifactIds.contains( plugin.getArtifactId() ) ) + if (!pluginArtifactIds.contains(plugin.getArtifactId())) { - result.addPlugin( plugin ); - pluginArtifactIds.add( plugin.getArtifactId() ); + result.addPlugin(plugin); + pluginArtifactIds.add(plugin.getArtifactId()); } } found = true; } - if ( partial.getVersioning() != null ) + if (partial.getVersioning() != null) { Versioning rVers = result.getVersioning(); - if ( rVers == null ) - { + if (rVers == null) { rVers = new Versioning(); } Versioning pVers = partial.getVersioning(); String rLU = found ? rVers.getLastUpdated() : null; String pLU = pVers.getLastUpdated(); - if ( pLU != null && ( rLU == null || rLU.compareTo( pLU ) < 0 ) ) - { + if (pLU != null && (rLU == null || rLU.compareTo(pLU) < 0)) { // partial is newer or only - if ( !StringUtils.isEmpty( pVers.getLatest() ) ) - { - rVers.setLatest( pVers.getLatest() ); + if (!StringUtils.isEmpty(pVers.getLatest())) { + rVers.setLatest(pVers.getLatest()); } - if ( !StringUtils.isEmpty( pVers.getRelease() ) ) - { - rVers.setLatest( pVers.getRelease() ); + if (!StringUtils.isEmpty(pVers.getRelease())) { + rVers.setLatest(pVers.getRelease()); } - rVers.setLastUpdated( pVers.getLastUpdated() ); + rVers.setLastUpdated(pVers.getLastUpdated()); } - for ( String version : pVers.getVersions() ) - { - if ( !rVers.getVersions().contains( version ) ) - { - rVers.addVersion( version ); + for (String version : pVers.getVersions()) { + if (!rVers.getVersions().contains(version)) { + rVers.addVersion(version); } } - if ( pVers.getSnapshot() != null ) - { - if ( rVers.getSnapshot() == null - || pVers.getSnapshot().getBuildNumber() > rVers.getSnapshot().getBuildNumber() ) - { + if (pVers.getSnapshot() != null) { + if (rVers.getSnapshot() == null + || pVers.getSnapshot().getBuildNumber() > rVers.getSnapshot().getBuildNumber()) { Snapshot snapshot = new Snapshot(); - snapshot.setBuildNumber( pVers.getSnapshot().getBuildNumber() ); - snapshot.setTimestamp( pVers.getSnapshot().getTimestamp() ); - rVers.setSnapshot( snapshot ); + snapshot.setBuildNumber(pVers.getSnapshot().getBuildNumber()); + snapshot.setTimestamp(pVers.getSnapshot().getTimestamp()); + rVers.setSnapshot(snapshot); } } - try - { - if ( pVers.getSnapshotVersions() != null && !pVers.getSnapshotVersions().isEmpty() ) - { - for ( SnapshotVersion snapshotVersion : pVers.getSnapshotVersions() ) - { + try { + if (pVers.getSnapshotVersions() != null && !pVers.getSnapshotVersions().isEmpty()) { + for (SnapshotVersion snapshotVersion : pVers.getSnapshotVersions()) { String key = snapshotVersion.getVersion() + "-" + snapshotVersion.getClassifier() + "." - + snapshotVersion.getExtension(); - if ( !snapshotVersions.contains( key ) ) - { - rVers.addSnapshotVersion( snapshotVersion ); - snapshotVersions.add( key ); + + snapshotVersion.getExtension(); + if (!snapshotVersions.contains(key)) { + rVers.addSnapshotVersion(snapshotVersion); + snapshotVersions.add(key); } } } - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // Maven 2 } - result.setVersioning( rVers ); + result.setVersioning(rVers); found = true; } - } - catch ( MetadataNotFoundException e ) - { + } catch (MetadataNotFoundException e) { // ignore } } @@ -330,22 +310,15 @@ public long getMetadataLastModified( String path ) { boolean found = false; long lastModified = 0; - for ( int i = 0; i < stores.length; i++ ) - { - try - { - if ( !found ) - { - lastModified = stores[i].getMetadataLastModified( path ); + for (ArtifactStore store : stores) { + try { + if (!found) { + lastModified = store.getMetadataLastModified(path); found = true; + } else { + lastModified = Math.max(lastModified, store.getMetadataLastModified(path)); } - else - { - lastModified = Math.max( lastModified, stores[i].getMetadataLastModified( path ) ); - } - } - catch ( MetadataNotFoundException e ) - { + } catch (MetadataNotFoundException e) { // ignore } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStore.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStore.java index ad096c57..dead9565 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStore.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStore.java @@ -18,10 +18,11 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; @@ -31,6 +32,7 @@ import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; @@ -92,15 +94,14 @@ public Set getGroupIds( String parentGroupId ) return Collections.emptySet(); } File[] groupDirs = parentDir.listFiles(); - Set result = new HashSet(); - for ( int i = 0; i < groupDirs.length; i++ ) + if(groupDirs==null) { - if ( groupDirs[i].isDirectory() ) - { - result.add( groupDirs[i].getName() ); - } + return Collections.emptySet(); } - return result; + return Arrays.stream(groupDirs).filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); + } /** @@ -113,18 +114,17 @@ public Set getArtifactIds( String groupId ) { return Collections.emptySet(); } - Set result = new HashSet(); + File[] artifactDirs = groupDir.listFiles(); - for ( int i = 0; i < artifactDirs.length; i++ ) + if (artifactDirs==null) { - if ( !artifactDirs[i].isDirectory() ) - { - continue; - } - final String artifactId = artifactDirs[i].getName(); - result.add( artifactId ); + return Collections.emptySet(); } - return result; + + return Arrays.stream(artifactDirs).filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); + } /** @@ -139,16 +139,14 @@ public Set getVersions( String groupId, String artifactId ) return Collections.emptySet(); } File[] dirs = artifactDir.listFiles(); - Set result = new HashSet(); - for ( int i = 0; i < dirs.length; i++ ) + if(dirs==null) { - if ( !dirs[i].isDirectory() ) - { - continue; - } - result.add( dirs[i].getName() ); + return Collections.emptySet(); } - return result; + + return Arrays.stream(dirs).filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); } /** @@ -227,17 +225,14 @@ public Artifact get( File file ) }; } File[] files = versionDir.listFiles(); - Set result = new HashSet( files.length ); - for ( int i = 0; i < files.length; i++ ) - { - if ( !files[i].isFile() || !rule.matcher( files[i].getName() ).matches() ) - { + Set result = new HashSet<>( files.length ); + for (File file : files) { + if (!file.isFile() || !rule.matcher(file.getName()).matches()) { continue; } - Artifact artifact = factory.get( files[i] ); - if ( artifact != null ) - { - result.add( artifact ); + Artifact artifact = factory.get(file); + if (artifact != null) { + result.add(artifact); } } return result; @@ -303,14 +298,12 @@ public void set( Artifact artifact, InputStream content ) throw new IOException( "Failed to create " + targetFile.getParentFile().getPath() ); } - OutputStream output = null; - try { - output = new FileOutputStream( targetFile ); + try (OutputStream output = Files.newOutputStream(targetFile.toPath())) + { IOUtils.copy( content, output ); } finally { IOUtils.closeQuietly( content ); - IOUtils.closeQuietly( output ); } } @@ -322,31 +315,22 @@ public Metadata getMetadata( String path ) { File file = root; String[] parts = StringUtils.strip( path, "/" ).split( "/" ); - for ( int i = 0; i < parts.length; i++ ) - { - file = new File( file, parts[i] ); + for (String part : parts) { + file = new File(file, part); } file = new File( file, "maven-metadata.xml" ); if ( !file.isFile() ) { throw new MetadataNotFoundException( path ); } - MetadataXpp3Reader reader = new MetadataXpp3Reader(); - InputStream inputStream = null; - try + + try (InputStream inputStream = Files.newInputStream( file.toPath() )) { - inputStream = new FileInputStream( file ); - return reader.read( inputStream ); + return new MetadataXpp3Reader().read( inputStream ); } catch ( XmlPullParserException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( inputStream ); + throw new IOException( e.getMessage(), e); } } @@ -361,22 +345,15 @@ public void setMetadata( String path, Metadata metadata ) File file = root; String[] parts = StringUtils.strip( path, "/" ).split( "/" ); - for ( int i = 0; i < parts.length; i++ ) - { - file = new File( file, parts[i] ); + for (String part : parts) { + file = new File(file, part); } file = new File( file, "maven-metadata.xml" ); - MetadataXpp3Writer writer = new MetadataXpp3Writer(); - OutputStream outputStream = null; - try + try (OutputStream outputStream = Files.newOutputStream(file.toPath())) { - outputStream = new FileOutputStream( file ); - writer.write( outputStream, metadata ); - } - finally { - IOUtils.closeQuietly( outputStream ); + new MetadataXpp3Writer().write( outputStream, metadata ); } } @@ -388,14 +365,14 @@ public long getMetadataLastModified( String path ) { File file = root; String[] parts = StringUtils.strip( path, "/" ).split( "/" ); - Stack stack = new Stack(); + Stack stack = new Stack<>(); for ( int i = 0; i < parts.length; i++ ) { if ( "..".equals( parts[i] ) ) { if ( !stack.isEmpty() ) { - file = (File) stack.pop(); + file = stack.pop(); } else { @@ -424,22 +401,14 @@ public ArchetypeCatalog getArchetypeCatalog() { throw new ArchetypeCatalogNotFoundException(); } - ArchetypeCatalogXpp3Reader reader = new ArchetypeCatalogXpp3Reader(); - InputStream inputStream = null; - try + + try (InputStream inputStream = Files.newInputStream(file.toPath())) { - inputStream = new FileInputStream( file ); - return reader.read( inputStream ); + return new ArchetypeCatalogXpp3Reader().read( inputStream ); } catch ( XmlPullParserException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( inputStream ); + throw new IOException( e.getMessage(), e); } } @@ -459,7 +428,6 @@ private File getFile( Artifact artifact ) File groupDir = new File( root, artifact.getGroupId().replace( '.', '/' ) ); File artifactDir = new File( groupDir, artifact.getArtifactId() ); File versionDir = new File( artifactDir, artifact.getVersion() ); - File targetFile = new File( versionDir, artifact.getName() ); - return targetFile; + return new File( versionDir, artifact.getName() ); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/FileSystemArtifactStore.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/FileSystemArtifactStore.java index 881ffc51..99ad06d4 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/FileSystemArtifactStore.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/FileSystemArtifactStore.java @@ -16,7 +16,6 @@ package org.codehaus.mojo.mrm.impl.maven; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.archetype.catalog.ArchetypeCatalog; import org.apache.maven.archetype.catalog.io.xpp3.ArchetypeCatalogXpp3Reader; @@ -35,6 +34,7 @@ import java.io.IOException; import java.io.InputStream; +import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; @@ -43,6 +43,7 @@ import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; /** * An artifact store based off a {@link FileSystem}. @@ -84,15 +85,9 @@ public Set getGroupIds( String parentGroupId ) } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; Entry[] entries = backing.listEntries( parentDir ); - Set result = new HashSet(); - for ( int i = 0; i < entries.length; i++ ) - { - if ( entries[i] instanceof DirectoryEntry ) - { - result.add( entries[i].getName() ); - } - } - return result; + return Arrays.stream(entries).filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** @@ -107,15 +102,9 @@ public Set getArtifactIds( String groupId ) } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; Entry[] entries = backing.listEntries( parentDir ); - Set result = new HashSet(); - for ( int i = 0; i < entries.length; i++ ) - { - if ( entries[i] instanceof DirectoryEntry ) - { - result.add( entries[i].getName() ); - } - } - return result; + return Arrays.stream(entries).filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** @@ -130,15 +119,9 @@ public Set getVersions( String groupId, String artifactId ) } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; Entry[] entries = backing.listEntries( parentDir ); - Set result = new HashSet(); - for ( int i = 0; i < entries.length; i++ ) - { - if ( entries[i] instanceof DirectoryEntry ) - { - result.add( entries[i].getName() ); - } - } - return result; + return Arrays.stream(entries).filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** @@ -216,17 +199,14 @@ public Artifact get( Entry entry ) } }; } - Set result = new HashSet( entries.length ); - for ( int i = 0; i < entries.length; i++ ) - { - if ( !( entries[i] instanceof FileEntry ) || !rule.matcher( entries[i].getName() ).matches() ) - { + Set result = new HashSet<>( entries.length ); + for (Entry entry : entries) { + if (!(entry instanceof FileEntry) || !rule.matcher(entry.getName()).matches()) { continue; } - Artifact artifact = factory.get( entries[i] ); - if ( artifact != null ) - { - result.add( artifact ); + Artifact artifact = factory.get(entry); + if (artifact != null) { + result.add(artifact); } } return result; @@ -301,22 +281,14 @@ public Metadata getMetadata( String path ) { throw new MetadataNotFoundException( path ); } - MetadataXpp3Reader reader = new MetadataXpp3Reader(); - InputStream inputStream = null; - try + + try (InputStream inputStream = ( (FileEntry) entry ).getInputStream()) { - inputStream = ( (FileEntry) entry ).getInputStream(); - return reader.read( inputStream ); + return new MetadataXpp3Reader().read( inputStream ); } catch ( XmlPullParserException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( inputStream ); + throw new IOException( e.getMessage(), e); } } @@ -343,22 +315,14 @@ public ArchetypeCatalog getArchetypeCatalog() { throw new ArchetypeCatalogNotFoundException(); } - ArchetypeCatalogXpp3Reader reader = new ArchetypeCatalogXpp3Reader(); - InputStream inputStream = null; - try + try (InputStream inputStream = ( (FileEntry) entry ).getInputStream()) { - inputStream = ( (FileEntry) entry ).getInputStream(); - return reader.read( inputStream ); + + return new ArchetypeCatalogXpp3Reader().read( inputStream ); } catch ( XmlPullParserException e ) { - IOException ioe = new IOException( e.getMessage() ); - ioe.initCause( e ); - throw ioe; - } - finally - { - IOUtils.closeQuietly( inputStream ); + throw new IOException( e.getMessage(), e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MemoryArtifactStore.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MemoryArtifactStore.java index cf80cee4..61317f3b 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MemoryArtifactStore.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MemoryArtifactStore.java @@ -78,8 +78,7 @@ public class MemoryArtifactStore * * @since 1.0 */ - private Map>>> contents = - new HashMap>>>(); + private Map>>> contents = new HashMap<>(); private Content archetypeCatalog; @@ -88,7 +87,7 @@ public class MemoryArtifactStore */ public synchronized Set getGroupIds( String parentGroupId ) { - Set result = new TreeSet(); + Set result = new TreeSet<>(); if ( StringUtils.isEmpty( parentGroupId ) ) { for ( String groupId : contents.keySet() ) @@ -119,7 +118,7 @@ public synchronized Set getGroupIds( String parentGroupId ) public synchronized Set getArtifactIds( String groupId ) { Map>> artifactMap = contents.get( groupId ); - return new TreeSet( artifactMap == null ? Collections. emptySet() : artifactMap.keySet() ); + return artifactMap == null ? Collections.emptySet() : new TreeSet<>(artifactMap.keySet() ); } /** @@ -129,7 +128,7 @@ public synchronized Set getVersions( String groupId, String artifactId ) { Map>> artifactMap = contents.get( groupId ); Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - return new TreeSet( versionMap == null ? Collections. emptySet() : versionMap.keySet() ); + return versionMap == null ? Collections.emptySet() : new TreeSet<>( versionMap.keySet() ); } /** @@ -141,7 +140,7 @@ public synchronized Set getArtifacts( String groupId, String artifactI Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - return new HashSet( filesMap == null ? Collections. emptySet() : filesMap.keySet() ); + return filesMap == null ? Collections.emptySet() : new HashSet<>( filesMap.keySet() ); } /** @@ -264,24 +263,9 @@ public synchronized InputStream get( Artifact artifact ) public synchronized void set( Artifact artifact, InputStream content ) throws IOException { - Map>> artifactMap = contents.get( artifact.getGroupId() ); - if ( artifactMap == null ) - { - artifactMap = new HashMap>>(); - contents.put( artifact.getGroupId(), artifactMap ); - } - Map> versionMap = artifactMap.get( artifact.getArtifactId() ); - if ( versionMap == null ) - { - versionMap = new HashMap>(); - artifactMap.put( artifact.getArtifactId(), versionMap ); - } - Map filesMap = versionMap.get( artifact.getVersion() ); - if ( filesMap == null ) - { - filesMap = new HashMap(); - versionMap.put( artifact.getVersion(), filesMap ); - } + Map>> artifactMap = contents.computeIfAbsent(artifact.getGroupId(), k -> new HashMap<>()); + Map> versionMap = artifactMap.computeIfAbsent(artifact.getArtifactId(), k -> new HashMap<>()); + Map filesMap = versionMap.computeIfAbsent(artifact.getVersion(), k -> new HashMap<>()); try { filesMap.put( artifact, new Content( IOUtils.toByteArray( content ) ) ); @@ -305,7 +289,7 @@ public synchronized Metadata getMetadata( String path ) Set pluginArtifactIds = getArtifactIds( groupId ); if ( pluginArtifactIds != null ) { - List plugins = new ArrayList(); + List plugins = new ArrayList<>(); for ( String artifactId : pluginArtifactIds ) { Set pluginVersions = getVersions( groupId, artifactId ); @@ -313,16 +297,15 @@ public synchronized Metadata getMetadata( String path ) { continue; } - String[] versions = (String[]) pluginVersions.toArray( new String[pluginVersions.size()] ); - Arrays.sort( versions, new VersionComparator() ); + String[] versions = pluginVersions.toArray(new String[0]); + Arrays.sort( versions, INSTANCE ); MavenXpp3Reader reader = new MavenXpp3Reader(); for ( int j = versions.length - 1; j >= 0; j-- ) { - InputStream inputStream = null; - try + try (InputStream inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) ); + XmlStreamReader xmlStreamReader = new XmlStreamReader( inputStream )) { - inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) ); - Model model = reader.read( new XmlStreamReader( inputStream ) ); + Model model = reader.read(xmlStreamReader); if ( model == null || !"maven-plugin".equals( model.getPackaging() ) ) { continue; @@ -364,18 +347,10 @@ public synchronized Metadata getMetadata( String path ) foundMetadata = true; break; } - catch ( ArtifactNotFoundException e ) + catch ( ArtifactNotFoundException | XmlPullParserException e ) { // ignore } - catch ( XmlPullParserException e ) - { - // ignore - } - finally - { - IOUtils.closeQuietly( inputStream ); - } } } if ( !plugins.isEmpty() ) @@ -394,8 +369,8 @@ public synchronized Metadata getMetadata( String path ) metadata.setGroupId( groupId ); metadata.setArtifactId( artifactId ); Versioning versioning = new Versioning(); - List versions = new ArrayList( artifactVersions ); - Collections.sort( versions, new VersionComparator() ); // sort the Maven way + List versions = new ArrayList<>( artifactVersions ); + versions.sort(INSTANCE); // sort the Maven way long lastUpdated = 0; for ( String version : versions ) { @@ -435,15 +410,15 @@ public synchronized Metadata getMetadata( String path ) Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); if ( filesMap != null ) { - List snapshotVersions = new ArrayList(); + List snapshotVersions = new ArrayList<>(); int maxBuildNumber = 0; long lastUpdated = 0; String timestamp = null; boolean found = false; - for ( final Map.Entry entry : filesMap.entrySet() ) + for ( Map.Entry entry : filesMap.entrySet() ) { - final Artifact artifact = entry.getKey(); - final Content content = entry.getValue(); + Artifact artifact = entry.getKey(); + Content content = entry.getValue(); SimpleDateFormat fmt = new SimpleDateFormat( "yyyyMMddHHmmss" ); fmt.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); String lastUpdatedTime = fmt.format( new Date( content.getLastModified() ) ); @@ -458,9 +433,9 @@ public synchronized Metadata getMetadata( String path ) if ( "pom".equals( artifact.getType() ) ) { if ( artifact.getBuildNumber() != null - && maxBuildNumber < artifact.getBuildNumber().intValue() ) + && maxBuildNumber < artifact.getBuildNumber()) { - maxBuildNumber = artifact.getBuildNumber().intValue(); + maxBuildNumber = artifact.getBuildNumber(); timestamp = artifact.getTimestampString(); } else @@ -592,21 +567,14 @@ public synchronized ArchetypeCatalog getArchetypeCatalog() { if ( archetypeCatalog != null ) { - ArchetypeCatalogXpp3Reader reader = new ArchetypeCatalogXpp3Reader(); - InputStream inputStream = null; - try + try (InputStream inputStream = new ByteArrayInputStream( archetypeCatalog.getBytes() )) { - inputStream = new ByteArrayInputStream( archetypeCatalog.getBytes() ); - return reader.read( inputStream ); + return new ArchetypeCatalogXpp3Reader().read( inputStream ); } catch ( XmlPullParserException e ) { throw new ArchetypeCatalogNotFoundException( e.getMessage(), e ); } - finally - { - IOUtils.closeQuietly( inputStream ); - } } else { @@ -660,6 +628,8 @@ private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, List INSTANCE = new VersionComparator(); + /** * Compares two versions using Maven's version comparison rules. * diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MetadataFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MetadataFileEntry.java index c7bb552b..86c07288 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MetadataFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MetadataFileEntry.java @@ -93,9 +93,7 @@ public long getSize() } catch ( MetadataNotFoundException e ) { - IOException ioe = new IOException( "File not found" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "File not found", e); } } @@ -131,9 +129,7 @@ public long getLastModified() } catch ( MetadataNotFoundException e ) { - IOException ioe = new IOException( "File not found" ); - ioe.initCause( e ); - throw ioe; + throw new IOException( "File not found", e); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStore.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStore.java index e6060128..5dd377cd 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStore.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStore.java @@ -20,7 +20,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileReader; -import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; @@ -138,10 +137,8 @@ public MockArtifactStore( Log log, File root, boolean lazyArchiver ) Collection poms = FileUtils.listFiles( root, POM_EXTENSIONS, true ); for ( File file : poms ) { - FileReader fileReader; - try + try (FileReader fileReader = new FileReader( file )) { - fileReader = new FileReader( file ); Model model = pomReader.read( fileReader ); String groupId = model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId(); String version = model.getVersion() != null ? model.getVersion() : model.getParent().getVersion(); @@ -174,14 +171,8 @@ else if ( "maven-plugin".equals( model.getPackaging() ) ) version ) ) ); } - Collection classifiedFiles = Arrays.asList( file.getParentFile().listFiles( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return FilenameUtils.getBaseName( name ).startsWith( basename + '-' ); - } - } ) ); + File[] classifiedFiles = file.getParentFile() + .listFiles((dir, name) -> FilenameUtils.getBaseName( name ).startsWith( basename + '-' )); for ( File classifiedFile : classifiedFiles ) { @@ -231,7 +222,7 @@ public boolean accept( File dir, String name ) */ public synchronized Set getGroupIds( String parentGroupId ) { - TreeSet result = new TreeSet(); + TreeSet result = new TreeSet<>(); if ( StringUtils.isEmpty( parentGroupId ) ) { for ( String groupId : contents.keySet() ) @@ -262,7 +253,7 @@ public synchronized Set getGroupIds( String parentGroupId ) public synchronized Set getArtifactIds( String groupId ) { Map>> artifactMap = contents.get( groupId ); - return new TreeSet( artifactMap == null ? Collections.emptySet() : artifactMap.keySet() ); + return artifactMap == null ? Collections.emptySet() : new TreeSet<>( artifactMap.keySet() ); } /** @@ -272,7 +263,7 @@ public synchronized Set getVersions( String groupId, String artifactId ) { Map>> artifactMap = contents.get( groupId ); Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - return new TreeSet( versionMap == null ? Collections.emptySet() : versionMap.keySet() ); + return versionMap == null ? Collections.emptySet() : new TreeSet<>( versionMap.keySet() ); } /** @@ -284,7 +275,7 @@ public synchronized Set getArtifacts( String groupId, String artifactI Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - return new HashSet( filesMap == null ? Collections.emptySet() : filesMap.keySet() ); + return filesMap == null ? Collections.emptySet() : new HashSet<>( filesMap.keySet() ); } /** @@ -423,24 +414,11 @@ public synchronized void set( Artifact artifact, InputStream content ) */ private synchronized void set( Artifact artifact, Content content ) { - Map>> artifactMap = contents.get( artifact.getGroupId() ); - if ( artifactMap == null ) - { - artifactMap = new HashMap>>(); - contents.put( artifact.getGroupId(), artifactMap ); - } - Map> versionMap = artifactMap.get( artifact.getArtifactId() ); - if ( versionMap == null ) - { - versionMap = new HashMap>(); - artifactMap.put( artifact.getArtifactId(), versionMap ); - } - Map filesMap = versionMap.get( artifact.getVersion() ); - if ( filesMap == null ) - { - filesMap = new HashMap(); - versionMap.put( artifact.getVersion(), filesMap ); - } + Map>> artifactMap = + contents.computeIfAbsent(artifact.getGroupId(), k -> new HashMap<>()); + Map> versionMap = + artifactMap.computeIfAbsent(artifact.getArtifactId(), k -> new HashMap<>()); + Map filesMap = versionMap.computeIfAbsent(artifact.getVersion(), k -> new HashMap<>()); filesMap.put( artifact, content ); } @@ -457,7 +435,7 @@ public synchronized Metadata getMetadata( String path ) Set pluginArtifactIds = getArtifactIds( groupId ); if ( pluginArtifactIds != null ) { - List plugins = new ArrayList(); + List plugins = new ArrayList<>(); for ( String artifactId : pluginArtifactIds ) { Set pluginVersions = getVersions( groupId, artifactId ); @@ -465,16 +443,13 @@ public synchronized Metadata getMetadata( String path ) { continue; } - String[] versions = pluginVersions.toArray( new String[pluginVersions.size()] ); - Arrays.sort( versions, new VersionComparator() ); - MavenXpp3Reader reader = new MavenXpp3Reader(); + String[] versions = pluginVersions.toArray(new String[0]); + Arrays.sort( versions, INSTANCE); for ( int j = versions.length - 1; j >= 0; j-- ) { - InputStream inputStream = null; - try + try (InputStream inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) )) { - inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) ); - Model model = reader.read( new XmlStreamReader( inputStream ) ); + Model model = new MavenXpp3Reader().read( new XmlStreamReader( inputStream ) ); if ( model == null || !"maven-plugin".equals( model.getPackaging() ) ) { continue; @@ -516,18 +491,10 @@ public synchronized Metadata getMetadata( String path ) foundMetadata = true; break; } - catch ( ArtifactNotFoundException e ) - { - // ignore - } - catch ( XmlPullParserException e ) + catch ( ArtifactNotFoundException | XmlPullParserException e ) { // ignore } - finally - { - IOUtils.closeQuietly( inputStream ); - } } } if ( !plugins.isEmpty() ) @@ -546,8 +513,8 @@ public synchronized Metadata getMetadata( String path ) metadata.setGroupId( groupId ); metadata.setArtifactId( artifactId ); Versioning versioning = new Versioning(); - List versions = new ArrayList( artifactVersions ); - Collections.sort( versions, new VersionComparator() ); // sort the Maven way + List versions = new ArrayList<>( artifactVersions ); + versions.sort(INSTANCE); // sort the Maven way long lastUpdated = 0; for ( String version : versions ) { @@ -587,7 +554,7 @@ public synchronized Metadata getMetadata( String path ) Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); if ( filesMap != null ) { - List snapshotVersions = new ArrayList(); + List snapshotVersions = new ArrayList<>(); int maxBuildNumber = 0; long lastUpdated = 0; String timestamp = null; @@ -610,9 +577,9 @@ public synchronized Metadata getMetadata( String path ) if ( "pom".equals( artifact.getType() ) ) { if ( artifact.getBuildNumber() != null - && maxBuildNumber < artifact.getBuildNumber().intValue() ) + && maxBuildNumber < artifact.getBuildNumber()) { - maxBuildNumber = artifact.getBuildNumber().intValue(); + maxBuildNumber = artifact.getBuildNumber(); timestamp = artifact.getTimestampString(); } else @@ -798,6 +765,8 @@ private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, List INSTANCE = new VersionComparator(); + /** * Compares two versions using Maven's version comparison rules. * @@ -997,11 +966,7 @@ private void createArchive() { archiver.createArchive(); } - catch ( ArchiverException e ) - { - throw new RuntimeException( e.getMessage(), e ); - } - catch ( IOException e ) + catch ( ArchiverException| IOException e ) { throw new RuntimeException( e.getMessage(), e ); } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/HostedRepo.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/HostedRepo.java index 0585a0fc..0e7d3ebc 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/HostedRepo.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/HostedRepo.java @@ -31,9 +31,6 @@ public ArtifactStore newInstance() @Override public String toString() { - final StringBuffer sb = new StringBuffer(); - sb.append( "Remote hosted (target: " ).append( target ); - sb.append( ')' ); - return sb.toString(); + return "Remote hosted (target: " + target + ')'; } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/LocalRepo.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/LocalRepo.java index c886fe44..ef38e5a9 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/LocalRepo.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/LocalRepo.java @@ -38,9 +38,6 @@ public ArtifactStore newInstance() */ public String toString() { - final StringBuffer sb = new StringBuffer(); - sb.append( "Locally hosted (source: " ).append( source ); - sb.append( ')' ); - return sb.toString(); + return "Locally hosted (source: " + source + ')'; } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/MockRepo.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/MockRepo.java index 85d0ad18..7fe04e10 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/MockRepo.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/plugin/MockRepo.java @@ -108,9 +108,6 @@ public void setFactoryHelper( FactoryHelper factoryHelper ) */ public String toString() { - final StringBuffer sb = new StringBuffer(); - sb.append( "Mock content (source: " ).append( source ); - sb.append( ')' ); - return sb.toString(); + return "Mock content (source: " + source + ')'; } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/servlet/FileSystemServlet.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/servlet/FileSystemServlet.java index c5151594..4cef5ac2 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/servlet/FileSystemServlet.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/servlet/FileSystemServlet.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.HttpURLConnection; @@ -30,7 +29,6 @@ import java.util.Date; import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -75,7 +73,7 @@ public class FileSystemServlet * * @since 1.0 */ - private FileSystem fileSystem; + private final FileSystem fileSystem; /** @@ -128,28 +126,24 @@ protected void doGet( HttpServletRequest req, HttpServletResponse resp ) { resp.setContentType( "text/xml" ); PrintWriter w = resp.getWriter(); - - Reader settingsReader = null; - try - { - String hostAddress; - try - { - hostAddress = InetAddress.getLocalHost().getHostAddress(); - } - catch ( UnknownHostException e ) - { - hostAddress = req.getServerName(); - } - String repositoryProxyUrl = req.getScheme() + "://" + hostAddress + ":" + req.getServerPort(); - Reader in = new InputStreamReader( FileSystemServlet.class.getResourceAsStream( "/settings-mrm.xml" ) ); - settingsReader = new InterpolationFilterReader( in, Collections.singletonMap( "repository.proxy.url", repositoryProxyUrl ), "@", "@" ); - IOUtil.copy( settingsReader, w ); + String hostAddress; + try + { + hostAddress = InetAddress.getLocalHost().getHostAddress(); } - finally + catch ( UnknownHostException e ) { - IOUtil.close( settingsReader ); + hostAddress = req.getServerName(); + } + + String repositoryProxyUrl = req.getScheme() + "://" + hostAddress + ":" + req.getServerPort(); + + try (Reader in = new InputStreamReader( FileSystemServlet.class.getResourceAsStream( "/settings-mrm.xml" ) ); + Reader settingsReader = + new InterpolationFilterReader( in, Collections.singletonMap( "repository.proxy.url", repositoryProxyUrl ), "@", "@" )) + { + IOUtil.copy( settingsReader, w ); } return; } @@ -164,18 +158,10 @@ protected void doGet( HttpServletRequest req, HttpServletResponse resp ) resp.setContentLength( (int) size ); } resp.setContentType( getServletContext().getMimeType( fileEntry.getName() ) ); - InputStream source = null; - OutputStream destination = null; - try - { - source = fileEntry.getInputStream(); - destination = resp.getOutputStream(); - IOUtils.copy( source, destination ); - } - finally + + try (InputStream source = fileEntry.getInputStream()) { - IOUtils.closeQuietly( source ); - IOUtils.closeQuietly( destination ); + IOUtils.copy( source, resp.getOutputStream() ); } return; } @@ -322,21 +308,14 @@ protected void doPut( HttpServletRequest req, HttpServletResponse resp ) { parent = new DefaultDirectoryEntry( fileSystem, parent, parts[i] ); } - ServletInputStream inputStream = null; - try - { - inputStream = req.getInputStream(); - FileEntry put = fileSystem.put( parent, name, inputStream ); - if ( put != null ) - { - resp.setStatus( HttpURLConnection.HTTP_OK ); - return; - } - } - finally + + FileEntry put = fileSystem.put( parent, name, req.getInputStream() ); + if ( put != null ) { - IOUtils.closeQuietly( inputStream ); + resp.setStatus( HttpURLConnection.HTTP_OK ); + return; } + resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); } diff --git a/mrm-webapp/pom.xml b/mrm-webapp/pom.xml index 80faeec7..c3945ca8 100644 --- a/mrm-webapp/pom.xml +++ b/mrm-webapp/pom.xml @@ -22,13 +22,13 @@ org.codehaus.mojo mrm - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT mrm-webapp war - Mock Repository Manager: Web Application + Mock Repository Manager :: Web Application diff --git a/pom.xml b/pom.xml index 772599b5..a6bd7758 100644 --- a/pom.xml +++ b/pom.xml @@ -27,10 +27,10 @@ org.codehaus.mojo mrm - 1.2.1-SNAPSHOT + 1.3.0-SNAPSHOT pom - Mock Repository Manager: Project + Mock Repository Manager :: Project Mock Repository Manager for Maven. The Mock Repository Manager provides a mock Maven repository manager. @@ -88,7 +88,7 @@ target/staging/mrm 2.2.1 - 1.7 + 1.8 @@ -239,7 +239,7 @@ org.codehaus.mojo.signature - java17 + java18 1.0