diff --git a/mrm-api/pom.xml b/mrm-api/pom.xml index 54924e54..351fa59b 100644 --- a/mrm-api/pom.xml +++ b/mrm-api/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -60,8 +58,7 @@ mockito-core test - - + 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 430b6d17..58025cf8 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 @@ -25,9 +25,7 @@ * @serial * @since 1.0 */ -public abstract class AbstractEntry - implements Entry -{ +public abstract class AbstractEntry implements Entry { /** * Ensure consistent serialization. @@ -65,8 +63,7 @@ public abstract class AbstractEntry * @param name The name of the entry. * @since 1.0 */ - protected AbstractEntry( FileSystem fileSystem, DirectoryEntry parent, String name ) - { + protected AbstractEntry(FileSystem fileSystem, DirectoryEntry parent, String name) { this.fileSystem = fileSystem; this.parent = parent; this.name = name; @@ -75,100 +72,84 @@ protected AbstractEntry( FileSystem fileSystem, DirectoryEntry parent, String na /** * {@inheritDoc} */ - public FileSystem getFileSystem() - { + public FileSystem getFileSystem() { return fileSystem; } /** * {@inheritDoc} */ - public DirectoryEntry getParent() - { + public DirectoryEntry getParent() { return parent; } /** * {@inheritDoc} */ - public String getName() - { + public String getName() { return name; } /** * {@inheritDoc} */ - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof AbstractEntry ) ) - { + if (!(o instanceof AbstractEntry)) { return false; } AbstractEntry abstractEntry = (AbstractEntry) o; - if ( !fileSystem.equals( abstractEntry.fileSystem ) ) - { + if (!fileSystem.equals(abstractEntry.fileSystem)) { return false; } - if ( !name.equals( abstractEntry.name ) ) - { + if (!name.equals(abstractEntry.name)) { return false; } - return Objects.equals( parent, abstractEntry.parent ); + return Objects.equals(parent, abstractEntry.parent); } /** * {@inheritDoc} */ - public final int hashCode() - { + public final int hashCode() { int result = name.hashCode(); - result = 31 * result + ( parent != null ? parent.hashCode() : 0 ); + result = 31 * result + (parent != null ? parent.hashCode() : 0); return result; } /** * {@inheritDoc} */ - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append( "Entry[" ); - sb.append( fileSystem ); - sb.append( ':' ).append( toPath() ).append( ']' ); + sb.append("Entry["); + sb.append(fileSystem); + sb.append(':').append(toPath()).append(']'); return sb.toString(); } /** * {@inheritDoc} */ - public final String toPath() - { + public final String toPath() { Stack stack = new Stack<>(); Entry root = getFileSystem().getRoot(); Entry entry = this; - do - { - stack.push( entry.getName() ); + do { + stack.push(entry.getName()); entry = entry.getParent(); - } - while ( entry != null && !root.equals( entry ) ); + } while (entry != null && !root.equals(entry)); StringBuilder buf = new StringBuilder(); - while ( stack.size() > 1 ) - { - buf.append( stack.pop() ); - buf.append( '/' ); + while (stack.size() > 1) { + buf.append(stack.pop()); + buf.append('/'); } - buf.append( stack.pop() ); + buf.append(stack.pop()); return buf.toString(); } - - } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileEntry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileEntry.java index 6bfa83cf..895fab47 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileEntry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/BaseFileEntry.java @@ -21,10 +21,7 @@ * * @since 1.0 */ -public abstract class BaseFileEntry - extends AbstractEntry - implements FileEntry -{ +public abstract class BaseFileEntry extends AbstractEntry implements FileEntry { /** * Ensure consistent serialization. * @@ -40,8 +37,7 @@ public abstract class BaseFileEntry * @param name The name of the entry. * @since 1.0 */ - protected BaseFileEntry( FileSystem fileSystem, DirectoryEntry parent, String name ) - { - super( fileSystem, parent, name ); + protected BaseFileEntry(FileSystem fileSystem, DirectoryEntry parent, String name) { + super(fileSystem, parent, name); } } 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 7d326407..3a0ae3d5 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 @@ -25,9 +25,7 @@ * * @since 1.0 */ -public abstract class BaseFileSystem - implements FileSystem -{ +public abstract class BaseFileSystem implements FileSystem { /** * Ensure consistent serialization. * @@ -38,40 +36,34 @@ public abstract class BaseFileSystem /** * The root entry. */ - private final DirectoryEntry root = new DefaultDirectoryEntry( this, null, "" ); + private final DirectoryEntry root = new DefaultDirectoryEntry(this, null, ""); /** * {@inheritDoc} */ - public DirectoryEntry getRoot() - { + public DirectoryEntry getRoot() { return root; } /** * {@inheritDoc} */ - public Entry get( String path ) - { - if ( path.startsWith( "/" ) ) - { - path = path.substring( 1 ); + public Entry get(String path) { + if (path.startsWith("/")) { + path = path.substring(1); } - if ( path.length() == 0 ) - { + if (path.length() == 0) { return root; } - String[] parts = path.split( "/" ); - if ( parts.length == 0 ) - { + String[] parts = path.split("/"); + if (parts.length == 0) { return root; } DirectoryEntry parent = root; - for ( int i = 0; i < parts.length - 1; i++ ) - { - parent = new DefaultDirectoryEntry( this, parent, parts[i] ); + for (int i = 0; i < parts.length - 1; i++) { + parent = new DefaultDirectoryEntry(this, parent, parts[i]); } - return get( parent, parts[parts.length - 1] ); + return get(parent, parts[parts.length - 1]); } /** @@ -83,16 +75,12 @@ public Entry get( String path ) * @param name the name of the entry to get. * @return the {@link Entry} or null if the entry does not exist. */ - protected Entry get( DirectoryEntry parent, String name ) - { + protected Entry get(DirectoryEntry parent, String name) { parent.getClass(); - Entry[] entries = listEntries( parent ); - if ( entries != null ) - { - for ( Entry entry : entries ) - { - if ( name.equals( entry.getName() ) ) - { + Entry[] entries = listEntries(parent); + if (entries != null) { + for (Entry entry : entries) { + if (name.equals(entry.getName())) { return entry; } } @@ -103,34 +91,28 @@ protected Entry get( DirectoryEntry parent, String name ) /** * {@inheritDoc} */ - public DirectoryEntry mkdir( DirectoryEntry parent, String name ) - { + public DirectoryEntry mkdir(DirectoryEntry parent, String name) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { + public FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public FileEntry put( DirectoryEntry parent, String name, byte[] content ) - throws IOException - { - return put( parent, name, new ByteArrayInputStream( content ) ); + public FileEntry put(DirectoryEntry parent, String name, byte[] content) throws IOException { + return put(parent, name, new ByteArrayInputStream(content)); } /** * {@inheritDoc} */ - public void remove( Entry entry ) - { + public void remove(Entry entry) { throw new UnsupportedOperationException(); } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DefaultDirectoryEntry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DefaultDirectoryEntry.java index 9aa097af..95a3d640 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DefaultDirectoryEntry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DefaultDirectoryEntry.java @@ -23,10 +23,7 @@ * * @since 1.0 */ -public class DefaultDirectoryEntry - extends AbstractEntry - implements DirectoryEntry -{ +public class DefaultDirectoryEntry extends AbstractEntry implements DirectoryEntry { /** * Ensure consistent serialization. * @@ -42,9 +39,8 @@ public class DefaultDirectoryEntry * @param name The name of the entry (or the empty string if this is the root entry). * @since 1.0 */ - public DefaultDirectoryEntry( FileSystem fileSystem, DirectoryEntry parent, String name ) - { - super( fileSystem, parent, name ); + public DefaultDirectoryEntry(FileSystem fileSystem, DirectoryEntry parent, String name) { + super(fileSystem, parent, name); } /** @@ -56,25 +52,20 @@ public DefaultDirectoryEntry( FileSystem fileSystem, DirectoryEntry parent, Stri * @return a {@link DirectoryEntry} in the target filesystem. * @since 1.0 */ - public static DirectoryEntry equivalent( FileSystem target, DirectoryEntry directory ) - { - if ( target.equals( directory.getFileSystem() ) ) - { + public static DirectoryEntry equivalent(FileSystem target, DirectoryEntry directory) { + if (target.equals(directory.getFileSystem())) { return directory; } - if ( directory.getParent() == null ) - { + if (directory.getParent() == null) { return target.getRoot(); } - return new DefaultDirectoryEntry( target, equivalent( target, directory.getParent() ), directory.getName() ); + return new DefaultDirectoryEntry(target, equivalent(target, directory.getParent()), directory.getName()); } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { - return getFileSystem().getLastModified( this ); + public long getLastModified() throws IOException { + return getFileSystem().getLastModified(this); } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DirectoryEntry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DirectoryEntry.java index 41324f69..b3611659 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DirectoryEntry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/DirectoryEntry.java @@ -21,7 +21,4 @@ * * @since 1.0 */ -public interface DirectoryEntry - extends Entry -{ -} +public interface DirectoryEntry extends Entry {} diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/Entry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/Entry.java index f437f296..54a4f3e8 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/Entry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/Entry.java @@ -23,9 +23,7 @@ * * @since 1.0 */ -public interface Entry - extends Serializable -{ +public interface Entry extends Serializable { /** * Returns the repository that this entry belongs to. @@ -62,8 +60,7 @@ public interface Entry * @throws IOException if an I/O error occurs. * @since 1.0 */ - long getLastModified() - throws IOException; + long getLastModified() throws IOException; /** * Returns the path of this entry relative to the root of the filesystem. diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileEntry.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileEntry.java index a09fe254..4227f864 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileEntry.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileEntry.java @@ -24,9 +24,7 @@ * * @since 1.0 */ -public interface FileEntry - extends Entry -{ +public interface FileEntry extends Entry { /** * Returns the size in bytes of the entry. * @@ -34,8 +32,7 @@ public interface FileEntry * @throws IOException if an I/O error occurs. * @since 1.0 */ - long getSize() - throws IOException; + long getSize() throws IOException; /** * Returns the contents of the entry. @@ -44,6 +41,5 @@ long getSize() * @throws IOException if an I/O error occurs. * @since 1.0 */ - InputStream getInputStream() - throws IOException; + InputStream getInputStream() throws IOException; } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java index f9348909..22be5867 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java @@ -25,9 +25,7 @@ * * @since 1.0 */ -public interface FileSystem - extends Serializable -{ +public interface FileSystem extends Serializable { /** * Lists the entries in the specified directory. Some implementations may be lazy caching * implementations, in which case it is permitted to return either an empty array, or only those entries which @@ -41,7 +39,7 @@ public interface FileSystem * modify the returned array. * @since 1.0 */ - Entry[] listEntries( DirectoryEntry directory ); + Entry[] listEntries(DirectoryEntry directory); /** * Returns the root directory entry. @@ -59,7 +57,7 @@ public interface FileSystem * @return the {@link Entry} or null if the path definitely does not exist. * @since 1.0 */ - Entry get( String path ); + Entry get(String path); /** * Returns the time that the specified directory entry was last modified. Note: @@ -73,8 +71,7 @@ public interface FileSystem * @throws IOException if an I/O error occurs. * @since 1.0 */ - long getLastModified( DirectoryEntry entry ) - throws IOException; + long getLastModified(DirectoryEntry entry) throws IOException; /** * Makes the specified child directory. @@ -85,7 +82,7 @@ long getLastModified( DirectoryEntry entry ) * @throws UnsupportedOperationException if the repository is read-only. * @since 1.0 */ - DirectoryEntry mkdir( DirectoryEntry parent, String name ); + DirectoryEntry mkdir(DirectoryEntry parent, String name); /** * Puts the specified content into a the specified directory. @@ -98,8 +95,7 @@ long getLastModified( DirectoryEntry entry ) * @throws java.io.IOException if the content could not be read/written. * @since 1.0 */ - FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException; + FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException; /** * Puts the specified content into a the specified directory. @@ -112,8 +108,7 @@ FileEntry put( DirectoryEntry parent, String name, InputStream content ) * @throws java.io.IOException if the content could not be read/written. * @since 1.0 */ - FileEntry put( DirectoryEntry parent, String name, byte[] content ) - throws IOException; + FileEntry put(DirectoryEntry parent, String name, byte[] content) throws IOException; /** * Removes the specified entry (and if the entry is a directory, all its children). @@ -122,5 +117,5 @@ FileEntry put( DirectoryEntry parent, String name, byte[] content ) * @throws UnsupportedOperationException if the repository is read-only. * @since 1.0 */ - void remove( Entry entry ); + void remove(Entry entry); } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArchetypeCatalogNotFoundException.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArchetypeCatalogNotFoundException.java index a1b47257..c52db06a 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArchetypeCatalogNotFoundException.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArchetypeCatalogNotFoundException.java @@ -21,9 +21,7 @@ * * @since 1.0 */ -public class ArchetypeCatalogNotFoundException - extends Exception -{ +public class ArchetypeCatalogNotFoundException extends Exception { /** * Ensure consistent serialization. * @@ -36,8 +34,7 @@ public class ArchetypeCatalogNotFoundException * * @since 1.0 */ - public ArchetypeCatalogNotFoundException() - { + public ArchetypeCatalogNotFoundException() { super(); } @@ -47,9 +44,8 @@ public ArchetypeCatalogNotFoundException() * @param message The message. * @since 1.0 */ - public ArchetypeCatalogNotFoundException( String message ) - { - this( message, null ); + public ArchetypeCatalogNotFoundException(String message) { + this(message, null); } /** @@ -59,8 +55,7 @@ public ArchetypeCatalogNotFoundException( String message ) * @param cause the reason why it was not found (or null if there is no specific reason) * @since 1.0 */ - public ArchetypeCatalogNotFoundException( String message, Throwable cause ) - { - super( message, cause ); + public ArchetypeCatalogNotFoundException(String message, Throwable cause) { + super(message, cause); } } 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 a047ac75..ee471d5f 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 @@ -30,9 +30,7 @@ * @serial * @since 1.0 */ -public final class Artifact - implements Serializable, Comparable -{ +public final class Artifact implements Serializable, Comparable { /** * Ensure consistent serialization. @@ -120,9 +118,14 @@ public final class Artifact * timestamp!=null) * @since 1.0 */ - private Artifact( String groupId, String artifactId, String version, String classifier, String type, Long timestamp, - Integer buildNumber ) - { + private Artifact( + String groupId, + String artifactId, + String version, + String classifier, + String type, + Long timestamp, + Integer buildNumber) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; @@ -144,11 +147,15 @@ private Artifact( String groupId, String artifactId, String version, String clas * @param buildNumber The build number. * @since 1.0 */ - public Artifact( String groupId, String artifactId, String version, String classifier, String type, long timestamp, - int buildNumber ) - { - this( groupId, artifactId, version, classifier, type, Long.valueOf( timestamp ), - Integer.valueOf( buildNumber ) ); + public Artifact( + String groupId, + String artifactId, + String version, + String classifier, + String type, + long timestamp, + int buildNumber) { + this(groupId, artifactId, version, classifier, type, Long.valueOf(timestamp), Integer.valueOf(buildNumber)); } /** @@ -162,9 +169,8 @@ public Artifact( String groupId, String artifactId, String version, String class * @param buildNumber The build number. * @since 1.0 */ - public Artifact( String groupId, String artifactId, String version, String type, long timestamp, int buildNumber ) - { - this( groupId, artifactId, version, null, type, new Long( timestamp ), new Integer( buildNumber ) ); + public Artifact(String groupId, String artifactId, String version, String type, long timestamp, int buildNumber) { + this(groupId, artifactId, version, null, type, new Long(timestamp), new Integer(buildNumber)); } /** @@ -177,9 +183,8 @@ public Artifact( String groupId, String artifactId, String version, String type, * @param type The type. * @since 1.0 */ - public Artifact( String groupId, String artifactId, String version, String classifier, String type ) - { - this( groupId, artifactId, version, classifier, type, null, null ); + public Artifact(String groupId, String artifactId, String version, String classifier, String type) { + this(groupId, artifactId, version, classifier, type, null, null); } /** @@ -191,9 +196,8 @@ public Artifact( String groupId, String artifactId, String version, String class * @param type The type. * @since 1.0 */ - public Artifact( String groupId, String artifactId, String version, String type ) - { - this( groupId, artifactId, version, null, type ); + public Artifact(String groupId, String artifactId, String version, String type) { + this(groupId, artifactId, version, null, type); } /** @@ -202,12 +206,12 @@ public Artifact( String groupId, String artifactId, String version, String type * @return the name of the artifact. * @since 1.0 */ - public String getName() - { - if ( name == null ) - { - name = MessageFormat.format( "{0}-{1}{2}.{3}", new Object[] {artifactId, getTimestampVersion(), - ( classifier == null ? "" : "-" + classifier ), type} ); + public String getName() { + if (name == null) { + name = MessageFormat.format( + "{0}-{1}{2}.{3}", + new Object[] {artifactId, getTimestampVersion(), (classifier == null ? "" : "-" + classifier), type + }); } return name; } @@ -218,8 +222,7 @@ public String getName() * @return the groupId of the artifact. * @since 1.0 */ - public String getGroupId() - { + public String getGroupId() { return groupId; } @@ -229,8 +232,7 @@ public String getGroupId() * @return the artifactId of the artifact. * @since 1.0 */ - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } @@ -240,8 +242,7 @@ public String getArtifactId() * @return the version of the artifact. * @since 1.0 */ - public String getVersion() - { + public String getVersion() { return version; } @@ -251,8 +252,7 @@ public String getVersion() * @return the type of the artifact. * @since 1.0 */ - public String getType() - { + public String getType() { return type; } @@ -262,8 +262,7 @@ public String getType() * @return the classifier of the artifact (may be null). * @since 1.0 */ - public String getClassifier() - { + public String getClassifier() { return classifier; } @@ -273,8 +272,7 @@ public String getClassifier() * @return the timestamp of the artifact (may be null). * @since 1.0 */ - public Long getTimestamp() - { + public Long getTimestamp() { return timestamp; } @@ -284,8 +282,7 @@ public Long getTimestamp() * @return the build number of the artifact (may be null). * @since 1.0 */ - public Integer getBuildNumber() - { + public Integer getBuildNumber() { return buildNumber; } @@ -297,17 +294,13 @@ public Integer getBuildNumber() * (may be null). * @since 1.0 */ - public String getTimestampString() - { - if ( timestamp == null ) - { + public String getTimestampString() { + if (timestamp == null) { return null; - } - else - { - SimpleDateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" ); - fmt.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - return fmt.format( new Date( timestamp.longValue() ) ); + } else { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss"); + fmt.setTimeZone(TimeZone.getTimeZone("GMT")); + return fmt.format(new Date(timestamp.longValue())); } } @@ -323,21 +316,20 @@ public String getTimestampString() * @return the timestamp version. * @since 1.0 */ - public String getTimestampVersion() - { - if ( timestampVersion == null ) - { - if ( timestamp != null ) - { + public String getTimestampVersion() { + if (timestampVersion == null) { + if (timestamp != null) { assert isSnapshot(); - SimpleDateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" ); - fmt.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - timestampVersion = MessageFormat.format( "{0}-{1}-{2}", new Object[] { - this.version.substring( 0, this.version.length() - "-SNAPSHOT".length() ), - fmt.format( new Date( timestamp.longValue() ) ), buildNumber} ); - } - else - { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss"); + fmt.setTimeZone(TimeZone.getTimeZone("GMT")); + timestampVersion = MessageFormat.format( + "{0}-{1}-{2}", + new Object[] { + this.version.substring(0, this.version.length() - "-SNAPSHOT".length()), + fmt.format(new Date(timestamp.longValue())), + buildNumber + }); + } else { timestampVersion = version; } } @@ -350,53 +342,42 @@ public String getTimestampVersion() * @return true if and only if the artifact is a SNAPSHOT artifact. * @since 1.0 */ - public boolean isSnapshot() - { - return version.endsWith( "-SNAPSHOT" ); + public boolean isSnapshot() { + return version.endsWith("-SNAPSHOT"); } /** * {@inheritDoc} */ - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null || getClass() != o.getClass() ) - { + if (o == null || getClass() != o.getClass()) { return false; } Artifact artifact = (Artifact) o; - if ( !groupId.equals( artifact.groupId ) ) - { + if (!groupId.equals(artifact.groupId)) { return false; } - if ( !artifactId.equals( artifact.artifactId ) ) - { + if (!artifactId.equals(artifact.artifactId)) { return false; } - if ( !version.equals( artifact.version ) ) - { + if (!version.equals(artifact.version)) { return false; } - if ( !type.equals( artifact.type ) ) - { + if (!type.equals(artifact.type)) { return false; } - if ( !Objects.equals( classifier, artifact.classifier ) ) - { + if (!Objects.equals(classifier, artifact.classifier)) { return false; } - if ( !Objects.equals( buildNumber, artifact.buildNumber ) ) - { + if (!Objects.equals(buildNumber, artifact.buildNumber)) { return false; } - if ( !Objects.equals( timestamp, artifact.timestamp ) ) - { + if (!Objects.equals(timestamp, artifact.timestamp)) { return false; } @@ -411,31 +392,24 @@ public boolean equals( Object o ) * for SNAPSHOT versions). * @since 1.0 */ - public boolean equalSnapshots( Artifact artifact ) - { - if ( this == artifact ) - { + public boolean equalSnapshots(Artifact artifact) { + if (this == artifact) { return true; } - if ( !groupId.equals( artifact.groupId ) ) - { + if (!groupId.equals(artifact.groupId)) { return false; } - if ( !artifactId.equals( artifact.artifactId ) ) - { + if (!artifactId.equals(artifact.artifactId)) { return false; } - if ( !version.equals( artifact.version ) ) - { + if (!version.equals(artifact.version)) { return false; } - if ( !type.equals( artifact.type ) ) - { + if (!type.equals(artifact.type)) { return false; } - if ( !Objects.equals( classifier, artifact.classifier ) ) - { + if (!Objects.equals(classifier, artifact.classifier)) { return false; } @@ -445,41 +419,37 @@ public boolean equalSnapshots( Artifact artifact ) /** * {@inheritDoc} */ - public int hashCode() - { + public int hashCode() { int result = groupId.hashCode(); result = 31 * result + artifactId.hashCode(); result = 31 * result + version.hashCode(); result = 31 * result + type.hashCode(); - result = 31 * result + ( classifier != null ? classifier.hashCode() : 0 ); + result = 31 * result + (classifier != null ? classifier.hashCode() : 0); return result; } /** * {@inheritDoc} */ - public String toString() - { + public String toString() { final StringBuffer sb = new StringBuffer(); - sb.append( "Artifact" ); - sb.append( "{" ).append( groupId ); - sb.append( ":" ).append( artifactId ); - sb.append( ":" ).append( getTimestampVersion() ); - if ( classifier != null ) - { - sb.append( ":" ).append( classifier ); + sb.append("Artifact"); + sb.append("{").append(groupId); + sb.append(":").append(artifactId); + sb.append(":").append(getTimestampVersion()); + if (classifier != null) { + sb.append(":").append(classifier); } - sb.append( ":" ).append( type ); - sb.append( '}' ); + sb.append(":").append(type); + sb.append('}'); return sb.toString(); } /** * {@inheritDoc} */ - public int compareTo( Artifact that ) - { - int rv = this.getGroupId().compareTo( that.getGroupId() ); - return rv == 0 ? getName().compareTo( that.getName() ) : rv; + public int compareTo(Artifact that) { + int rv = this.getGroupId().compareTo(that.getGroupId()); + return rv == 0 ? getName().compareTo(that.getName()) : rv; } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactNotFoundException.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactNotFoundException.java index fee96d95..ff845428 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactNotFoundException.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactNotFoundException.java @@ -21,9 +21,7 @@ * * @since 1.0 */ -public class ArtifactNotFoundException - extends Exception -{ +public class ArtifactNotFoundException extends Exception { /** * Ensure consistent serialization. * @@ -44,9 +42,8 @@ public class ArtifactNotFoundException * @param artifact the artifact that was not found. * @since 1.0 */ - public ArtifactNotFoundException( Artifact artifact ) - { - this( artifact.toString(), artifact, null ); + public ArtifactNotFoundException(Artifact artifact) { + this(artifact.toString(), artifact, null); } /** @@ -56,9 +53,8 @@ public ArtifactNotFoundException( Artifact artifact ) * @param cause the reason why it was not found (or null if there is no specific reason) * @since 1.0 */ - public ArtifactNotFoundException( Artifact artifact, Throwable cause ) - { - this( artifact.toString(), artifact, cause ); + public ArtifactNotFoundException(Artifact artifact, Throwable cause) { + this(artifact.toString(), artifact, cause); } /** @@ -68,9 +64,8 @@ public ArtifactNotFoundException( Artifact artifact, Throwable cause ) * @param artifact the artifact that was not found. * @since 1.0 */ - public ArtifactNotFoundException( String message, Artifact artifact ) - { - this( message, artifact, null ); + public ArtifactNotFoundException(String message, Artifact artifact) { + this(message, artifact, null); } /** @@ -81,9 +76,8 @@ public ArtifactNotFoundException( String message, Artifact artifact ) * @param cause the reason why it was not found (or null if there is no specific reason) * @since 1.0 */ - public ArtifactNotFoundException( String message, Artifact artifact, Throwable cause ) - { - super( message, cause ); + public ArtifactNotFoundException(String message, Artifact artifact, Throwable cause) { + super(message, cause); this.artifact = artifact; } @@ -93,8 +87,7 @@ public ArtifactNotFoundException( String message, Artifact artifact, Throwable c * @return the artifact that does not exist. * @since 1.0 */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactStore.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactStore.java index 613dba94..89d9b58c 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactStore.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/ArtifactStore.java @@ -16,22 +16,20 @@ package org.codehaus.mojo.mrm.api.maven; -import org.apache.maven.archetype.catalog.ArchetypeCatalog; -import org.apache.maven.artifact.repository.metadata.Metadata; - import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.Set; +import org.apache.maven.archetype.catalog.ArchetypeCatalog; +import org.apache.maven.artifact.repository.metadata.Metadata; + /** * An artifact store holds Maven {@link Artifact}s and can provide {@link Metadata} about the artifacts that it holds. * * @since 1.0 */ -public interface ArtifactStore - extends Serializable -{ +public interface ArtifactStore extends Serializable { /** *

@@ -64,7 +62,7 @@ public interface ArtifactStore * one and only one additional segment. * @since 1.0 */ - Set getGroupIds( String parentGroupId ); + Set getGroupIds(String parentGroupId); /** *

@@ -81,7 +79,7 @@ public interface ArtifactStore * {@code groupId}. * @since 1.0 */ - Set getArtifactIds( String groupId ); + Set getArtifactIds(String groupId); /** *

@@ -99,7 +97,7 @@ public interface ArtifactStore * {@code groupId:artifactId}. * @since 1.0 */ - Set getVersions( String groupId, String artifactId ); + Set getVersions(String groupId, String artifactId); /** * Returns the set of artifacts at the specified groupId:artifactId:version. Some implementations may be lazy @@ -115,7 +113,7 @@ public interface ArtifactStore * specified {@code groupId:artifactId:version}. * @since 1.0 */ - Set getArtifacts( String groupId, String artifactId, String version ); + Set getArtifacts(String groupId, String artifactId, String version); /** * Returns the time that the specified artifact was last modified. @@ -130,8 +128,7 @@ public interface ArtifactStore * @throws ArtifactNotFoundException if the artifact definitely does not exist. * @since 1.0 */ - long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException; + long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException; /** * Returns the size in bytes of the specified artifact. @@ -142,8 +139,7 @@ long getLastModified( Artifact artifact ) * @throws ArtifactNotFoundException if the artifact definitely does not exist. * @since 1.0 */ - long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException; + long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException; /** * Retrieves the the artifact as an {@link InputStream}. The caller is responsible for closing the stream. @@ -154,8 +150,7 @@ long getSize( Artifact artifact ) * @throws ArtifactNotFoundException if the artifact does not exist. * @since 1.0 */ - InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException; + InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException; /** * Create/update the specified artifact. This is an optional method for implementers. @@ -166,8 +161,7 @@ InputStream get( Artifact artifact ) * @throws UnsupportedOperationException if the implementation is a read-only implementation. * @since 1.0 */ - void set( Artifact artifact, InputStream content ) - throws IOException; + void set(Artifact artifact, InputStream content) throws IOException; /** * Returns the specified metadata. @@ -178,8 +172,7 @@ void set( Artifact artifact, InputStream content ) * @throws MetadataNotFoundException if the metadata does not exist. * @since 1.0 */ - Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException; + Metadata getMetadata(String path) throws IOException, MetadataNotFoundException; /** * Create/update the specified metadata. @@ -189,7 +182,7 @@ Metadata getMetadata( String path ) * @throws IOException if an I/O error occurs. * @since 1.1.0 */ - void setMetadata( String path, Metadata content ) throws IOException; + void setMetadata(String path, Metadata content) throws IOException; /** * Returns the time that the specified metadata was last modified. @@ -204,8 +197,7 @@ Metadata getMetadata( String path ) * @throws MetadataNotFoundException if the metadata definitely does not exist. * @since 1.0 */ - long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException; + long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException; /** * @return ArchetypeCatalog @@ -228,6 +220,5 @@ long getMetadataLastModified( String path ) * @throws IOException if an I/O error occurs. * @since 1.0 */ - void setArchetypeCatalog( InputStream content ) throws IOException; - + void setArchetypeCatalog(InputStream content) throws IOException; } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/BaseArtifactStore.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/BaseArtifactStore.java index 02e1c1ed..26fa968b 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/BaseArtifactStore.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/BaseArtifactStore.java @@ -12,9 +12,7 @@ * @serial * @since 1.0 */ -public abstract class BaseArtifactStore - implements ArtifactStore -{ +public abstract class BaseArtifactStore implements ArtifactStore { /** * Ensure consistent serialization. @@ -26,45 +24,35 @@ public abstract class BaseArtifactStore /** * {@inheritDoc} */ - public void set( Artifact artifact, InputStream content ) - throws IOException - { - throw new UnsupportedOperationException( "Read-only artifact store" ); + public void set(Artifact artifact, InputStream content) throws IOException { + throw new UnsupportedOperationException("Read-only artifact store"); } @Override - public void setMetadata( String path, Metadata metadata ) - throws IOException - { - throw new UnsupportedOperationException( "Read-only artifact store" ); + public void setMetadata(String path, Metadata metadata) throws IOException { + throw new UnsupportedOperationException("Read-only artifact store"); } /** * {@inheritDoc} */ - public void setArchetypeCatalog( InputStream content ) - throws IOException - { - throw new UnsupportedOperationException( "Read-only artifact store" ); + public void setArchetypeCatalog(InputStream content) throws IOException { + throw new UnsupportedOperationException("Read-only artifact store"); } /** * {@inheritDoc} */ - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { - throw new ArchetypeCatalogNotFoundException( "Archetype Catalog not available", - new UnsupportedOperationException() ); + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { + throw new ArchetypeCatalogNotFoundException( + "Archetype Catalog not available", new UnsupportedOperationException()); } /** * {@inheritDoc} */ - public long getArchetypeCatalogLastModified() - throws IOException, ArchetypeCatalogNotFoundException - { - throw new ArchetypeCatalogNotFoundException( "Archetype Catalog not available", - new UnsupportedOperationException() ); + public long getArchetypeCatalogLastModified() throws IOException, ArchetypeCatalogNotFoundException { + throw new ArchetypeCatalogNotFoundException( + "Archetype Catalog not available", new UnsupportedOperationException()); } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/MetadataNotFoundException.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/MetadataNotFoundException.java index 300f8b4e..28630d81 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/MetadataNotFoundException.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/api/maven/MetadataNotFoundException.java @@ -21,9 +21,7 @@ * * @since 1.0 */ -public class MetadataNotFoundException - extends Exception -{ +public class MetadataNotFoundException extends Exception { /** * Ensure consistent serialization. * @@ -44,9 +42,8 @@ public class MetadataNotFoundException * @param path the path of the metadata that was not found. * @since 1.0 */ - public MetadataNotFoundException( String path ) - { - this( path, path ); + public MetadataNotFoundException(String path) { + this(path, path); } /** @@ -56,9 +53,8 @@ public MetadataNotFoundException( String path ) * @param path the path of the metadata that was not found. * @since 1.0 */ - public MetadataNotFoundException( String message, String path ) - { - this( message, path, null ); + public MetadataNotFoundException(String message, String path) { + this(message, path, null); } /** @@ -68,9 +64,8 @@ public MetadataNotFoundException( String message, String path ) * @param cause the reason why it was not found (or null if there is no specific reason) * @since 1.0 */ - public MetadataNotFoundException( String path, Throwable cause ) - { - this( path, path, cause ); + public MetadataNotFoundException(String path, Throwable cause) { + this(path, path, cause); } /** @@ -81,9 +76,8 @@ public MetadataNotFoundException( String path, Throwable cause ) * @param cause the reason why it was not found (or null if there is no specific reason) * @since 1.0 */ - public MetadataNotFoundException( String message, String path, Throwable cause ) - { - super( message, cause ); + public MetadataNotFoundException(String message, String path, Throwable cause) { + super(message, cause); this.path = path; } @@ -93,8 +87,7 @@ public MetadataNotFoundException( String message, String path, Throwable cause ) * @return the path of the metadata that was not found. * @since 1.0 */ - public String getPath() - { + public String getPath() { return path; } } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/ArtifactStoreFactory.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/ArtifactStoreFactory.java index b02079aa..98dc6fa5 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/ArtifactStoreFactory.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/ArtifactStoreFactory.java @@ -24,8 +24,7 @@ * @see FactoryHelperRequired * @since 1.0 */ -public interface ArtifactStoreFactory -{ +public interface ArtifactStoreFactory { /** * Creates a new {@link ArtifactStore} instance, note that implementations are free to create a singleton and always * return that instance. @@ -34,5 +33,4 @@ public interface ArtifactStoreFactory * @since 1.0 */ ArtifactStore newInstance(); - } 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 ff6449a7..883599e1 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 @@ -16,6 +16,8 @@ package org.codehaus.mojo.mrm.plugin; +import java.util.List; + import org.apache.maven.archetype.ArchetypeManager; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -23,16 +25,13 @@ import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.plugin.logging.Log; -import java.util.List; - /** * Helper interface that exposes the Maven components that may be required. * * @see FactoryHelperRequired * @since 1.0 */ -public interface FactoryHelper -{ +public interface FactoryHelper { /** * Returns the {@link RepositoryMetadataManager} provided by Maven. * @@ -91,11 +90,9 @@ public interface FactoryHelper /** * Returns the {@link ArchetypeManager} - * + * * @return The {@link ArchetypeManager} * @since 1.0 */ ArchetypeManager getArchetypeManager(); - - } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelperRequired.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelperRequired.java index e35f4d8b..41213266 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelperRequired.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FactoryHelperRequired.java @@ -19,16 +19,15 @@ /** * Marker interface to indicate that a {@link ArtifactStoreFactory} or {@link FileSystemFactory} should be provided with * a {@link FactoryHelper} before use. - * + * * @since 1.0 */ -public interface FactoryHelperRequired -{ +public interface FactoryHelperRequired { /** * Provide the {@link FactoryHelper} instance. - * + * * @param factoryHelper the {@link FactoryHelper} instance. * @since 1.0 */ - void setFactoryHelper( FactoryHelper factoryHelper ); + void setFactoryHelper(FactoryHelper factoryHelper); } diff --git a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java index b2fe378d..e5904ccf 100644 --- a/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java +++ b/mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java @@ -20,19 +20,17 @@ /** * Something that produces new {@link FileSystem} instances. - * + * * @see FactoryHelperRequired * @since 1.0 */ -public interface FileSystemFactory -{ +public interface FileSystemFactory { /** * Creates a new {@link FileSystem} instance, note that implementations are free to create a singleton and always * return that instance. - * + * * @return the {@link FileSystem} instance. * @since 1.0 */ FileSystem newInstance(); - } diff --git a/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/AbstractEntryTest.java b/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/AbstractEntryTest.java index 7be80002..2f6f9e3c 100644 --- a/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/AbstractEntryTest.java +++ b/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/AbstractEntryTest.java @@ -1,24 +1,21 @@ -package org.codehaus.mojo.mrm.api; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Test; - -public class AbstractEntryTest -{ - - // MMOCKRM-13 - @Test - public void testPathForRootEntry() - { - FileSystem fileSystem = mock( FileSystem.class ); - DefaultDirectoryEntry entry = new DefaultDirectoryEntry( fileSystem, null, "/favicon.ico" ); - - when( fileSystem.getRoot() ).thenReturn( entry ); - - assertEquals( "/favicon.ico", entry.toPath() ); - } - -} +package org.codehaus.mojo.mrm.api; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class AbstractEntryTest { + + // MMOCKRM-13 + @Test + public void testPathForRootEntry() { + FileSystem fileSystem = mock(FileSystem.class); + DefaultDirectoryEntry entry = new DefaultDirectoryEntry(fileSystem, null, "/favicon.ico"); + + when(fileSystem.getRoot()).thenReturn(entry); + + assertEquals("/favicon.ico", entry.toPath()); + } +} diff --git a/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/maven/ArtifactTest.java b/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/maven/ArtifactTest.java index 6d6601da..0208cceb 100644 --- a/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/maven/ArtifactTest.java +++ b/mrm-api/src/test/java/org/codehaus/mojo/mrm/api/maven/ArtifactTest.java @@ -15,16 +15,13 @@ */ package org.codehaus.mojo.mrm.api.maven; -import static org.junit.Assert.assertEquals; - import org.junit.Test; -public class ArtifactTest -{ +import static org.junit.Assert.assertEquals; + +public class ArtifactTest { @Test - public void testSmokes() - throws Exception - { - assertEquals( new Artifact( "foo", "bar", "1.0", "jar" ), new Artifact( "foo", "bar", "1.0", null, "jar" ) ); + public void testSmokes() throws Exception { + assertEquals(new Artifact("foo", "bar", "1.0", "jar"), new Artifact("foo", "bar", "1.0", null, "jar")); } } diff --git a/mrm-maven-plugin/pom.xml b/mrm-maven-plugin/pom.xml index 01a486c1..0ff7cdd4 100644 --- a/mrm-maven-plugin/pom.xml +++ b/mrm-maven-plugin/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 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 3b36db6f..fb5fcbfd 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 @@ -16,6 +16,19 @@ * limitations under the License. */ +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + import org.apache.commons.lang.StringUtils; import org.apache.maven.archetype.ArchetypeManager; import org.apache.maven.archetype.catalog.ArchetypeCatalog; @@ -40,25 +53,10 @@ import org.codehaus.mojo.mrm.api.maven.BaseArtifactStore; import org.codehaus.mojo.mrm.api.maven.MetadataNotFoundException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -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. */ -public class ProxyArtifactStore - extends BaseArtifactStore -{ +public class ProxyArtifactStore extends BaseArtifactStore { /** * The {@link RepositoryMetadataManager} provided by Maven. */ @@ -89,7 +87,6 @@ public class ProxyArtifactStore */ private final ArtifactResolver artifactResolver; - private final ArchetypeManager archetypeManager; /** @@ -118,13 +115,16 @@ public class ProxyArtifactStore * @param artifactResolver the {@link ArtifactResolver} to use. * @param log the {@link Log} to log to. */ - @SuppressWarnings( "checkstyle:ParameterNumber" ) - public ProxyArtifactStore( RepositoryMetadataManager repositoryMetadataManager, - List remoteArtifactRepositories, - List remotePluginRepositories, ArtifactRepository localRepository, - ArtifactFactory artifactFactory, ArtifactResolver artifactResolver, - ArchetypeManager archetypeManager, Log log ) - { + @SuppressWarnings("checkstyle:ParameterNumber") + public ProxyArtifactStore( + RepositoryMetadataManager repositoryMetadataManager, + List remoteArtifactRepositories, + List remotePluginRepositories, + ArtifactRepository localRepository, + ArtifactFactory artifactFactory, + ArtifactResolver artifactResolver, + ArchetypeManager archetypeManager, + Log log) { this.repositoryMetadataManager = repositoryMetadataManager; this.remotePluginRepositories = remotePluginRepositories; this.localRepository = localRepository; @@ -133,16 +133,13 @@ public ProxyArtifactStore( RepositoryMetadataManager repositoryMetadataManager, this.archetypeManager = archetypeManager; this.log = log; remoteRepositories = new ArrayList<>(); - remoteRepositories.addAll( remoteArtifactRepositories ); - remoteRepositories.addAll( remotePluginRepositories ); - try - { - anyVersion = VersionRange.createFromVersionSpec( "[0,]" ); - } - catch ( InvalidVersionSpecificationException e ) - { + remoteRepositories.addAll(remoteArtifactRepositories); + remoteRepositories.addAll(remotePluginRepositories); + try { + anyVersion = VersionRange.createFromVersionSpec("[0,]"); + } catch (InvalidVersionSpecificationException e) { // must never happen... so if it does make sure we stop - throw new IllegalStateException( "[0,] should always be a valid version specification", e ); + throw new IllegalStateException("[0,] should always be a valid version specification", e); } } @@ -151,13 +148,12 @@ public ProxyArtifactStore( RepositoryMetadataManager repositoryMetadataManager, * * @param artifact the artifact that was resolved. */ - private synchronized void addResolved( Artifact artifact ) - { + private synchronized void addResolved(Artifact artifact) { String path = - artifact.getGroupId().replace( '.', '/' ) + '/' + artifact.getArtifactId() + "/" + artifact.getVersion(); - Map artifactMapper = this.children.computeIfAbsent( path, k -> new HashMap<>() ); - artifactMapper.put( artifact.getName(), artifact ); - addResolved( path ); + artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + "/" + artifact.getVersion(); + Map artifactMapper = this.children.computeIfAbsent(path, k -> new HashMap<>()); + artifactMapper.put(artifact.getName(), artifact); + addResolved(path); } /** @@ -165,358 +161,302 @@ private synchronized void addResolved( Artifact artifact ) * * @param path the path that was resolved. */ - private synchronized void addResolved( String path ) - { - for ( int index = path.lastIndexOf( '/' ); index > 0; index = path.lastIndexOf( '/' ) ) - { - String name = path.substring( index + 1 ); - path = path.substring( 0, index ); - Map artifactMapper = this.children.computeIfAbsent( path, k -> new HashMap<>() ); - artifactMapper.put( name, null ); + private synchronized void addResolved(String path) { + for (int index = path.lastIndexOf('/'); index > 0; index = path.lastIndexOf('/')) { + String name = path.substring(index + 1); + path = path.substring(0, index); + Map artifactMapper = this.children.computeIfAbsent(path, k -> new HashMap<>()); + artifactMapper.put(name, null); } - if ( !StringUtils.isEmpty( path ) ) - { - Map artifactMapper = this.children.computeIfAbsent( "", k -> new HashMap<>() ); - artifactMapper.put( path, null ); + if (!StringUtils.isEmpty(path)) { + Map artifactMapper = this.children.computeIfAbsent("", k -> new HashMap<>()); + artifactMapper.put(path, null); } } /** * {@inheritDoc} */ - public synchronized Set getGroupIds( String parentGroupId ) - { - String path = parentGroupId.replace( '.', '/' ); - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { + public synchronized Set getGroupIds(String parentGroupId) { + String path = parentGroupId.replace('.', '/'); + Map artifactMapper = this.children.get(path); + if (artifactMapper == null) { return Collections.emptySet(); } - return artifactMapper.entrySet().stream().filter( entry -> entry.getValue() == null ) - .map( Map.Entry::getKey ) - .collect( Collectors.toSet() ); + return artifactMapper.entrySet().stream() + .filter(entry -> entry.getValue() == null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public synchronized Set getArtifactIds( String groupId ) - { - String path = groupId.replace( '.', '/' ); - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { + public synchronized Set getArtifactIds(String groupId) { + String path = groupId.replace('.', '/'); + Map artifactMapper = this.children.get(path); + if (artifactMapper == null) { return Collections.emptySet(); } - return artifactMapper.entrySet().stream().filter( entry -> entry.getValue() == null ) - .map( Map.Entry::getKey ) - .collect( Collectors.toSet() ); + return artifactMapper.entrySet().stream() + .filter(entry -> entry.getValue() == null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public synchronized Set getVersions( String groupId, String artifactId ) - { - String path = groupId.replace( '.', '/' ) + '/' + artifactId; - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { + public synchronized Set getVersions(String groupId, String artifactId) { + String path = groupId.replace('.', '/') + '/' + artifactId; + Map artifactMapper = this.children.get(path); + if (artifactMapper == null) { return Collections.emptySet(); } - return artifactMapper.entrySet().stream().filter( entry -> entry.getValue() == null ) - .map( Map.Entry::getKey ) - .collect( Collectors.toSet() ); + return artifactMapper.entrySet().stream() + .filter(entry -> entry.getValue() == null) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public synchronized Set getArtifacts( String groupId, String artifactId, String version ) - { - String path = groupId.replace( '.', '/' ) + '/' + artifactId + "/" + version; - Map artifactMapper = this.children.get( path ); - if ( artifactMapper == null ) - { + public synchronized Set getArtifacts(String groupId, String artifactId, String version) { + String path = groupId.replace('.', '/') + '/' + artifactId + "/" + version; + Map artifactMapper = this.children.get(path); + if (artifactMapper == null) { return Collections.emptySet(); } - return artifactMapper.values().stream().filter( Objects::nonNull ) - .collect( Collectors.toSet() ); - + return artifactMapper.values().stream().filter(Objects::nonNull).collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - org.apache.maven.artifact.Artifact mavenArtifact = - artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), - artifact.getTimestampVersion(), artifact.getType(), - artifact.getClassifier() ); - try - { - artifactResolver.resolve( mavenArtifact, remoteRepositories, localRepository ); + public long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + org.apache.maven.artifact.Artifact mavenArtifact = artifactFactory.createArtifactWithClassifier( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getTimestampVersion(), + artifact.getType(), + artifact.getClassifier()); + try { + artifactResolver.resolve(mavenArtifact, remoteRepositories, localRepository); final File file = mavenArtifact.getFile(); - if ( file != null && file.isFile() ) - { - addResolved( artifact ); + if (file != null && file.isFile()) { + addResolved(artifact); return file.lastModified(); } - throw new ArtifactNotFoundException( artifact ); - } - catch ( org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) - { - throw new ArtifactNotFoundException( artifact, e ); - } - catch ( ArtifactResolutionException e ) - { - throw new IOException( e.getMessage(), e ); + throw new ArtifactNotFoundException(artifact); + } catch (org.apache.maven.artifact.resolver.ArtifactNotFoundException e) { + throw new ArtifactNotFoundException(artifact, e); + } catch (ArtifactResolutionException e) { + throw new IOException(e.getMessage(), e); } } /** * {@inheritDoc} */ - public long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - org.apache.maven.artifact.Artifact mavenArtifact = - artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), - artifact.getTimestampVersion(), artifact.getType(), - artifact.getClassifier() ); - try - { - artifactResolver.resolve( mavenArtifact, remoteRepositories, localRepository ); + public long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + org.apache.maven.artifact.Artifact mavenArtifact = artifactFactory.createArtifactWithClassifier( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getTimestampVersion(), + artifact.getType(), + artifact.getClassifier()); + try { + artifactResolver.resolve(mavenArtifact, remoteRepositories, localRepository); final File file = mavenArtifact.getFile(); - if ( file != null && file.isFile() ) - { - addResolved( artifact ); + if (file != null && file.isFile()) { + addResolved(artifact); return file.length(); } - throw new ArtifactNotFoundException( artifact ); - } - catch ( org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) - { - throw new ArtifactNotFoundException( artifact, e ); - } - catch ( ArtifactResolutionException e ) - { - throw new IOException( e.getMessage(), e ); + throw new ArtifactNotFoundException(artifact); + } catch (org.apache.maven.artifact.resolver.ArtifactNotFoundException e) { + throw new ArtifactNotFoundException(artifact, e); + } catch (ArtifactResolutionException e) { + throw new IOException(e.getMessage(), e); } } /** * {@inheritDoc} */ - public InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - org.apache.maven.artifact.Artifact mavenArtifact = - artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), - artifact.getTimestampVersion(), artifact.getType(), - artifact.getClassifier() ); - try - { - artifactResolver.resolve( mavenArtifact, remoteRepositories, localRepository ); + public InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + org.apache.maven.artifact.Artifact mavenArtifact = artifactFactory.createArtifactWithClassifier( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getTimestampVersion(), + artifact.getType(), + artifact.getClassifier()); + try { + artifactResolver.resolve(mavenArtifact, remoteRepositories, localRepository); File file = mavenArtifact.getFile(); - if ( file != null && file.isFile() ) - { - addResolved( artifact ); - return new FileInputStream( file ); + if (file != null && file.isFile()) { + addResolved(artifact); + return new FileInputStream(file); } - throw new ArtifactNotFoundException( artifact ); - } - catch ( org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) - { - throw new ArtifactNotFoundException( artifact, e ); - } - catch ( ArtifactResolutionException e ) - { - throw new IOException( e.getMessage(), e ); + throw new ArtifactNotFoundException(artifact); + } catch (org.apache.maven.artifact.resolver.ArtifactNotFoundException e) { + throw new ArtifactNotFoundException(artifact, e); + } catch (ArtifactResolutionException e) { + throw new IOException(e.getMessage(), e); } } /** * {@inheritDoc} */ - public void set( Artifact artifact, InputStream content ) - throws IOException - { + public void set(Artifact artifact, InputStream content) throws IOException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { - path = StringUtils.strip( path, "/" ); - int index = path.lastIndexOf( '/' ); - int index2 = index == -1 ? -1 : path.lastIndexOf( '/', index - 1 ); + public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { + path = StringUtils.strip(path, "/"); + int index = path.lastIndexOf('/'); + int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); - String version = index2 == -1 ? null : path.substring( index + 1 ); - String artifactId = index2 == -1 ? null : path.substring( index2 + 1, index ); - String groupId = index2 == -1 ? null : path.substring( 0, index2 ).replace( '/', '.' ); + String version = index2 == -1 ? null : path.substring(index + 1); + String artifactId = index2 == -1 ? null : path.substring(index2 + 1, index); + String groupId = index2 == -1 ? null : path.substring(0, index2).replace('/', '.'); Metadata metadata = new Metadata(); boolean foundSomething = false; // is this path a groupId:artifactId pair? - if ( version != null && version.endsWith( "-SNAPSHOT" ) && !StringUtils.isEmpty( artifactId ) - && !StringUtils.isEmpty( groupId ) ) - { - org.apache.maven.artifact.Artifact artifact = - artifactFactory.createDependencyArtifact( groupId, artifactId, - VersionRange.createFromVersion( version ), "pom", null, - "compile" ); + if (version != null + && version.endsWith("-SNAPSHOT") + && !StringUtils.isEmpty(artifactId) + && !StringUtils.isEmpty(groupId)) { + org.apache.maven.artifact.Artifact artifact = artifactFactory.createDependencyArtifact( + groupId, artifactId, VersionRange.createFromVersion(version), "pom", null, "compile"); SnapshotArtifactRepositoryMetadata artifactRepositoryMetadata = - new SnapshotArtifactRepositoryMetadata( artifact ); - try - { - repositoryMetadataManager.resolve( artifactRepositoryMetadata, remoteRepositories, localRepository ); + new SnapshotArtifactRepositoryMetadata(artifact); + try { + repositoryMetadataManager.resolve(artifactRepositoryMetadata, remoteRepositories, localRepository); Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata(); - if ( artifactMetadata.getVersioning() != null - && artifactMetadata.getVersioning().getSnapshot() != null ) - { + if (artifactMetadata.getVersioning() != null + && artifactMetadata.getVersioning().getSnapshot() != null) { foundSomething = true; - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); - metadata.setVersion( version ); - metadata.merge( artifactMetadata ); + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); + metadata.setVersion(version); + metadata.merge(artifactMetadata); } - try - { - if ( artifactMetadata.getVersioning() != null - && !artifactMetadata.getVersioning().getSnapshotVersions().isEmpty() ) - { + try { + if (artifactMetadata.getVersioning() != null + && !artifactMetadata + .getVersioning() + .getSnapshotVersions() + .isEmpty()) { // TODO up to and including Maven 3.0.3 we do not get a populated SnapshotVersions - for ( SnapshotVersion v : artifactMetadata.getVersioning().getSnapshotVersions() ) - { - metadata.getVersioning().addSnapshotVersion( v ); - if ( v.getVersion().endsWith( "-SNAPSHOT" ) ) - { - addResolved( - new Artifact( groupId, artifactId, version, v.getClassifier(), v.getExtension() ) ); + for (SnapshotVersion v : + artifactMetadata.getVersioning().getSnapshotVersions()) { + metadata.getVersioning().addSnapshotVersion(v); + if (v.getVersion().endsWith("-SNAPSHOT")) { + addResolved(new Artifact( + groupId, artifactId, version, v.getClassifier(), v.getExtension())); } } } - } - catch ( NoSuchMethodError e ) - { + } catch (NoSuchMethodError e) { // ignore Maven 2.x doesn't give us the info } - } - catch ( RepositoryMetadataResolutionException e ) - { - log.debug( e ); + } catch (RepositoryMetadataResolutionException e) { + log.debug(e); } } // is this path a groupId:artifactId pair? - artifactId = index == -1 ? null : path.substring( index + 1 ); - groupId = index == -1 ? null : path.substring( 0, index ).replace( '/', '.' ); - if ( !StringUtils.isEmpty( artifactId ) && !StringUtils.isEmpty( groupId ) ) - { + artifactId = index == -1 ? null : path.substring(index + 1); + groupId = index == -1 ? null : path.substring(0, index).replace('/', '.'); + if (!StringUtils.isEmpty(artifactId) && !StringUtils.isEmpty(groupId)) { org.apache.maven.artifact.Artifact artifact = - artifactFactory.createDependencyArtifact( groupId, artifactId, anyVersion, "pom", null, "compile" ); - ArtifactRepositoryMetadata artifactRepositoryMetadata = new ArtifactRepositoryMetadata( artifact ); - try - { - repositoryMetadataManager.resolve( artifactRepositoryMetadata, remoteRepositories, localRepository ); + artifactFactory.createDependencyArtifact(groupId, artifactId, anyVersion, "pom", null, "compile"); + ArtifactRepositoryMetadata artifactRepositoryMetadata = new ArtifactRepositoryMetadata(artifact); + try { + repositoryMetadataManager.resolve(artifactRepositoryMetadata, remoteRepositories, localRepository); final Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata(); - if ( artifactMetadata.getVersioning() != null ) - { + if (artifactMetadata.getVersioning() != null) { foundSomething = true; - if ( StringUtils.isEmpty( metadata.getGroupId() ) ) - { - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); + if (StringUtils.isEmpty(metadata.getGroupId())) { + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); } - metadata.merge( artifactMetadata ); - for ( String v : artifactMetadata.getVersioning().getVersions() ) - { - addResolved( path + "/" + v ); + metadata.merge(artifactMetadata); + for (String v : artifactMetadata.getVersioning().getVersions()) { + addResolved(path + "/" + v); } } - } - catch ( RepositoryMetadataResolutionException e ) - { - log.debug( e ); + } catch (RepositoryMetadataResolutionException e) { + log.debug(e); } } // if this path a groupId on its own? - groupId = path.replace( '/', '.' ); - final GroupRepositoryMetadata groupRepositoryMetadata = new GroupRepositoryMetadata( groupId ); - try - { - repositoryMetadataManager.resolve( groupRepositoryMetadata, remotePluginRepositories, localRepository ); + groupId = path.replace('/', '.'); + final GroupRepositoryMetadata groupRepositoryMetadata = new GroupRepositoryMetadata(groupId); + try { + repositoryMetadataManager.resolve(groupRepositoryMetadata, remotePluginRepositories, localRepository); foundSomething = true; - metadata.merge( groupRepositoryMetadata.getMetadata() ); - for ( Plugin plugin : groupRepositoryMetadata.getMetadata().getPlugins() ) - { - addResolved( path + "/" + plugin.getArtifactId() ); + metadata.merge(groupRepositoryMetadata.getMetadata()); + for (Plugin plugin : groupRepositoryMetadata.getMetadata().getPlugins()) { + addResolved(path + "/" + plugin.getArtifactId()); } - } - catch ( RepositoryMetadataResolutionException e ) - { - log.debug( e ); + } catch (RepositoryMetadataResolutionException e) { + log.debug(e); } - if ( !foundSomething ) - { - throw new MetadataNotFoundException( path ); + if (!foundSomething) { + throw new MetadataNotFoundException(path); } - addResolved( path ); + addResolved(path); return metadata; } /** * {@inheritDoc} */ - public long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { - Metadata metadata = getMetadata( path ); - if ( metadata != null ) - { - if ( !StringUtils.isEmpty( metadata.getGroupId() ) || !StringUtils.isEmpty( metadata.getArtifactId() ) - || !StringUtils.isEmpty( metadata.getVersion() ) - || ( metadata.getPlugins() != null && !metadata.getPlugins().isEmpty() ) || ( - metadata.getVersioning() != null && ( !StringUtils.isEmpty( metadata.getVersioning().getLastUpdated() ) - || !StringUtils.isEmpty( metadata.getVersioning().getLatest() ) - || !StringUtils.isEmpty( metadata.getVersioning().getRelease() ) - || ( metadata.getVersioning().getVersions() != null - && !metadata.getVersioning().getVersions().isEmpty() ) || ( metadata.getVersioning().getSnapshot() - != null ) ) ) ) - { + public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { + Metadata metadata = getMetadata(path); + if (metadata != null) { + if (!StringUtils.isEmpty(metadata.getGroupId()) + || !StringUtils.isEmpty(metadata.getArtifactId()) + || !StringUtils.isEmpty(metadata.getVersion()) + || (metadata.getPlugins() != null && !metadata.getPlugins().isEmpty()) + || (metadata.getVersioning() != null + && (!StringUtils.isEmpty(metadata.getVersioning().getLastUpdated()) + || !StringUtils.isEmpty( + metadata.getVersioning().getLatest()) + || !StringUtils.isEmpty( + metadata.getVersioning().getRelease()) + || (metadata.getVersioning().getVersions() != null + && !metadata.getVersioning() + .getVersions() + .isEmpty()) + || (metadata.getVersioning().getSnapshot() != null)))) { return System.currentTimeMillis(); } } - throw new MetadataNotFoundException( path ); + throw new MetadataNotFoundException(path); } - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { return archetypeManager.getDefaultLocalCatalog(); } - public long getArchetypeCatalogLastModified() - throws IOException, ArchetypeCatalogNotFoundException - { - if ( archetypeManager.getDefaultLocalCatalog() != null ) - { + public long getArchetypeCatalogLastModified() throws IOException, ArchetypeCatalogNotFoundException { + if (archetypeManager.getDefaultLocalCatalog() != null) { return System.currentTimeMillis(); - } - else - { + } else { throw new ArchetypeCatalogNotFoundException(); } } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractMRMMojo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractMRMMojo.java index 913475b2..19962faf 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractMRMMojo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/AbstractMRMMojo.java @@ -1,7 +1,5 @@ package org.codehaus.mojo.mrm.plugin; -import java.util.List; - /* * Copyright 2011 Stephen Connolly * @@ -18,6 +16,8 @@ * limitations under the License. */ +import java.util.List; + import org.apache.maven.archetype.ArchetypeManager; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; @@ -40,13 +40,11 @@ * * @since 1.0 */ -public abstract class AbstractMRMMojo - extends AbstractMojo -{ +public abstract class AbstractMRMMojo extends AbstractMojo { /** * The Maven project. */ - @Parameter( defaultValue = "${project}", required = true, readonly = true ) + @Parameter(defaultValue = "${project}", required = true, readonly = true) protected MavenProject project; /** @@ -58,19 +56,19 @@ public abstract class AbstractMRMMojo /** * The remote repositories. */ - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) protected List remoteArtifactRepositories; /** * The remote pluginRepositories. */ - @Parameter( defaultValue = "${project.pluginArtifactRepositories}", readonly = true ) + @Parameter(defaultValue = "${project.pluginArtifactRepositories}", readonly = true) protected List remotePluginRepositories; /** * The local repository. */ - @Parameter( defaultValue = "${localRepository}", readonly = true ) + @Parameter(defaultValue = "${localRepository}", readonly = true) protected ArtifactRepository localRepository; /** @@ -94,25 +92,25 @@ public abstract class AbstractMRMMojo /** * The Maven Session Object */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) protected MavenSession session; /** * This plugins descriptor. */ - @Parameter( defaultValue = "${plugin}", required = true, readonly = true ) + @Parameter(defaultValue = "${plugin}", required = true, readonly = true) protected PluginDescriptor pluginDescriptor; /** * This mojo's execution. */ - @Parameter( defaultValue = "${mojoExecution}", readonly = true, required = true ) + @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true) protected MojoExecution mojoExecution; /** * If true, execution of the plugin is skipped. */ - @Parameter( property = "mrm.skip", defaultValue = "false" ) + @Parameter(property = "mrm.skip", defaultValue = "false") protected boolean skip; /** @@ -121,35 +119,29 @@ public abstract class AbstractMRMMojo * @throws MojoExecutionException If there is an exception occuring during the execution of the plugin. * @throws MojoFailureException If there is an exception occuring during the execution of the plugin. */ - public final void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping invocation per configuration." - + " If this is incorrect, ensure the skip parameter is not set to true." ); + public final void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping invocation per configuration." + + " If this is incorrect, ensure the skip parameter is not set to true."); return; } - if ( pluginDescriptor == null ) - { + if (pluginDescriptor == null) { pluginDescriptor = mojoExecution.getMojoDescriptor().getPluginDescriptor(); } doExecute(); } - protected MojoExecution getMojoExecution() - { + protected MojoExecution getMojoExecution() { return mojoExecution; } - + /** * Performs this plugin's action. * * @throws MojoExecutionException If there is an exception occuring during the execution of the plugin. * @throws MojoFailureException If there is an exception occuring during the execution of the plugin. */ - protected abstract void doExecute() - throws MojoExecutionException, MojoFailureException; + protected abstract void doExecute() throws MojoExecutionException, MojoFailureException; /** * Creates an {@link org.codehaus.mojo.mrm.api.maven.ArtifactStore} that fetches from the repositories available to @@ -158,10 +150,16 @@ protected abstract void doExecute() * @return an {@link org.codehaus.mojo.mrm.api.maven.ArtifactStore} that fetches from the repositories available to * Maven itself. */ - protected ProxyArtifactStore createProxyArtifactStore() - { - return new ProxyArtifactStore( repositoryMetadataManager, remoteArtifactRepositories, remotePluginRepositories, - localRepository, artifactFactory, artifactResolver, archetypeManager, getLog() ); + protected ProxyArtifactStore createProxyArtifactStore() { + return new ProxyArtifactStore( + repositoryMetadataManager, + remoteArtifactRepositories, + remotePluginRepositories, + localRepository, + artifactFactory, + artifactResolver, + archetypeManager, + getLog()); } /** @@ -169,8 +167,7 @@ protected ProxyArtifactStore createProxyArtifactStore() * * @return a new {@link FactoryHelper} instance for injection into anything that needs one. */ - protected FactoryHelper createFactoryHelper() - { + protected FactoryHelper createFactoryHelper() { return new FactoryHelperImpl(); } @@ -179,70 +176,60 @@ protected FactoryHelper createFactoryHelper() * * @since 1.0 */ - private class FactoryHelperImpl - implements FactoryHelper - { + private class FactoryHelperImpl implements FactoryHelper { /** * {@inheritDoc} */ - public RepositoryMetadataManager getRepositoryMetadataManager() - { + public RepositoryMetadataManager getRepositoryMetadataManager() { return repositoryMetadataManager; } /** * {@inheritDoc} */ - public List getRemotePluginRepositories() - { + public List getRemotePluginRepositories() { return remotePluginRepositories; } /** * {@inheritDoc} */ - public ArtifactRepository getLocalRepository() - { + public ArtifactRepository getLocalRepository() { return localRepository; } /** * {@inheritDoc} */ - public ArtifactFactory getArtifactFactory() - { + public ArtifactFactory getArtifactFactory() { return artifactFactory; } /** * {@inheritDoc} */ - public List getRemoteArtifactRepositories() - { + public List getRemoteArtifactRepositories() { return remoteArtifactRepositories; } /** * {@inheritDoc} */ - public ArtifactResolver getArtifactResolver() - { + public ArtifactResolver getArtifactResolver() { return artifactResolver; } /** * {@inheritDoc} */ - public ArchetypeManager getArchetypeManager() - { + public ArchetypeManager getArchetypeManager() { return archetypeManager; } /** * {@inheritDoc} */ - public Log getLog() - { + public Log getLog() { return AbstractMRMMojo.this.getLog(); } } 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 3cd51b00..09c85e95 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 @@ -16,6 +16,9 @@ * limitations under the License. */ +import java.util.ArrayList; +import java.util.List; + import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; @@ -24,21 +27,16 @@ import org.codehaus.mojo.mrm.impl.maven.ArtifactStoreFileSystem; import org.codehaus.mojo.mrm.impl.maven.CompositeArtifactStore; -import java.util.ArrayList; -import java.util.List; - /** * Common base class for the mojos that start a repository. * * @since 1.0 */ -public abstract class AbstractStartMojo - extends AbstractMRMMojo -{ +public abstract class AbstractStartMojo extends AbstractMRMMojo { /** * The port to serve the repository on. If not specified a random port will be used. */ - @Parameter( property = "mrm.port" ) + @Parameter(property = "mrm.port") private int port; /** @@ -52,7 +50,7 @@ public abstract class AbstractStartMojo * * @since 1.4.0 */ - @Parameter( property = "mrm.basePath", defaultValue = "/" ) + @Parameter(property = "mrm.basePath", defaultValue = "/") private String basePath; /** @@ -70,7 +68,7 @@ public abstract class AbstractStartMojo * * @since 1.5.0 */ - @Parameter( property = "mrm.debugServer", defaultValue = "false" ) + @Parameter(property = "mrm.debugServer", defaultValue = "false") private boolean debugServer; /** @@ -79,13 +77,14 @@ public abstract class AbstractStartMojo * @param artifactStore the artifact store to serve. * @return the file system server. */ - protected FileSystemServer createFileSystemServer( ArtifactStore artifactStore ) - { - return new FileSystemServer( ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ), - Math.max( 0, Math.min( port, 65535 ) ), - basePath, - new AutoDigestFileSystem( new ArtifactStoreFileSystem( artifactStore ) ), - getSettingsServletPath(), debugServer ); + protected FileSystemServer createFileSystemServer(ArtifactStore artifactStore) { + return new FileSystemServer( + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()), + Math.max(0, Math.min(port, 65535)), + basePath, + new AutoDigestFileSystem(new ArtifactStoreFileSystem(artifactStore)), + getSettingsServletPath(), + debugServer); } /** @@ -93,8 +92,7 @@ protected FileSystemServer createFileSystemServer( ArtifactStore artifactStore ) * * @return the servlet path to the settings file of {@code null} */ - protected String getSettingsServletPath() - { + protected String getSettingsServletPath() { return null; } @@ -104,32 +102,25 @@ protected String getSettingsServletPath() * @return an artifact store. * @throws org.apache.maven.plugin.MojoExecutionException if the configuration is invalid. */ - protected ArtifactStore createArtifactStore() - throws MojoExecutionException - { - if ( repositories == null ) - { - getLog().info( "Configuring Mock Repository Manager to proxy through this Maven instance" ); + protected ArtifactStore createArtifactStore() throws MojoExecutionException { + if (repositories == null) { + getLog().info("Configuring Mock Repository Manager to proxy through this Maven instance"); return createProxyArtifactStore(); } - getLog().info( "Configuring Mock Repository Manager..." ); + getLog().info("Configuring Mock Repository Manager..."); List stores = new ArrayList<>(); - if ( repositories == null || repositories.length == 0 ) - { + if (repositories == null || repositories.length == 0) { repositories = new ArtifactStoreFactory[] {new ProxyRepo()}; } FactoryHelper helper = createFactoryHelper(); - for ( ArtifactStoreFactory artifactStoreFactory : repositories ) - { - if ( artifactStoreFactory instanceof FactoryHelperRequired ) - { - ( (FactoryHelperRequired) artifactStoreFactory ).setFactoryHelper( helper ); + for (ArtifactStoreFactory artifactStoreFactory : repositories) { + if (artifactStoreFactory instanceof FactoryHelperRequired) { + ((FactoryHelperRequired) artifactStoreFactory).setFactoryHelper(helper); } - getLog().info( " " + artifactStoreFactory.toString() ); - stores.add( artifactStoreFactory.newInstance() ); + getLog().info(" " + artifactStoreFactory.toString()); + stores.add(artifactStoreFactory.newInstance()); } - ArtifactStore[] artifactStores = stores.toArray( new ArtifactStore[0] ); - return artifactStores.length == 1 ? artifactStores[0] : new CompositeArtifactStore( artifactStores ); + 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/ConsoleScanner.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ConsoleScanner.java index f8049fea..2b758867 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ConsoleScanner.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ConsoleScanner.java @@ -21,9 +21,7 @@ /** * A thread that waits for the user to press a key. */ -public class ConsoleScanner - extends Thread -{ +public class ConsoleScanner extends Thread { /** * The guard for {@link #finished}. */ @@ -39,48 +37,34 @@ public class ConsoleScanner /** * creates a new instance. */ - public ConsoleScanner() - { - setName( "Console scanner" ); - setDaemon( true ); + public ConsoleScanner() { + setName("Console scanner"); + setDaemon(true); } /** * {@inheritDoc} */ - public void run() - { - try - { - synchronized ( lock ) - { - try - { - while ( !finished ) - { + public void run() { + try { + synchronized (lock) { + try { + while (!finished) { checkSystemInput(); - try - { - lock.wait( 500 ); - } - catch ( InterruptedException e ) - { + try { + lock.wait(500); + } catch (InterruptedException e) { // ignore } } - } - finally - { - synchronized ( lock ) - { + } finally { + synchronized (lock) { finished = true; lock.notifyAll(); } } } - } - catch ( IOException e ) - { + } catch (IOException e) { // ignore } } @@ -90,28 +74,19 @@ public void run() * * @throws IOException if something went wrong. */ - private void checkSystemInput() - throws IOException - { - while ( System.in.available() > 0 ) - { + private void checkSystemInput() throws IOException { + while (System.in.available() > 0) { int input = System.in.read(); - if ( input >= 0 ) - { + if (input >= 0) { char c = (char) input; - if ( c == '\n' ) - { - synchronized ( lock ) - { + if (c == '\n') { + synchronized (lock) { finished = true; lock.notifyAll(); } } - } - else - { - synchronized ( lock ) - { + } else { + synchronized (lock) { finished = true; lock.notifyAll(); } @@ -124,13 +99,9 @@ private void checkSystemInput() * * @throws InterruptedException if interrupted. */ - public void waitForFinished() - throws InterruptedException - { - synchronized ( lock ) - { - while ( !finished ) - { + public void waitForFinished() throws InterruptedException { + synchronized (lock) { + while (!finished) { lock.wait(); } } 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 022c68a5..8aeb6a9a 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 @@ -16,6 +16,9 @@ * limitations under the License. */ +import java.net.InetAddress; +import java.net.UnknownHostException; + import org.apache.maven.plugin.MojoExecutionException; import org.codehaus.mojo.mrm.api.FileSystem; import org.codehaus.mojo.mrm.servlet.FileSystemServlet; @@ -26,14 +29,10 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import java.net.InetAddress; -import java.net.UnknownHostException; - /** * A file system server. */ -public class FileSystemServer -{ +public class FileSystemServer { /** * Guard for {@link #starting}, {@link #started}, {@link #finishing}, {@link #finished}, {@link #boundPort} @@ -121,13 +120,17 @@ public class FileSystemServer * @param fileSystem the file system to serve. * @param debugServer the server debug mode */ - public FileSystemServer( String name, int port, String contextPath, FileSystem fileSystem, - String settingsServletPath, boolean debugServer ) - { + public FileSystemServer( + String name, + int port, + String contextPath, + FileSystem fileSystem, + String settingsServletPath, + boolean debugServer) { this.name = name; this.fileSystem = fileSystem; this.requestedPort = port; - this.contextPath = sanitizeContextPath( contextPath ); + this.contextPath = sanitizeContextPath(contextPath); this.settingsServletPath = settingsServletPath; this.debugServer = debugServer; } @@ -139,19 +142,15 @@ public FileSystemServer( String name, int port, String contextPath, FileSystem f * @param contextPath the contextPath to sanitize * @return sanitized {@code contextPath} */ - static String sanitizeContextPath( String contextPath ) - { - if ( contextPath == null || contextPath.isEmpty() || contextPath.equals( "/" ) ) - { + static String sanitizeContextPath(String contextPath) { + if (contextPath == null || contextPath.isEmpty() || contextPath.equals("/")) { return "/"; } - if ( !contextPath.startsWith( "/" ) ) - { + if (!contextPath.startsWith("/")) { return "/" + contextPath; } - if ( contextPath.endsWith( "/" ) ) - { - return contextPath.substring( 0, contextPath.length() - 1 ); + if (contextPath.endsWith("/")) { + return contextPath.substring(0, contextPath.length() - 1); } return contextPath; } @@ -162,13 +161,9 @@ static String sanitizeContextPath( String contextPath ) * * @throws MojoExecutionException if the file system server could not be started. */ - public void ensureStarted() - throws MojoExecutionException - { - synchronized ( lock ) - { - if ( started || starting ) - { + public void ensureStarted() throws MojoExecutionException { + synchronized (lock) { + if (started || starting) { return; } starting = true; @@ -176,39 +171,30 @@ public void ensureStarted() finished = false; finishing = false; } - Thread worker = new Thread( new Worker(), "FileSystemServer[" + name + "]" ); - worker.setDaemon( true ); + Thread worker = new Thread(new Worker(), "FileSystemServer[" + name + "]"); + worker.setDaemon(true); worker.start(); - try - { - synchronized ( lock ) - { - while ( starting && !started && !finished && !finishing ) - { + try { + synchronized (lock) { + while (starting && !started && !finished && !finishing) { lock.wait(); } - if ( problem != null ) - { + if (problem != null) { throw problem; } } - } - catch ( Exception e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + } catch (Exception e) { + throw new MojoExecutionException(e.getMessage(), e); } } - /** * Returns true if and only if the file system server is finished. * * @return true if and only if the file system server is finished. */ - public boolean isFinished() - { - synchronized ( lock ) - { + public boolean isFinished() { + synchronized (lock) { return finished; } } @@ -218,10 +204,8 @@ public boolean isFinished() * * @return true if and only if the file system server is started. */ - public boolean isStarted() - { - synchronized ( lock ) - { + public boolean isStarted() { + synchronized (lock) { return finished; } } @@ -229,10 +213,8 @@ public boolean isStarted() /** * Signal the file system server to shut down. */ - public void finish() - { - synchronized ( lock ) - { + public void finish() { + synchronized (lock) { finishing = true; lock.notifyAll(); } @@ -243,13 +225,9 @@ public void finish() * * @throws InterruptedException if interrupted. */ - public void waitForFinished() - throws InterruptedException - { - synchronized ( lock ) - { - while ( !finished ) - { + public void waitForFinished() throws InterruptedException { + synchronized (lock) { + while (!finished) { lock.wait(); } } @@ -260,10 +238,8 @@ public void waitForFinished() * * @return the port that the file system server is/will server on. */ - public int getPort() - { - synchronized ( lock ) - { + public int getPort() { + synchronized (lock) { return started ? boundPort : requestedPort; } } @@ -273,9 +249,8 @@ public int getPort() * * @return the root url that the file system server is/will server on. */ - public String getUrl() - { - return "http://localhost:" + getPort() + ( contextPath.equals( "/" ) ? "" : contextPath ); + public String getUrl() { + return "http://localhost:" + getPort() + (contextPath.equals("/") ? "" : contextPath); } /** @@ -284,81 +259,60 @@ public String getUrl() * @return the scheme + raw IP address + port + contextPath * @throws UnknownHostException if the local host name could not be resolved into an address. */ - public String getRemoteUrl() throws UnknownHostException - { + public String getRemoteUrl() throws UnknownHostException { return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + getPort() - + ( contextPath.equals( "/" ) ? "" : contextPath ); + + (contextPath.equals("/") ? "" : contextPath); } /** * The work to monitor and control the Jetty instance that hosts the file system. */ - private final class Worker - implements Runnable - { + private final class Worker implements Runnable { /** * {@inheritDoc} */ - public void run() - { - try - { - Logger serverLogger = new ServerLogger( debugServer ); - Log.setLog( serverLogger ); + public void run() { + try { + Logger serverLogger = new ServerLogger(debugServer); + Log.setLog(serverLogger); Log.initialized(); - Server server = new Server( requestedPort ); + Server server = new Server(requestedPort); - try - { + try { ServletContextHandler context = new ServletContextHandler(); - context.setContextPath( contextPath ); - context.addServlet( new ServletHolder( new FileSystemServlet( fileSystem, settingsServletPath ) ), - "/*" ); - server.setHandler( context ); + context.setContextPath(contextPath); + context.addServlet(new ServletHolder(new FileSystemServlet(fileSystem, settingsServletPath)), "/*"); + server.setHandler(context); server.start(); - synchronized ( lock ) - { - boundPort = ( (ServerConnector) server.getConnectors()[0] ).getLocalPort(); + synchronized (lock) { + boundPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort(); starting = false; started = true; lock.notifyAll(); } - } - catch ( Exception e ) - { - synchronized ( lock ) - { + } catch (Exception e) { + synchronized (lock) { problem = e; } - serverLogger.warn( e ); + serverLogger.warn(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 } } } server.stop(); server.join(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore - } - finally - { - synchronized ( lock ) - { + } finally { + synchronized (lock) { started = false; starting = false; finishing = false; @@ -369,5 +323,4 @@ public void run() } } } - } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ProxyRepo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ProxyRepo.java index 0def4252..53151d68 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ProxyRepo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ProxyRepo.java @@ -16,7 +16,6 @@ * limitations under the License. */ - import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.codehaus.mojo.mrm.maven.ProxyArtifactStore; @@ -25,9 +24,7 @@ * * @since 1.0 */ -public class ProxyRepo - implements ArtifactStoreFactory, FactoryHelperRequired -{ +public class ProxyRepo implements ArtifactStoreFactory, FactoryHelperRequired { /** * Our factory helper. @@ -37,33 +34,32 @@ public class ProxyRepo /** * {@inheritDoc} */ - public ArtifactStore newInstance() - { - if ( factoryHelper == null ) - { - throw new IllegalStateException( "FactoryHelper has not been set" ); + public ArtifactStore newInstance() { + if (factoryHelper == null) { + throw new IllegalStateException("FactoryHelper has not been set"); } - return new ProxyArtifactStore( factoryHelper.getRepositoryMetadataManager(), - factoryHelper.getRemoteArtifactRepositories(), - factoryHelper.getRemotePluginRepositories(), factoryHelper.getLocalRepository(), - factoryHelper.getArtifactFactory(), factoryHelper.getArtifactResolver(), - factoryHelper.getArchetypeManager(), - factoryHelper.getLog() ); + return new ProxyArtifactStore( + factoryHelper.getRepositoryMetadataManager(), + factoryHelper.getRemoteArtifactRepositories(), + factoryHelper.getRemotePluginRepositories(), + factoryHelper.getLocalRepository(), + factoryHelper.getArtifactFactory(), + factoryHelper.getArtifactResolver(), + factoryHelper.getArchetypeManager(), + factoryHelper.getLog()); } /** * {@inheritDoc} */ - public void setFactoryHelper( FactoryHelper factoryHelper ) - { + public void setFactoryHelper(FactoryHelper factoryHelper) { this.factoryHelper = factoryHelper; } /** * {@inheritDoc} */ - public String toString() - { + public String toString() { return "Proxy (source: this Maven session)"; } } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/RunMojo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/RunMojo.java index 0e2d1839..7a7235f5 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/RunMojo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/RunMojo.java @@ -33,73 +33,56 @@ *

* Starts a mock repository manager for manual testing. */ -@Mojo( name = "run", requiresProject = false, requiresDirectInvocation = true, threadSafe = true ) -public class RunMojo - extends AbstractStartMojo -{ +@Mojo(name = "run", requiresProject = false, requiresDirectInvocation = true, threadSafe = true) +public class RunMojo extends AbstractStartMojo { /** * ServletPath for the settings.xml, so it can be downloaded. */ - @Parameter( property = "mrm.settingsServletPath", defaultValue = "settings-mrm.xml" ) + @Parameter(property = "mrm.settingsServletPath", defaultValue = "settings-mrm.xml") private String settingsServletPath; /** * {@inheritDoc} */ - public void doExecute() - throws MojoExecutionException, MojoFailureException - { - if ( !session.getSettings().isInteractiveMode() ) - { + public void doExecute() throws MojoExecutionException, MojoFailureException { + if (!session.getSettings().isInteractiveMode()) { throw new MojoExecutionException( - "Cannot run a mock repository in batch mode (as there is no way to signal shutdown) " - + "use mrm:start instead" ); + "Cannot run a mock repository in batch mode (as there is no way to signal shutdown) " + + "use mrm:start instead"); } - FileSystemServer mrm = createFileSystemServer( createArtifactStore() ); - getLog().info( "Starting Mock Repository Manager" ); + FileSystemServer mrm = createFileSystemServer(createArtifactStore()); + getLog().info("Starting Mock Repository Manager"); mrm.ensureStarted(); String url = mrm.getUrl(); - try - { - getLog().info( "Mock Repository Manager " + url + " is started." ); - if ( StringUtils.isNotEmpty( settingsServletPath ) ) - { + try { + getLog().info("Mock Repository Manager " + url + " is started."); + if (StringUtils.isNotEmpty(settingsServletPath)) { String downloadUrl; - try - { + try { downloadUrl = mrm.getRemoteUrl(); - } - catch ( UnknownHostException e ) - { + } catch (UnknownHostException e) { downloadUrl = mrm.getUrl(); } - String settings = FileUtils.filename( settingsServletPath ); + String settings = FileUtils.filename(settingsServletPath); - getLog().info( - "To share this repository manager, let users download " + downloadUrl + "/" + settingsServletPath ); - getLog().info( "Maven should be started as 'mvn --settings " + settings + " [phase|goal]'" ); + getLog().info("To share this repository manager, let users download " + downloadUrl + "/" + + settingsServletPath); + getLog().info("Maven should be started as 'mvn --settings " + settings + " [phase|goal]'"); } ConsoleScanner consoleScanner = new ConsoleScanner(); consoleScanner.start(); - getLog().info( "Hit ENTER on the console to stop the Mock Repository Manager and continue the build." ); + getLog().info("Hit ENTER on the console to stop the Mock Repository Manager and continue the build."); consoleScanner.waitForFinished(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // ignore - } - finally - { - getLog().info( "Stopping Mock Repository Manager " + url ); + } finally { + getLog().info("Stopping Mock Repository Manager " + url); mrm.finish(); - try - { + try { mrm.waitForFinished(); - getLog().info( "Mock Repository Manager " + url + " is stopped." ); - } - catch ( InterruptedException e ) - { + getLog().info("Mock Repository Manager " + url + " is stopped."); + } catch (InterruptedException e) { // ignore } } @@ -109,9 +92,7 @@ public void doExecute() * {@inheritDoc} */ @Override - protected String getSettingsServletPath() - { + protected String getSettingsServletPath() { return settingsServletPath; } - } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ServerLogger.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ServerLogger.java index 8caa8543..5547cffe 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ServerLogger.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/ServerLogger.java @@ -25,72 +25,58 @@ * * @author Slawomir Jaranowski */ -class ServerLogger extends Slf4jLog -{ +class ServerLogger extends Slf4jLog { private final boolean debugEnabled; - ServerLogger( boolean debugEnabled ) - { - this( ServerLogger.class.getName(), debugEnabled ); + ServerLogger(boolean debugEnabled) { + this(ServerLogger.class.getName(), debugEnabled); } - ServerLogger( String name, boolean debugEnabled ) - { - super( name ); + ServerLogger(String name, boolean debugEnabled) { + super(name); this.debugEnabled = debugEnabled; } @Override - public void debug( String msg, Object... args ) - { - if ( isDebugEnabled() ) - { - super.debug( msg, args ); + public void debug(String msg, Object... args) { + if (isDebugEnabled()) { + super.debug(msg, args); } } @Override - public void debug( String msg, long arg ) - { - if ( isDebugEnabled() ) - { - super.debug( msg, arg ); + public void debug(String msg, long arg) { + if (isDebugEnabled()) { + super.debug(msg, arg); } } @Override - public void debug( Throwable thrown ) - { - if ( isDebugEnabled() ) - { - super.debug( thrown ); + public void debug(Throwable thrown) { + if (isDebugEnabled()) { + super.debug(thrown); } } @Override - public void debug( String msg, Throwable thrown ) - { - if ( isDebugEnabled() ) - { - super.debug( msg, thrown ); + public void debug(String msg, Throwable thrown) { + if (isDebugEnabled()) { + super.debug(msg, thrown); } } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return debugEnabled; } @Override - public void setDebugEnabled( boolean enabled ) - { + public void setDebugEnabled(boolean enabled) { // do nothing } @Override - protected Logger newLogger( String fullname ) - { - return new ServerLogger( fullname, debugEnabled ); + protected Logger newLogger(String fullname) { + return new ServerLogger(fullname, debugEnabled); } } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StartMojo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StartMojo.java index f708adaf..c585b315 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StartMojo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StartMojo.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import java.util.Map; + import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; @@ -24,8 +26,6 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; -import java.util.Map; - /** * This goal is used in-situ on a Maven project to allow integration tests based on the Maven Invoker to use a custom * settings.xml and still work behind a proxy. @@ -34,40 +34,33 @@ * * Starts a mock repository manager as part of a maven build for use by integration tests. */ -@Mojo( name = "start", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresProject = false, threadSafe = true ) -public class StartMojo - extends AbstractStartMojo -{ +@Mojo(name = "start", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST, requiresProject = false, threadSafe = true) +public class StartMojo extends AbstractStartMojo { /** * The property to set the repository url to. */ - @Parameter( property = "mrm.propertyName", defaultValue = "mrm.repository.url" ) + @Parameter(property = "mrm.propertyName", defaultValue = "mrm.repository.url") private String propertyName; /** * {@inheritDoc} */ - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public void doExecute() - throws MojoExecutionException, MojoFailureException - { - FileSystemServer mrm = createFileSystemServer( createArtifactStore() ); - getLog().info( "Starting Mock Repository Manager" ); + @SuppressWarnings({"rawtypes", "unchecked"}) + public void doExecute() throws MojoExecutionException, MojoFailureException { + FileSystemServer mrm = createFileSystemServer(createArtifactStore()); + getLog().info("Starting Mock Repository Manager"); mrm.ensureStarted(); String url = mrm.getUrl(); - getLog().info( "Mock Repository Manager " + url + " is started." ); - if ( !StringUtils.isEmpty( propertyName ) ) - { - getLog().info( "Setting property '" + propertyName + "' to '" + url + "'." ); - project.getProperties().setProperty( propertyName, url ); + getLog().info("Mock Repository Manager " + url + " is started."); + if (!StringUtils.isEmpty(propertyName)) { + getLog().info("Setting property '" + propertyName + "' to '" + url + "'."); + project.getProperties().setProperty(propertyName, url); } - Map pluginContext = session.getPluginContext( pluginDescriptor, project ); - pluginContext.put( getFileSystemServerKey( getMojoExecution() ), mrm ); - } - - protected static String getFileSystemServerKey( MojoExecution mojoExecution ) - { - return FileSystemServer.class.getName() + "@" + mojoExecution.getExecutionId(); + Map pluginContext = session.getPluginContext(pluginDescriptor, project); + pluginContext.put(getFileSystemServerKey(getMojoExecution()), mrm); } + protected static String getFileSystemServerKey(MojoExecution mojoExecution) { + return FileSystemServer.class.getName() + "@" + mojoExecution.getExecutionId(); + } } diff --git a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StopMojo.java b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StopMojo.java index 82a87aaa..28bb014a 100644 --- a/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StopMojo.java +++ b/mrm-maven-plugin/src/main/java/org/codehaus/mojo/mrm/plugin/StopMojo.java @@ -16,13 +16,13 @@ * limitations under the License. */ +import java.util.Map; + import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; -import java.util.Map; - /** * This goal is used in-situ on a Maven project to allow integration tests based on the Maven Invoker to use a custom * settings.xml and still work behind a proxy. @@ -32,38 +32,30 @@ * Stops the mock repository manager started by mrm:start as part of a maven build for use * by integration tests. */ -@Mojo( name = "stop", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST, requiresProject = false, threadSafe = true ) -public class StopMojo - extends AbstractMRMMojo -{ +@Mojo(name = "stop", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST, requiresProject = false, threadSafe = true) +public class StopMojo extends AbstractMRMMojo { /** * {@inheritDoc} */ - @SuppressWarnings( "rawtypes" ) - public void doExecute() - throws MojoExecutionException, MojoFailureException - { - Map pluginContext = session.getPluginContext( pluginDescriptor, project ); + @SuppressWarnings("rawtypes") + public void doExecute() throws MojoExecutionException, MojoFailureException { + Map pluginContext = session.getPluginContext(pluginDescriptor, project); FileSystemServer mrm = - (FileSystemServer) pluginContext.get( StartMojo.getFileSystemServerKey( getMojoExecution() ) ); + (FileSystemServer) pluginContext.get(StartMojo.getFileSystemServerKey(getMojoExecution())); - if ( mrm == null ) - { - getLog().info( "Mock Repository Manager was not started" ); + if (mrm == null) { + getLog().info("Mock Repository Manager was not started"); return; } String url = mrm.getUrl(); - getLog().info( "Stopping Mock Repository Manager on " + url ); + getLog().info("Stopping Mock Repository Manager on " + url); mrm.finish(); - try - { + try { mrm.waitForFinished(); - getLog().info( "Mock Repository Manager " + url + " is stopped." ); - pluginContext.remove( FileSystemServer.class.getName() ); - } - catch ( InterruptedException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + getLog().info("Mock Repository Manager " + url + " is stopped."); + pluginContext.remove(FileSystemServer.class.getName()); + } catch (InterruptedException e) { + throw new MojoExecutionException(e.getMessage(), e); } } } diff --git a/mrm-maven-plugin/src/test/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStoreTest.java b/mrm-maven-plugin/src/test/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStoreTest.java index 9d6708aa..ac0836f2 100644 --- a/mrm-maven-plugin/src/test/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStoreTest.java +++ b/mrm-maven-plugin/src/test/java/org/codehaus/mojo/mrm/maven/ProxyArtifactStoreTest.java @@ -1,91 +1,89 @@ -package org.codehaus.mojo.mrm.maven; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.Collections; - -import org.apache.maven.archetype.ArchetypeManager; -import org.apache.maven.artifact.factory.ArtifactFactory; -import org.apache.maven.artifact.resolver.ArtifactResolver; -import org.codehaus.mojo.mrm.api.maven.Artifact; -import org.codehaus.mojo.mrm.api.maven.ArtifactNotFoundException; -import org.junit.Test; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -public class ProxyArtifactStoreTest -{ - - @Test( expected = ArtifactNotFoundException.class ) - public void verifyArtifactNotFoundExceptionOnGet() - throws Exception - { - ArtifactFactory artifactFactory = mock( ArtifactFactory.class ); - ArtifactResolver artifactResolver = mock( ArtifactResolver.class ); - ProxyArtifactStore store = - new ProxyArtifactStore( null, Collections.emptyList(), - Collections.emptyList(), null, artifactFactory, - artifactResolver, null, null ); - - doThrow( org.apache.maven.artifact.resolver.ArtifactNotFoundException.class ) - .when( artifactResolver ) - .resolve( isNull(), eq( Collections.emptyList() ), any() ); - - Artifact artifact = new Artifact( "localhost", "test", "1.0-SNAPSHOT", "pom" ); - store.get( artifact ); - } - - @Test( expected = RuntimeException.class ) - public void verifyArtifactResolutionExceptionOnGet() - throws Exception - { - ArtifactFactory artifactFactory = mock( ArtifactFactory.class ); - ArtifactResolver artifactResolver = mock( ArtifactResolver.class ); - ProxyArtifactStore store = - new ProxyArtifactStore( null, Collections.emptyList(), - Collections.emptyList(), null, artifactFactory, - artifactResolver, null, null ); - - doThrow( RuntimeException.class ) - .when( artifactResolver ) - .resolve( isNull(), eq( Collections.emptyList() ), any() ); - - Artifact artifact = new Artifact( "localhost", "test", "1.0-SNAPSHOT", "pom" ); - store.get( artifact ); - } - - @Test( expected = RuntimeException.class ) - public void verifyArchetypeCatalogNotFoundException() - throws Exception - { - ArchetypeManager archetypeManager = mock( ArchetypeManager.class ); - ProxyArtifactStore store = - new ProxyArtifactStore( null, Collections.emptyList(), - Collections.emptyList(), null, null, null, archetypeManager, - null ); - doThrow( RuntimeException.class ).when( archetypeManager ).getDefaultLocalCatalog(); - store.getArchetypeCatalog(); - } - -} +package org.codehaus.mojo.mrm.maven; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.Collections; + +import org.apache.maven.archetype.ArchetypeManager; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.codehaus.mojo.mrm.api.maven.Artifact; +import org.codehaus.mojo.mrm.api.maven.ArtifactNotFoundException; +import org.junit.Test; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +public class ProxyArtifactStoreTest { + + @Test(expected = ArtifactNotFoundException.class) + public void verifyArtifactNotFoundExceptionOnGet() throws Exception { + ArtifactFactory artifactFactory = mock(ArtifactFactory.class); + ArtifactResolver artifactResolver = mock(ArtifactResolver.class); + ProxyArtifactStore store = new ProxyArtifactStore( + null, + Collections.emptyList(), + Collections.emptyList(), + null, + artifactFactory, + artifactResolver, + null, + null); + + doThrow(org.apache.maven.artifact.resolver.ArtifactNotFoundException.class) + .when(artifactResolver) + .resolve(isNull(), eq(Collections.emptyList()), any()); + + Artifact artifact = new Artifact("localhost", "test", "1.0-SNAPSHOT", "pom"); + store.get(artifact); + } + + @Test(expected = RuntimeException.class) + public void verifyArtifactResolutionExceptionOnGet() throws Exception { + ArtifactFactory artifactFactory = mock(ArtifactFactory.class); + ArtifactResolver artifactResolver = mock(ArtifactResolver.class); + ProxyArtifactStore store = new ProxyArtifactStore( + null, + Collections.emptyList(), + Collections.emptyList(), + null, + artifactFactory, + artifactResolver, + null, + null); + + doThrow(RuntimeException.class).when(artifactResolver).resolve(isNull(), eq(Collections.emptyList()), any()); + + Artifact artifact = new Artifact("localhost", "test", "1.0-SNAPSHOT", "pom"); + store.get(artifact); + } + + @Test(expected = RuntimeException.class) + public void verifyArchetypeCatalogNotFoundException() throws Exception { + ArchetypeManager archetypeManager = mock(ArchetypeManager.class); + ProxyArtifactStore store = new ProxyArtifactStore( + null, Collections.emptyList(), Collections.emptyList(), null, null, null, archetypeManager, null); + doThrow(RuntimeException.class).when(archetypeManager).getDefaultLocalCatalog(); + store.getArchetypeCatalog(); + } +} diff --git a/mrm-servlet/pom.xml b/mrm-servlet/pom.xml index 4e540c67..c993b21f 100644 --- a/mrm-servlet/pom.xml +++ b/mrm-servlet/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -88,5 +86,4 @@ - 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 497579cf..69eda54e 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 @@ -16,12 +16,6 @@ package org.codehaus.mojo.mrm.impl; -import org.codehaus.mojo.mrm.api.DefaultDirectoryEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.Entry; -import org.codehaus.mojo.mrm.api.FileEntry; -import org.codehaus.mojo.mrm.api.FileSystem; - import java.io.IOException; import java.io.InputStream; import java.util.Arrays; @@ -29,14 +23,18 @@ import java.util.Objects; import java.util.TreeMap; +import org.codehaus.mojo.mrm.api.DefaultDirectoryEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.Entry; +import org.codehaus.mojo.mrm.api.FileEntry; +import org.codehaus.mojo.mrm.api.FileSystem; + /** * A file system that is a composite of multiple file systems. * * @since 1.0 */ -public class CompositeFileSystem - implements FileSystem -{ +public class CompositeFileSystem implements FileSystem { /** * Ensure consistent serialization. @@ -57,7 +55,7 @@ public class CompositeFileSystem * * @since 1.0 */ - private final DirectoryEntry root = new DefaultDirectoryEntry( this, null, "" ); + private final DirectoryEntry root = new DefaultDirectoryEntry(this, null, ""); /** * Creates a new {@link FileSystem} that will delegate to each of the supplied delegate {@link FileSystem} in turn @@ -65,73 +63,56 @@ public class CompositeFileSystem * * @param delegates the delegate {@link FileSystem}s (in order of preference). */ - public CompositeFileSystem( FileSystem[] delegates ) - { + public CompositeFileSystem(FileSystem[] delegates) { this.delegates = delegates; } /** * {@inheritDoc} */ - public Entry[] listEntries( DirectoryEntry directory ) - { + public Entry[] listEntries(DirectoryEntry directory) { Map result = new TreeMap<>(); - for ( FileSystem delegate : delegates ) - { - Entry[] entries = delegate.listEntries( DefaultDirectoryEntry.equivalent( delegate, directory ) ); - if ( entries == null ) - { + for (FileSystem delegate : delegates) { + Entry[] entries = delegate.listEntries(DefaultDirectoryEntry.equivalent(delegate, directory)); + if (entries == null) { continue; } - for ( Entry entry : entries ) - { - if ( result.containsKey( entry.getName() ) ) - { + for (Entry entry : entries) { + if (result.containsKey(entry.getName())) { continue; } - if ( entry instanceof DirectoryEntry ) - { - result.put( entry.getName(), - new DefaultDirectoryEntry( this, directory, entry.getName() ) ); - } - else if ( entry instanceof FileEntry ) - { - result.put( entry.getName(), new LinkFileEntry( this, directory, (FileEntry) entry ) ); + if (entry instanceof DirectoryEntry) { + result.put(entry.getName(), new DefaultDirectoryEntry(this, directory, entry.getName())); + } else if (entry instanceof FileEntry) { + result.put(entry.getName(), new LinkFileEntry(this, directory, (FileEntry) entry)); } } } - return result.values().toArray( new Entry[0] ); + return result.values().toArray(new Entry[0]); } /** * {@inheritDoc} */ - public Entry get( String path ) - { - 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 ); - + public Entry get(String path) { + 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); } /** * {@inheritDoc} */ - public long getLastModified( DirectoryEntry entry ) - throws IOException - { + public long getLastModified(DirectoryEntry entry) throws IOException { long lastModified = 0; - for ( FileSystem delegate : delegates ) - { - try - { - lastModified = Math.max( lastModified, delegate.getLastModified( entry ) ); - } - catch ( IOException e ) - { + for (FileSystem delegate : delegates) { + try { + lastModified = Math.max(lastModified, delegate.getLastModified(entry)); + } catch (IOException e) { // ignore } } @@ -141,43 +122,35 @@ public long getLastModified( DirectoryEntry entry ) /** * {@inheritDoc} */ - public DirectoryEntry getRoot() - { + public DirectoryEntry getRoot() { return root; } /** * {@inheritDoc} */ - public DirectoryEntry mkdir( DirectoryEntry parent, String name ) - { + public DirectoryEntry mkdir(DirectoryEntry parent, String name) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { + public FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public FileEntry put( DirectoryEntry parent, String name, byte[] content ) - throws IOException - { + public FileEntry put(DirectoryEntry parent, String name, byte[] content) throws IOException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} */ - public void remove( Entry entry ) - { + public void remove(Entry entry) { throw new UnsupportedOperationException(); } - } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileEntry.java index 5aa02ab5..6350cbcf 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/DiskFileEntry.java @@ -16,23 +16,21 @@ package org.codehaus.mojo.mrm.impl; -import org.codehaus.mojo.mrm.api.BaseFileEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.FileSystem; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import org.codehaus.mojo.mrm.api.BaseFileEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.FileSystem; + /** * A file entry backed by a {@link File} on a local disk. * * @since 1.0 */ -public class DiskFileEntry - extends BaseFileEntry -{ +public class DiskFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -57,9 +55,8 @@ public class DiskFileEntry * @param file the backing file. * @since 1.0 */ - public DiskFileEntry( FileSystem fileSystem, DirectoryEntry parent, File file ) - { - this( fileSystem, parent, file.getName(), file ); + public DiskFileEntry(FileSystem fileSystem, DirectoryEntry parent, File file) { + this(fileSystem, parent, file.getName(), file); } /** @@ -72,34 +69,29 @@ public DiskFileEntry( FileSystem fileSystem, DirectoryEntry parent, File file ) * @param file the backing file. * @since 1.0 */ - public DiskFileEntry( FileSystem fileSystem, DirectoryEntry parent, String name, File file ) - { - super( fileSystem, parent, name ); + public DiskFileEntry(FileSystem fileSystem, DirectoryEntry parent, String name, File file) { + super(fileSystem, parent, name); this.file = file; } /** * {@inheritDoc} */ - public long getLastModified() - { + public long getLastModified() { return file.lastModified(); } /** * {@inheritDoc} */ - public long getSize() - { + public long getSize() { return file.length(); } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new FileInputStream( file ); + public InputStream getInputStream() throws IOException { + return new FileInputStream(file); } } 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 ced54919..b7953168 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 @@ -16,6 +16,11 @@ package org.codehaus.mojo.mrm.impl; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Stack; + import org.apache.commons.io.FileUtils; import org.codehaus.mojo.mrm.api.BaseFileSystem; import org.codehaus.mojo.mrm.api.DefaultDirectoryEntry; @@ -23,19 +28,12 @@ import org.codehaus.mojo.mrm.api.Entry; import org.codehaus.mojo.mrm.api.FileEntry; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Stack; - /** * A file system hosted from a local directory. * * @since 1.0 */ -public class DiskFileSystem - extends BaseFileSystem -{ +public class DiskFileSystem extends BaseFileSystem { /** * The root directory of the file system. @@ -58,8 +56,7 @@ public class DiskFileSystem * @param readOnly true if the file system is to be read-only * @since 1.0 */ - public DiskFileSystem( File root, boolean readOnly ) - { + public DiskFileSystem(File root, boolean readOnly) { this.root = root; this.readOnly = readOnly; } @@ -70,33 +67,26 @@ public DiskFileSystem( File root, boolean readOnly ) * @param root the root of the file system. * @since 1.0 */ - public DiskFileSystem( File root ) - { - this( root, true ); + public DiskFileSystem(File root) { + this(root, true); } /** * {@inheritDoc} */ - public Entry[] listEntries( DirectoryEntry directory ) - { - File file = toFile( directory ); - if ( !file.isDirectory() ) - { + public Entry[] listEntries(DirectoryEntry directory) { + File file = toFile(directory); + if (!file.isDirectory()) { return null; } File[] files = file.listFiles(); Entry[] result = new Entry[files.length]; - for ( int i = 0; i < files.length; i++ ) - { - if ( files[i].isFile() ) - { - result[i] = new DiskFileEntry( this, directory, files[i] ); - } - else - { - result[i] = new DefaultDirectoryEntry( this, directory, files[i].getName() ); + for (int i = 0; i < files.length; i++) { + if (files[i].isFile()) { + result[i] = new DiskFileEntry(this, directory, files[i]); + } else { + result[i] = new DefaultDirectoryEntry(this, directory, files[i].getName()); } } return result; @@ -105,10 +95,8 @@ public Entry[] listEntries( DirectoryEntry directory ) /** * {@inheritDoc} */ - public long getLastModified( DirectoryEntry entry ) - throws IOException - { - return toFile( entry ).lastModified(); + public long getLastModified(DirectoryEntry entry) throws IOException { + return toFile(entry).lastModified(); } /** @@ -118,30 +106,23 @@ public long getLastModified( DirectoryEntry entry ) * @return the corresponding file. * @since 1.0 */ - private File toFile( Entry entry ) - { + private File toFile(Entry entry) { Stack stack = new Stack<>(); Entry entryRoot = entry.getFileSystem().getRoot(); - while ( entry != null && !entryRoot.equals( entry ) ) - { + while (entry != null && !entryRoot.equals(entry)) { String name = entry.getName(); - if ( "..".equals( name ) ) - { - if ( !stack.isEmpty() ) - { + if ("..".equals(name)) { + if (!stack.isEmpty()) { stack.pop(); } - } - else if ( !".".equals( name ) ) - { - stack.push( name ); + } else if (!".".equals(name)) { + stack.push(name); } entry = entry.getParent(); } File file = this.root; - while ( !stack.empty() ) - { - file = new File( file, stack.pop() ); + while (!stack.empty()) { + file = new File(file, stack.pop()); } return file; } @@ -149,44 +130,37 @@ else if ( !".".equals( name ) ) /** * {@inheritDoc} */ - public DirectoryEntry mkdir( DirectoryEntry parent, String name ) - { - if ( readOnly ) - { + public DirectoryEntry mkdir(DirectoryEntry parent, String name) { + if (readOnly) { throw new UnsupportedOperationException(); } - File file = new File( toFile( parent ), name ); + File file = new File(toFile(parent), name); file.mkdirs(); - return new DefaultDirectoryEntry( this, parent, name ); + return new DefaultDirectoryEntry(this, parent, name); } /** * {@inheritDoc} */ - public FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { - if ( readOnly ) - { + public FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { + if (readOnly) { throw new UnsupportedOperationException(); } - File parentFile = toFile( parent ); + File parentFile = toFile(parent); parentFile.mkdirs(); - File file = new File( parentFile, name ); - FileUtils.copyInputStreamToFile( content, file ); - return new DiskFileEntry( this, parent, file ); + File file = new File(parentFile, name); + FileUtils.copyInputStreamToFile(content, file); + return new DiskFileEntry(this, parent, file); } /** * {@inheritDoc} */ - public void remove( Entry entry ) - { - if ( readOnly ) - { + public void remove(Entry entry) { + if (readOnly) { throw new UnsupportedOperationException(); } - File file = toFile( entry ); + File file = toFile(entry); file.delete(); } } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/GenerateOnErrorFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/GenerateOnErrorFileEntry.java index 777b531b..11ad64e9 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/GenerateOnErrorFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/GenerateOnErrorFileEntry.java @@ -16,22 +16,20 @@ package org.codehaus.mojo.mrm.impl; +import java.io.IOException; +import java.io.InputStream; + import org.codehaus.mojo.mrm.api.BaseFileEntry; import org.codehaus.mojo.mrm.api.DirectoryEntry; import org.codehaus.mojo.mrm.api.FileEntry; import org.codehaus.mojo.mrm.api.FileSystem; -import java.io.IOException; -import java.io.InputStream; - /** * A delegating file entry that also knows how to generate the content if the entry it delegates to has problems. * * @since 1.0 */ -public class GenerateOnErrorFileEntry - extends BaseFileEntry -{ +public class GenerateOnErrorFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -74,10 +72,9 @@ public class GenerateOnErrorFileEntry * primary delegate has an error. * @since 1.0 */ - public GenerateOnErrorFileEntry( FileSystem fileSystem, DirectoryEntry parent, FileEntry delegateEntry, - FileEntry generatorEntry ) - { - super( fileSystem, parent, delegateEntry.getName() ); + public GenerateOnErrorFileEntry( + FileSystem fileSystem, DirectoryEntry parent, FileEntry delegateEntry, FileEntry generatorEntry) { + super(fileSystem, parent, delegateEntry.getName()); this.generatorEntry = generatorEntry; this.delegateEntry = delegateEntry; } @@ -85,23 +82,15 @@ public GenerateOnErrorFileEntry( FileSystem fileSystem, DirectoryEntry parent, F /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { - if ( !error ) - { - try - { + public long getLastModified() throws IOException { + if (!error) { + try { return delegateEntry.getLastModified(); - } - catch ( IOException e ) - { + } catch (IOException e) { error = true; return generatorEntry.getLastModified(); } - } - else - { + } else { return generatorEntry.getLastModified(); } } @@ -109,23 +98,15 @@ public long getLastModified() /** * {@inheritDoc} */ - public long getSize() - throws IOException - { - if ( !error ) - { - try - { + public long getSize() throws IOException { + if (!error) { + try { return delegateEntry.getSize(); - } - catch ( IOException e ) - { + } catch (IOException e) { error = true; return generatorEntry.getSize(); } - } - else - { + } else { return generatorEntry.getSize(); } } @@ -133,25 +114,16 @@ public long getSize() /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - if ( !error ) - { - try - { + public InputStream getInputStream() throws IOException { + if (!error) { + try { return delegateEntry.getInputStream(); - } - catch ( IOException e ) - { + } catch (IOException e) { error = true; return generatorEntry.getInputStream(); } - } - else - { + } else { return generatorEntry.getInputStream(); } } - } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/LinkFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/LinkFileEntry.java index 153401ae..64110c6b 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/LinkFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/LinkFileEntry.java @@ -16,22 +16,20 @@ package org.codehaus.mojo.mrm.impl; +import java.io.IOException; +import java.io.InputStream; + import org.codehaus.mojo.mrm.api.BaseFileEntry; import org.codehaus.mojo.mrm.api.DirectoryEntry; import org.codehaus.mojo.mrm.api.FileEntry; import org.codehaus.mojo.mrm.api.FileSystem; -import java.io.IOException; -import java.io.InputStream; - /** * An entry backed by a {@link FileEntry} on a (possibly different) {@link FileSystem}. * * @since 1.0 */ -public class LinkFileEntry - extends BaseFileEntry -{ +public class LinkFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -56,9 +54,8 @@ public class LinkFileEntry * @param entry the backing entry. * @since 1.0 */ - public LinkFileEntry( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ) - { - this( fileSystem, parent, entry.getName(), entry ); + public LinkFileEntry(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry) { + this(fileSystem, parent, entry.getName(), entry); } /** @@ -71,37 +68,29 @@ public LinkFileEntry( FileSystem fileSystem, DirectoryEntry parent, FileEntry en * @param entry the backing entry. * @since 1.0 */ - public LinkFileEntry( FileSystem fileSystem, DirectoryEntry parent, String name, FileEntry entry ) - { - super( fileSystem, parent, name ); + public LinkFileEntry(FileSystem fileSystem, DirectoryEntry parent, String name, FileEntry entry) { + super(fileSystem, parent, name); this.entry = entry; } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { return entry.getLastModified(); } /** * {@inheritDoc} */ - public long getSize() - throws IOException - { + public long getSize() throws IOException { return entry.getSize(); } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return entry.getInputStream(); } - } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileEntry.java index 112170ba..a3820723 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/MemoryFileEntry.java @@ -16,20 +16,18 @@ package org.codehaus.mojo.mrm.impl; -import org.codehaus.mojo.mrm.api.BaseFileEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.FileSystem; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import org.codehaus.mojo.mrm.api.BaseFileEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.FileSystem; + /** * A {@link org.codehaus.mojo.mrm.api.FileEntry} who's contents are held in memory. */ -public class MemoryFileEntry - extends BaseFileEntry -{ +public class MemoryFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -69,9 +67,8 @@ public class MemoryFileEntry * @param content the content. * @since 1.0 */ - public MemoryFileEntry( FileSystem fileSystem, DirectoryEntry parent, String name, byte[] content ) - { - super( fileSystem, parent, name ); + public MemoryFileEntry(FileSystem fileSystem, DirectoryEntry parent, String name, byte[] content) { + super(fileSystem, parent, name); this.content = content == null ? EMPTY_BYTE_ARRAY : content; this.lastModified = System.currentTimeMillis(); } @@ -79,25 +76,21 @@ public MemoryFileEntry( FileSystem fileSystem, DirectoryEntry parent, String nam /** * {@inheritDoc} */ - public long getLastModified() - { + public long getLastModified() { return lastModified; } /** * {@inheritDoc} */ - public long getSize() - { + public long getSize() { return content.length; } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new ByteArrayInputStream( content ); + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(content); } } 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 6ff626b6..1c8ebc0c 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 @@ -16,13 +16,6 @@ package org.codehaus.mojo.mrm.impl; -import org.apache.commons.io.IOUtils; -import org.codehaus.mojo.mrm.api.BaseFileSystem; -import org.codehaus.mojo.mrm.api.DefaultDirectoryEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.Entry; -import org.codehaus.mojo.mrm.api.FileEntry; - import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -31,14 +24,19 @@ import java.util.List; import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.codehaus.mojo.mrm.api.BaseFileSystem; +import org.codehaus.mojo.mrm.api.DefaultDirectoryEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.Entry; +import org.codehaus.mojo.mrm.api.FileEntry; + /** * A file system who's structure is entirely stored in memory. * * @since 1.0 */ -public class MemoryFileSystem - extends BaseFileSystem -{ +public class MemoryFileSystem extends BaseFileSystem { /** * The file system content. @@ -52,37 +50,30 @@ public class MemoryFileSystem * * @since 1.0 */ - public MemoryFileSystem() - { - contents.put( getRoot(), new ArrayList<>() ); + public MemoryFileSystem() { + contents.put(getRoot(), new ArrayList<>()); } /** * {@inheritDoc} */ - public synchronized Entry[] listEntries( DirectoryEntry directory ) - { - List entries = contents.get( directory == null ? getRoot() : directory ); - if ( entries == null ) - { + public synchronized Entry[] listEntries(DirectoryEntry directory) { + List entries = contents.get(directory == null ? getRoot() : directory); + if (entries == null) { return null; } - return entries.toArray( new Entry[0] ); + return entries.toArray(new Entry[0]); } /** * {@inheritDoc} */ - public long getLastModified( DirectoryEntry directoryEntry ) - throws IOException - { + public long getLastModified(DirectoryEntry directoryEntry) throws IOException { long lastModified = 0; - Entry[] entries = listEntries( directoryEntry ); - if ( entries != null ) - { - for ( Entry entry : entries ) - { - lastModified = Math.max( lastModified, entry.getLastModified() ); + Entry[] entries = listEntries(directoryEntry); + if (entries != null) { + for (Entry entry : entries) { + lastModified = Math.max(lastModified, entry.getLastModified()); } } @@ -92,63 +83,53 @@ public long getLastModified( DirectoryEntry directoryEntry ) /** * {@inheritDoc} */ - protected synchronized Entry get( DirectoryEntry parent, String name ) - { - List parentEntries = contents.get( parent ); - return parentEntries == null ? null : parentEntries.stream() - .filter( entry -> name.equals( entry.getName() ) ) - .findFirst() - .orElse( null ); + protected synchronized Entry get(DirectoryEntry parent, String name) { + List parentEntries = contents.get(parent); + return parentEntries == null + ? null + : parentEntries.stream() + .filter(entry -> name.equals(entry.getName())) + .findFirst() + .orElse(null); } /** * {@inheritDoc} */ - public synchronized DirectoryEntry mkdir( DirectoryEntry parent, String name ) - { - parent = getNormalizedParent( parent ); - List entries = getEntriesList( parent ); - for ( Entry entry : entries ) - { - if ( name.equals( entry.getName() ) ) - { - if ( entry instanceof DirectoryEntry ) - { + public synchronized DirectoryEntry mkdir(DirectoryEntry parent, String name) { + parent = getNormalizedParent(parent); + List entries = getEntriesList(parent); + for (Entry entry : entries) { + if (name.equals(entry.getName())) { + if (entry instanceof DirectoryEntry) { return (DirectoryEntry) entry; } return null; } } - DirectoryEntry entry = new DefaultDirectoryEntry( this, parent, name ); - entries.add( entry ); + DirectoryEntry entry = new DefaultDirectoryEntry(this, parent, name); + entries.add(entry); return entry; } /** * {@inheritDoc} */ - public synchronized FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { - parent = getNormalizedParent( parent ); - List entries = getEntriesList( parent ); - for ( Iterator i = entries.iterator(); i.hasNext(); ) - { + public synchronized FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { + parent = getNormalizedParent(parent); + List entries = getEntriesList(parent); + for (Iterator i = entries.iterator(); i.hasNext(); ) { Entry entry = i.next(); - if ( name.equals( entry.getName() ) ) - { - if ( entry instanceof FileEntry ) - { + if (name.equals(entry.getName())) { + if (entry instanceof FileEntry) { i.remove(); - } - else - { + } else { return null; } } } - FileEntry entry = new MemoryFileEntry( this, parent, name, IOUtils.toByteArray( content ) ); - entries.add( entry ); + FileEntry entry = new MemoryFileEntry(this, parent, name, IOUtils.toByteArray(content)); + entries.add(entry); return entry; } @@ -159,15 +140,11 @@ public synchronized FileEntry put( DirectoryEntry parent, String name, InputStre * @return the actual directory entry instance used as the key in {@link #contents}. * @since 1.0 */ - private DirectoryEntry getNormalizedParent( DirectoryEntry parent ) - { - if ( parent.getParent() == null ) - { + private DirectoryEntry getNormalizedParent(DirectoryEntry parent) { + if (parent.getParent() == null) { return getRoot(); - } - else - { - return mkdir( parent.getParent(), parent.getName() ); + } else { + return mkdir(parent.getParent(), parent.getName()); } } @@ -178,51 +155,40 @@ private DirectoryEntry getNormalizedParent( DirectoryEntry parent ) * @return the list of entries (never null). * @since 1.0 */ - private synchronized List getEntriesList( DirectoryEntry directory ) - { - return contents.computeIfAbsent( directory, k -> new ArrayList<>() ); + private synchronized List getEntriesList(DirectoryEntry directory) { + return contents.computeIfAbsent(directory, k -> new ArrayList<>()); } /** * {@inheritDoc} */ - public synchronized void remove( Entry entry ) - { + public synchronized void remove(Entry entry) { List entries; - if ( entry == null ) - { + if (entry == null) { return; } DirectoryEntry parent = entry.getParent(); - if ( parent == null ) - { + if (parent == null) { return; - } - else - { - entries = contents.get( parent ); - if ( entries == null ) - { + } else { + entries = contents.get(parent); + if (entries == null) { return; } } - for ( Iterator i = entries.iterator(); i.hasNext(); ) - { + for (Iterator i = entries.iterator(); i.hasNext(); ) { Entry e = i.next(); - if ( entry.equals( e ) ) - { - if ( e instanceof DirectoryEntry ) - { - Entry[] children = listEntries( (DirectoryEntry) e ); - for ( int j = children.length - 1; j >= 0; j-- ) - { - remove( children[j] ); + if (entry.equals(e)) { + if (e instanceof DirectoryEntry) { + Entry[] children = listEntries((DirectoryEntry) e); + for (int j = children.length - 1; j >= 0; j--) { + remove(children[j]); } - contents.remove( e ); + contents.remove(e); } i.remove(); return; } } } -} \ No newline at end of file +} diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/RemoteFileEntry.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/RemoteFileEntry.java index 29d4d048..f2efb305 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/RemoteFileEntry.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/RemoteFileEntry.java @@ -16,20 +16,18 @@ package org.codehaus.mojo.mrm.impl; -import org.codehaus.mojo.mrm.api.BaseFileEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.FileSystem; - import java.io.IOException; import java.io.InputStream; import java.net.URL; +import org.codehaus.mojo.mrm.api.BaseFileEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.FileSystem; + /** * A {@link org.codehaus.mojo.mrm.api.FileEntry} that is hosted at a remote {@link URL}. */ -public class RemoteFileEntry - extends BaseFileEntry -{ +public class RemoteFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -51,36 +49,29 @@ public class RemoteFileEntry * @param name the name of the entry. * @param url the content of the entry. */ - public RemoteFileEntry( FileSystem fileSystem, DirectoryEntry parent, String name, URL url ) - { - super( fileSystem, parent, name ); + public RemoteFileEntry(FileSystem fileSystem, DirectoryEntry parent, String name, URL url) { + super(fileSystem, parent, name); this.url = url; } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { return url.openConnection().getLastModified(); } /** * {@inheritDoc} */ - public long getSize() - throws IOException - { + public long getSize() throws IOException { return url.openConnection().getContentLength(); } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return url.openConnection().getInputStream(); } } 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 116b296e..0e3d8de5 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 @@ -16,8 +16,6 @@ package org.codehaus.mojo.mrm.impl; -import org.apache.maven.model.Model; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -30,21 +28,21 @@ import java.util.jar.JarOutputStream; import java.util.jar.Manifest; +import org.apache.maven.model.Model; + /** * Utility class. * * @since 1.0 */ -public final class Utils -{ +public final class Utils { /** * Do not instantiate. * * @since 1.0 */ - private Utils() - { - throw new IllegalAccessError( "Utility class" ); + private Utils() { + throw new IllegalAccessError("Utility class"); } /** @@ -58,20 +56,13 @@ private Utils() * @throws java.io.IOException if things go wrong. * @since 1.0 */ - public static InputStream asInputStream( Object content ) - throws IOException - { - if ( content instanceof byte[] ) - { - return new ByteArrayInputStream( (byte[]) content ); - } - else if ( content instanceof File ) - { - return new FileInputStream( (File) content ); - } - else - { - return new ByteArrayInputStream( content.toString().getBytes( StandardCharsets.UTF_8 ) ); + public static InputStream asInputStream(Object content) throws IOException { + if (content instanceof byte[]) { + return new ByteArrayInputStream((byte[]) content); + } else if (content instanceof File) { + return new FileInputStream((File) content); + } else { + return new ByteArrayInputStream(content.toString().getBytes(StandardCharsets.UTF_8)); } } @@ -82,16 +73,14 @@ else if ( content instanceof File ) * @throws IOException if things go wrong. * @since 1.0 */ - public static byte[] newEmptyJarContent() - throws IOException - { + public static byte[] newEmptyJarContent() throws IOException { 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" ); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + manifest.getMainAttributes().putValue("Archiver-Version", "1.0"); + manifest.getMainAttributes().putValue("Created-By", "Mock Repository Maven Plugin"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - new JarOutputStream( bos, manifest ).close(); + new JarOutputStream(bos, manifest).close(); return bos.toByteArray(); } @@ -105,23 +94,21 @@ public static byte[] newEmptyJarContent() * @throws IOException if things go wrong. * @since 1.0 */ - public static byte[] newEmptyMavenPluginJarContent( String groupId, String artifactId, String version ) - throws IOException - { + public static byte[] newEmptyMavenPluginJarContent(String groupId, String artifactId, String version) + throws IOException { 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" ); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + manifest.getMainAttributes().putValue("Archiver-Version", "1.0"); + manifest.getMainAttributes().putValue("Created-By", "Mock Repository Maven Plugin"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); - 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() ); + 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(); } return bos.toByteArray(); @@ -136,9 +123,8 @@ public static byte[] newEmptyMavenPluginJarContent( String groupId, String artif * @return the base filepath for artifacts at the specified coordinates. * @since 1.0 */ - public static String getGAVPathName( String groupId, String artifactId, String version ) - { - return getGAVPath( groupId, artifactId, version ) + '/' + artifactId + '-' + version; + public static String getGAVPathName(String groupId, String artifactId, String version) { + return getGAVPath(groupId, artifactId, version) + '/' + artifactId + '-' + version; } /** @@ -150,10 +136,9 @@ public static String getGAVPathName( String groupId, String artifactId, String v * @return the path. * @since 1.0 */ - public static String getGAVPath( String groupId, String artifactId, String version ) - { - return groupId.replace( '.', '/' ) + ( artifactId != null ? ( '/' + artifactId + ( version != null ? ( '/' - + version ) : "" ) ) : "" ); + public static String getGAVPath(String groupId, String artifactId, String version) { + return groupId.replace('.', '/') + + (artifactId != null ? ('/' + artifactId + (version != null ? ('/' + version) : "")) : ""); } /** @@ -163,11 +148,9 @@ public static String getGAVPath( String groupId, String artifactId, String versi * @return the version of the project. * @since 1.0 */ - public static String getVersion( Model model ) - { + public static String getVersion(Model model) { String version = model.getVersion(); - if ( version == null ) - { + if (version == null) { version = model.getParent().getVersion(); } return version; @@ -180,11 +163,9 @@ public static String getVersion( Model model ) * @return the artifactId of the project. * @since 1.0 */ - public static String getArtifactId( Model model ) - { + public static String getArtifactId(Model model) { String artifactId = model.getArtifactId(); - if ( artifactId == null ) - { + if (artifactId == null) { artifactId = model.getParent().getArtifactId(); } return artifactId; @@ -197,11 +178,9 @@ public static String getArtifactId( Model model ) * @return the groupId of the project. * @since 1.0 */ - public static String getGroupId( Model model ) - { + public static String getGroupId(Model model) { String groupId = model.getGroupId(); - if ( groupId == null ) - { + if (groupId == null) { groupId = model.getParent().getGroupId(); } return groupId; @@ -215,18 +194,15 @@ public static String getGroupId( Model model ) * @throws UnsupportedEncodingException if the path cannot be encoded. * @since 1.0 */ - public static String urlEncodePath( String path ) - throws UnsupportedEncodingException - { - StringBuilder buf = new StringBuilder( path.length() + 64 ); + public static String urlEncodePath(String path) throws UnsupportedEncodingException { + 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, i, Math.min( path.length(), i + 1 ) ); + for (int i = path.indexOf('/'); i != -1; i = path.indexOf('/', last)) { + buf.append(urlEncodePathSegment(path.substring(last, i))); + buf.append(path, i, Math.min(path.length(), i + 1)); last = i + 1; } - buf.append( path.substring( last ) ); + buf.append(path.substring(last)); return buf.toString(); } @@ -237,14 +213,11 @@ public static String urlEncodePath( String path ) * @return the path segment encoded for use as an URL parameter. * @since 1.0 */ - public static String urlEncodePathSegment( String pathSegment ) - { - StringBuilder buf = new StringBuilder( pathSegment.length() + 64 ); - byte[] chars = pathSegment.getBytes( StandardCharsets.UTF_8 ); - for ( byte aChar : chars ) - { - switch ( aChar ) - { + public static String urlEncodePathSegment(String pathSegment) { + StringBuilder buf = new StringBuilder(pathSegment.length() + 64); + byte[] chars = pathSegment.getBytes(StandardCharsets.UTF_8); + for (byte aChar : chars) { + switch (aChar) { case '$': case '-': case '_': @@ -317,18 +290,17 @@ public static String urlEncodePathSegment( String pathSegment ) case 'x': case 'y': case 'z': - buf.append( (char) aChar ); + buf.append((char) aChar); break; case ' ': - buf.append( '+' ); + buf.append('+'); break; default: - buf.append( '%' ); - if ( ( aChar & 0xf0 ) == 0 ) - { - buf.append( '0' ); + buf.append('%'); + if ((aChar & 0xf0) == 0) { + buf.append('0'); } - buf.append( Integer.toHexString( aChar & 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 82fff06f..989511f7 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 @@ -43,9 +43,7 @@ * * @since 1.0 */ -public class AutoDigestFileSystem - extends BaseFileSystem -{ +public class AutoDigestFileSystem extends BaseFileSystem { /** * The backing filesystem. * @@ -67,10 +65,9 @@ public class AutoDigestFileSystem * @param backing the backing file system. * @since 1.0 */ - public AutoDigestFileSystem( FileSystem backing ) - { - this( backing, - new DigestFileEntryFactory[] {new MD5DigestFileEntry.Factory(), new SHA1DigestFileEntry.Factory()} ); + public AutoDigestFileSystem(FileSystem backing) { + this(backing, new DigestFileEntryFactory[] {new MD5DigestFileEntry.Factory(), new SHA1DigestFileEntry.Factory() + }); } /** @@ -81,167 +78,125 @@ public AutoDigestFileSystem( FileSystem backing ) * @param digestFactories the digest factories. * @since 1.0 */ - public AutoDigestFileSystem( FileSystem backing, DigestFileEntryFactory[] digestFactories ) - { + public AutoDigestFileSystem(FileSystem backing, DigestFileEntryFactory[] digestFactories) { this.backing = backing; - this.digestFactories = - Collections.unmodifiableMap( Arrays.stream( digestFactories ) - .collect( Collectors.toMap( DigestFileEntryFactory::getType, - factory -> factory ) ) ); + this.digestFactories = Collections.unmodifiableMap(Arrays.stream(digestFactories) + .collect(Collectors.toMap(DigestFileEntryFactory::getType, factory -> factory))); } /** * {@inheritDoc} */ - public Entry[] listEntries( DirectoryEntry directory ) - { + public Entry[] listEntries(DirectoryEntry directory) { Map result = new TreeMap<>(); Map missing = new HashMap<>(); Set present = new HashSet<>(); - Entry[] entries = backing.listEntries( DefaultDirectoryEntry.equivalent( backing, directory ) ); - for ( Entry entry : entries ) - { + Entry[] entries = backing.listEntries(DefaultDirectoryEntry.equivalent(backing, directory)); + for (Entry entry : entries) { final String name = entry.getName(); - if ( entry instanceof FileEntry ) - { - for ( String type : digestFactories.keySet() ) - { - if ( name.endsWith( type ) ) - { - present.add( name ); - } - else - { - missing.put( name + type, (FileEntry) entry ); + if (entry instanceof FileEntry) { + for (String type : digestFactories.keySet()) { + if (name.endsWith(type)) { + present.add(name); + } else { + missing.put(name + type, (FileEntry) entry); } } - result.put( name, new LinkFileEntry( this, directory, (FileEntry) entry ) ); - } - else if ( entry instanceof DirectoryEntry ) - { - result.put( name, DefaultDirectoryEntry.equivalent( this, (DirectoryEntry) entry ) ); + result.put(name, new LinkFileEntry(this, directory, (FileEntry) entry)); + } else if (entry instanceof DirectoryEntry) { + result.put(name, DefaultDirectoryEntry.equivalent(this, (DirectoryEntry) entry)); } } - missing.keySet().removeAll( present ); - for ( Map.Entry entry : missing.entrySet() ) - { + missing.keySet().removeAll(present); + for (Map.Entry entry : missing.entrySet()) { String name = entry.getKey(); FileEntry fileEntry = entry.getValue(); - for ( DigestFileEntryFactory factory : digestFactories.values() ) - { - if ( name.endsWith( factory.getType() ) ) - { - result.put( name, factory.create( this, directory, fileEntry ) ); + for (DigestFileEntryFactory factory : digestFactories.values()) { + if (name.endsWith(factory.getType())) { + result.put(name, factory.create(this, directory, fileEntry)); } } } - return result.values().toArray( new Entry[0] ); + return result.values().toArray(new Entry[0]); } /** * {@inheritDoc} */ - public long getLastModified( DirectoryEntry entry ) - throws IOException - { - return backing.getLastModified( DefaultDirectoryEntry.equivalent( backing, entry ) ); + public long getLastModified(DirectoryEntry entry) throws IOException { + return backing.getLastModified(DefaultDirectoryEntry.equivalent(backing, entry)); } /** * {@inheritDoc} */ - public Entry get( String path ) - { - Entry entry = backing.get( path ); - if ( entry == null ) - { - if ( path.startsWith( "/" ) ) - { - path = path.substring( 1 ); + public Entry get(String path) { + Entry entry = backing.get(path); + if (entry == null) { + if (path.startsWith("/")) { + path = path.substring(1); } - if ( path.length() == 0 ) - { + if (path.length() == 0) { return getRoot(); } - String[] parts = path.split( "/" ); - if ( parts.length == 0 ) - { + String[] parts = path.split("/"); + if (parts.length == 0) { return getRoot(); } DirectoryEntry parent = getRoot(); - for ( int i = 0; i < parts.length - 1; i++ ) - { - parent = new DefaultDirectoryEntry( this, parent, parts[i] ); + for (int i = 0; i < parts.length - 1; i++) { + parent = new DefaultDirectoryEntry(this, parent, parts[i]); } String name = parts[parts.length - 1]; - for ( DigestFileEntryFactory factory : digestFactories.values() ) - { - if ( name.endsWith( factory.getType() ) ) - { - Entry shadow = - backing.get( parent.toPath() + "/" + StringUtils.removeEnd( name, factory.getType() ) ); - return factory.create( this, parent, (FileEntry) shadow ); + for (DigestFileEntryFactory factory : digestFactories.values()) { + if (name.endsWith(factory.getType())) { + Entry shadow = backing.get(parent.toPath() + "/" + StringUtils.removeEnd(name, factory.getType())); + return factory.create(this, parent, (FileEntry) shadow); } } - return get( parent, name ); - } - else - { - if ( path.startsWith( "/" ) ) - { - path = path.substring( 1 ); + return get(parent, name); + } else { + if (path.startsWith("/")) { + path = path.substring(1); } - if ( path.length() == 0 ) - { + if (path.length() == 0) { return getRoot(); } - String[] parts = path.split( "/" ); - if ( parts.length == 0 ) - { + String[] parts = path.split("/"); + if (parts.length == 0) { return getRoot(); } DirectoryEntry parent = getRoot(); - for ( int i = 0; i < parts.length - 1; i++ ) - { - parent = new DefaultDirectoryEntry( this, parent, parts[i] ); + for (int i = 0; i < parts.length - 1; i++) { + parent = new DefaultDirectoryEntry(this, parent, parts[i]); } - if ( entry instanceof FileEntry ) - { + if (entry instanceof FileEntry) { // repair filesystems that lie to us because they are caching - for ( DigestFileEntryFactory factory : digestFactories.values() ) - { - if ( entry.getName().endsWith( factory.getType() ) ) - { + for (DigestFileEntryFactory factory : digestFactories.values()) { + if (entry.getName().endsWith(factory.getType())) { Entry shadow = backing.get( - parent.toPath() + "/" + StringUtils.removeEnd( entry.getName(), factory.getType() ) ); - return new GenerateOnErrorFileEntry( this, parent, (FileEntry) entry, - factory.create( this, parent, (FileEntry) shadow ) ); + parent.toPath() + "/" + StringUtils.removeEnd(entry.getName(), factory.getType())); + return new GenerateOnErrorFileEntry( + this, parent, (FileEntry) entry, factory.create(this, parent, (FileEntry) shadow)); } } - return new LinkFileEntry( this, parent, (FileEntry) entry ); - } - else if ( entry instanceof DirectoryEntry ) - { - for ( DigestFileEntryFactory factory : digestFactories.values() ) - { - if ( entry.getName().endsWith( factory.getType() ) ) - { + return new LinkFileEntry(this, parent, (FileEntry) entry); + } else if (entry instanceof DirectoryEntry) { + for (DigestFileEntryFactory factory : digestFactories.values()) { + if (entry.getName().endsWith(factory.getType())) { Entry shadow = backing.get( - parent.toPath() + "/" + StringUtils.removeEnd( entry.getName(), factory.getType() ) ); - return factory.create( this, parent, (FileEntry) shadow ); + parent.toPath() + "/" + StringUtils.removeEnd(entry.getName(), factory.getType())); + return factory.create(this, parent, (FileEntry) shadow); } } - return new DefaultDirectoryEntry( this, parent, entry.getName() ); + return new DefaultDirectoryEntry(this, parent, entry.getName()); } } return null; } @Override - public FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { - return backing.put( parent, name, content ); + public FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { + return backing.put(parent, name, content); } - } diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/BaseDigestFileEntryFactory.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/BaseDigestFileEntryFactory.java index df3420c3..25f46991 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/BaseDigestFileEntryFactory.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/BaseDigestFileEntryFactory.java @@ -21,7 +21,4 @@ * * @since 1.0 */ -public abstract class BaseDigestFileEntryFactory - implements DigestFileEntryFactory -{ -} +public abstract class BaseDigestFileEntryFactory implements DigestFileEntryFactory {} diff --git a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/DigestFileEntryFactory.java b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/DigestFileEntryFactory.java index 028e3028..fc354da2 100644 --- a/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/DigestFileEntryFactory.java +++ b/mrm-servlet/src/main/java/org/codehaus/mojo/mrm/impl/digest/DigestFileEntryFactory.java @@ -25,8 +25,7 @@ * * @since 1.0 */ -public interface DigestFileEntryFactory -{ +public interface DigestFileEntryFactory { /** * Returns the type of digest (i.e. the file extension). * @@ -44,6 +43,5 @@ public interface DigestFileEntryFactory * @return a digest file entry. * @since 1.0 */ - FileEntry create( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ); - + FileEntry create(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry); } 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 72025c3f..4c6ada9f 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,12 +16,6 @@ package org.codehaus.mojo.mrm.impl.digest; -import org.apache.commons.lang.StringUtils; -import org.codehaus.mojo.mrm.api.BaseFileEntry; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.FileEntry; -import org.codehaus.mojo.mrm.api.FileSystem; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -29,12 +23,16 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import org.apache.commons.lang.StringUtils; +import org.codehaus.mojo.mrm.api.BaseFileEntry; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.FileEntry; +import org.codehaus.mojo.mrm.api.FileSystem; + /** * A {@link FileEntry} that corresponds to the MD5 digest of another file entry. */ -public class MD5DigestFileEntry - extends BaseFileEntry -{ +public class MD5DigestFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -59,37 +57,30 @@ public class MD5DigestFileEntry * @param entry the entry to digest. * @since 1.0 */ - public MD5DigestFileEntry( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ) - { - super( fileSystem, parent, entry.getName() + ".md5" ); + public MD5DigestFileEntry(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry) { + super(fileSystem, parent, entry.getName() + ".md5"); this.entry = entry; } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { return entry.getLastModified(); } /** * {@inheritDoc} */ - public long getSize() - throws IOException - { + public long getSize() throws IOException { return 32; } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new ByteArrayInputStream( getContent() ); + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(getContent()); } /** @@ -99,29 +90,22 @@ public InputStream getInputStream() * @throws IOException if the backing entry could not be read. * @since 1.0 */ - @SuppressWarnings( "checkstyle:MagicNumber" ) - private byte[] getContent() - throws IOException - { - try - { - MessageDigest digest = MessageDigest.getInstance( "MD5" ); + @SuppressWarnings("checkstyle:MagicNumber") + private byte[] getContent() throws IOException { + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); byte[] buffer = new byte[8192]; int read; - try ( InputStream is = entry.getInputStream() ) - { - while ( ( read = is.read( buffer ) ) > 0 ) - { - digest.update( buffer, 0, read ); + try (InputStream is = entry.getInputStream()) { + while ((read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); } } - final String md5 = StringUtils.leftPad( new BigInteger( 1, digest.digest() ).toString( 16 ), 32, "0" ); + final String md5 = StringUtils.leftPad(new BigInteger(1, digest.digest()).toString(16), 32, "0"); return md5.getBytes(); - } - catch ( NoSuchAlgorithmException e ) - { - throw new IOException( "Unable to calculate hash", e ); + } catch (NoSuchAlgorithmException e) { + throw new IOException("Unable to calculate hash", e); } } @@ -130,23 +114,19 @@ private byte[] getContent() * * @since 1.0 */ - public static class Factory - extends BaseDigestFileEntryFactory - { + public static class Factory extends BaseDigestFileEntryFactory { /** * {@inheritDoc} */ - public String getType() - { + public String getType() { return ".md5"; } /** * {@inheritDoc} */ - public FileEntry create( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ) - { - return new MD5DigestFileEntry( fileSystem, parent, entry ); + public FileEntry create(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry) { + return new MD5DigestFileEntry(fileSystem, parent, entry); } } } 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 f6568393..3ebf47fd 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 @@ -34,9 +34,7 @@ * * @since 1.0 */ -public class SHA1DigestFileEntry - extends BaseFileEntry -{ +public class SHA1DigestFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -61,37 +59,30 @@ public class SHA1DigestFileEntry * @param entry the entry to digest. * @since 1.0 */ - public SHA1DigestFileEntry( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ) - { - super( fileSystem, parent, entry.getName() + ".sha1" ); + public SHA1DigestFileEntry(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry) { + super(fileSystem, parent, entry.getName() + ".sha1"); this.entry = entry; } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { return entry.getLastModified(); } /** * {@inheritDoc} */ - public long getSize() - throws IOException - { + public long getSize() throws IOException { return 40; } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new ByteArrayInputStream( getContent() ); + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(getContent()); } /** @@ -101,25 +92,19 @@ public InputStream getInputStream() * @throws IOException if the backing entry could not be read. * @since 1.0 */ - private byte[] getContent() - throws IOException - { - try ( InputStream is = entry.getInputStream() ) - { - MessageDigest digest = MessageDigest.getInstance( "SHA1" ); + private byte[] getContent() throws IOException { + try (InputStream is = entry.getInputStream()) { + MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.reset(); byte[] buffer = new byte[8192]; int read; - while ( ( read = is.read( buffer ) ) > 0 ) - { - digest.update( buffer, 0, read ); + while ((read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); } - 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 ) - { - throw new IOException( "Unable to calculate hash", e ); + } catch (NoSuchAlgorithmException e) { + throw new IOException("Unable to calculate hash", e); } } @@ -128,23 +113,19 @@ private byte[] getContent() * * @since 1.0 */ - public static class Factory - extends BaseDigestFileEntryFactory - { + public static class Factory extends BaseDigestFileEntryFactory { /** * {@inheritDoc} */ - public String getType() - { + public String getType() { return ".sha1"; } /** * {@inheritDoc} */ - public FileEntry create( FileSystem fileSystem, DirectoryEntry parent, FileEntry entry ) - { - return new SHA1DigestFileEntry( fileSystem, parent, entry ); + public FileEntry create(FileSystem fileSystem, DirectoryEntry parent, FileEntry entry) { + return new SHA1DigestFileEntry(fileSystem, parent, entry); } } } 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 111c6d89..edd79095 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 @@ -34,9 +34,7 @@ * * @since 1.0 */ -public class ArchetypeCatalogFileEntry - extends BaseFileEntry -{ +public class ArchetypeCatalogFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -62,48 +60,37 @@ public class ArchetypeCatalogFileEntry * @param store the artifact store. * @since 1.0 */ - public ArchetypeCatalogFileEntry( FileSystem fileSystem, DirectoryEntry parent, ArtifactStore store ) - { - super( fileSystem, parent, "archetype-catalog.xml" ); + public ArchetypeCatalogFileEntry(FileSystem fileSystem, DirectoryEntry parent, ArtifactStore store) { + super(fileSystem, parent, "archetype-catalog.xml"); this.store = store; } /** * {@inheritDoc} */ - public long getSize() - throws IOException - { - try - { + public long getSize() throws IOException { + try { ArchetypeCatalog metadata = store.getArchetypeCatalog(); ArchetypeCatalogXpp3Writer writer = new ArchetypeCatalogXpp3Writer(); StringWriter stringWriter = new StringWriter(); - writer.write( stringWriter, metadata ); + writer.write(stringWriter, metadata); return stringWriter.toString().getBytes().length; - } - catch ( ArchetypeCatalogNotFoundException e ) - { - throw new IOException( "File not found", e ); + } catch (ArchetypeCatalogNotFoundException e) { + throw new IOException("File not found", e); } } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - try - { + public InputStream getInputStream() throws IOException { + try { ArchetypeCatalog metadata = store.getArchetypeCatalog(); ArchetypeCatalogXpp3Writer writer = new ArchetypeCatalogXpp3Writer(); StringWriter stringWriter = new StringWriter(); - writer.write( stringWriter, metadata ); - return new ByteArrayInputStream( stringWriter.toString().getBytes() ); - } - catch ( ArchetypeCatalogNotFoundException e ) - { + writer.write(stringWriter, metadata); + return new ByteArrayInputStream(stringWriter.toString().getBytes()); + } catch (ArchetypeCatalogNotFoundException e) { return null; } } @@ -111,17 +98,11 @@ public InputStream getInputStream() /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { - try - { + public long getLastModified() throws IOException { + try { return store.getArchetypeCatalogLastModified(); - } - catch ( ArchetypeCatalogNotFoundException e ) - { - throw new IOException( "File not found", e ); + } catch (ArchetypeCatalogNotFoundException e) { + 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 b0c5511f..d698bbc8 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 @@ -16,6 +16,9 @@ package org.codehaus.mojo.mrm.impl.maven; +import java.io.IOException; +import java.io.InputStream; + import org.codehaus.mojo.mrm.api.BaseFileEntry; import org.codehaus.mojo.mrm.api.DirectoryEntry; import org.codehaus.mojo.mrm.api.FileSystem; @@ -23,17 +26,12 @@ import org.codehaus.mojo.mrm.api.maven.ArtifactNotFoundException; import org.codehaus.mojo.mrm.api.maven.ArtifactStore; -import java.io.IOException; -import java.io.InputStream; - /** * A file entry backed by a {@link Artifact} in a {@link ArtifactStore}. * * @since 1.0 */ -public class ArtifactFileEntry - extends BaseFileEntry -{ +public class ArtifactFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -67,9 +65,8 @@ public class ArtifactFileEntry * @param store the artifact store. * @since 1.0 */ - protected ArtifactFileEntry( FileSystem fileSystem, DirectoryEntry parent, Artifact artifact, ArtifactStore store ) - { - super( fileSystem, parent, artifact.getName() ); + protected ArtifactFileEntry(FileSystem fileSystem, DirectoryEntry parent, Artifact artifact, ArtifactStore store) { + super(fileSystem, parent, artifact.getName()); this.artifact = artifact; this.store = store; } @@ -77,48 +74,33 @@ protected ArtifactFileEntry( FileSystem fileSystem, DirectoryEntry parent, Artif /** * {@inheritDoc} */ - public long getSize() - throws IOException - { - try - { - return store.getSize( artifact ); - } - catch ( ArtifactNotFoundException e ) - { - throw new IOException( "Artifact does not exist", e ); + public long getSize() throws IOException { + try { + return store.getSize(artifact); + } catch (ArtifactNotFoundException e) { + throw new IOException("Artifact does not exist", e); } } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - try - { - return store.get( artifact ); - } - catch ( ArtifactNotFoundException e ) - { - throw new IOException( "Artifact does not exist", e ); + public InputStream getInputStream() throws IOException { + try { + return store.get(artifact); + } catch (ArtifactNotFoundException e) { + throw new IOException("Artifact does not exist", e); } } /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { - try - { - return store.getLastModified( artifact ); - } - catch ( ArtifactNotFoundException e ) - { - throw new IOException( "Artifact does not exist", e ); + public long getLastModified() throws IOException { + try { + return store.getLastModified(artifact); + } catch (ArtifactNotFoundException e) { + throw new IOException("Artifact does not exist", e); } } @@ -128,8 +110,7 @@ public long getLastModified() * @return the backing artifact. * @since 1.0 */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } } 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 1f5cddce..6acc4a4d 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 @@ -50,9 +50,7 @@ * @see FileSystemArtifactStore for the oposite. * @since 1.0 */ -public class ArtifactStoreFileSystem - extends BaseFileSystem -{ +public class ArtifactStoreFileSystem extends BaseFileSystem { /** * Regex to match the groupId portion of a path. @@ -87,9 +85,9 @@ public class ArtifactStoreFileSystem * * @since 1.0 */ - /*package*/ static final Pattern METADATA = Pattern.compile( GROUP_ID_PATH_REGEX + "(maven-metadata\\.xml)" ); + /*package*/ static final Pattern METADATA = Pattern.compile(GROUP_ID_PATH_REGEX + "(maven-metadata\\.xml)"); - /*package*/ static final Pattern ARCHETYPE_CATALOG = Pattern.compile( "/archetype-catalog\\.xml" ); + /*package*/ static final Pattern ARCHETYPE_CATALOG = Pattern.compile("/archetype-catalog\\.xml"); /** * Regex to match a release artifact path. @@ -97,16 +95,15 @@ public class ArtifactStoreFileSystem * @since 1.0 */ /*package*/ static final Pattern ARTIFACT = Pattern.compile( - GROUP_ID_PATH_REGEX + ARTIFACT_ID_PATH_REGEX + VERSION_REGEX + "(\\2-\\3(-[^.]+)?\\.([^/]*))" ); + GROUP_ID_PATH_REGEX + ARTIFACT_ID_PATH_REGEX + VERSION_REGEX + "(\\2-\\3(-[^.]+)?\\.([^/]*))"); /** * Regex to match a snapshot artifact path. * * @since 1.0 */ - /*package*/ static final Pattern SNAPSHOT_ARTIFACT = Pattern.compile( - GROUP_ID_PATH_REGEX + ARTIFACT_ID_PATH_REGEX + SNAPSHOT_VERSION_REGEX - + "(\\2-(?:\\3-(?:SNAPSHOT|\\d{8}\\.\\d{6}-\\d+))(-[^.]+)?\\.([^/]*))" ); + /*package*/ static final Pattern SNAPSHOT_ARTIFACT = Pattern.compile(GROUP_ID_PATH_REGEX + ARTIFACT_ID_PATH_REGEX + + SNAPSHOT_VERSION_REGEX + "(\\2-(?:\\3-(?:SNAPSHOT|\\d{8}\\.\\d{6}-\\d+))(-[^.]+)?\\.([^/]*))"); /** * The backing {@link ArtifactStore}. @@ -121,22 +118,18 @@ public class ArtifactStoreFileSystem * @param store the backing artifact store. * @since 1.0 */ - public ArtifactStoreFileSystem( ArtifactStore store ) - { + public ArtifactStoreFileSystem(ArtifactStore store) { this.store = store; } @Override - public Entry[] listEntries( DirectoryEntry directory ) - { - if ( getRoot().equals( directory ) ) - { - Set rootGroupIds = new TreeSet<>( store.getGroupIds( "" ) ); + public Entry[] listEntries(DirectoryEntry directory) { + if (getRoot().equals(directory)) { + Set rootGroupIds = new TreeSet<>(store.getGroupIds("")); Entry[] result = new Entry[rootGroupIds.size()]; int index = 0; - for ( String name : rootGroupIds ) - { - result[index++] = new DefaultDirectoryEntry( this, getRoot(), name ); + for (String name : rootGroupIds) { + result[index++] = new DefaultDirectoryEntry(this, getRoot(), name); } return result; } @@ -144,373 +137,292 @@ public Entry[] listEntries( DirectoryEntry directory ) Set names = new HashSet<>(); String path = directory.toPath(); - try - { - store.getMetadataLastModified( path ); - MetadataFileEntry entry = new MetadataFileEntry( this, directory, path, store ); - if ( !names.contains( entry.getName() ) ) - { - result.add( entry ); - names.add( entry.getName() ); + try { + store.getMetadataLastModified(path); + MetadataFileEntry entry = new MetadataFileEntry(this, directory, path, store); + if (!names.contains(entry.getName())) { + result.add(entry); + names.add(entry.getName()); } - } - catch ( MetadataNotFoundException | IOException e ) - { + } catch (MetadataNotFoundException | IOException e) { // ignore } - String groupId = path.replace( '/', '.' ); + String groupId = path.replace('/', '.'); // get all the groupId's that start with this groupId - Set groupIds = new TreeSet<>( store.getGroupIds( groupId ) ); - for ( String name : groupIds ) - { - if ( !names.contains( name ) ) - { - result.add( new DefaultDirectoryEntry( this, directory, name ) ); - names.add( name ); + Set groupIds = new TreeSet<>(store.getGroupIds(groupId)); + for (String name : groupIds) { + if (!names.contains(name)) { + result.add(new DefaultDirectoryEntry(this, directory, name)); + names.add(name); } } // get all the artifactIds that belong to this groupId - for ( String name : store.getArtifactIds( groupId ) ) - { - if ( !names.contains( name ) ) - { - result.add( new DefaultDirectoryEntry( this, directory, name ) ); - names.add( name ); + for (String name : store.getArtifactIds(groupId)) { + if (!names.contains(name)) { + result.add(new DefaultDirectoryEntry(this, directory, name)); + names.add(name); } } DirectoryEntry parent = directory.getParent(); - if ( parent != null && !getRoot().equals( parent ) ) - { + if (parent != null && !getRoot().equals(parent)) { // get all the versions that belong to the groupId/artifactId path - groupId = parent.toPath().replace( '/', '.' ); + groupId = parent.toPath().replace('/', '.'); String artifactId = directory.getName(); - for ( String name : store.getVersions( groupId, artifactId ) ) - { - if ( !names.contains( name ) ) - { - result.add( new DefaultDirectoryEntry( this, directory, name ) ); - names.add( name ); + for (String name : store.getVersions(groupId, artifactId)) { + if (!names.contains(name)) { + result.add(new DefaultDirectoryEntry(this, directory, name)); + names.add(name); } } DirectoryEntry grandParent = parent.getParent(); - if ( grandParent != null && !getRoot().equals( grandParent ) ) - { + if (grandParent != null && !getRoot().equals(grandParent)) { // get all the versions that belong to the groupId/artifactId path - groupId = grandParent.toPath().replace( '/', '.' ); + groupId = grandParent.toPath().replace('/', '.'); artifactId = parent.getName(); String version = directory.getName(); - for ( Artifact a : store.getArtifacts( groupId, artifactId, version ) ) - { - ArtifactFileEntry entry = new ArtifactFileEntry( this, directory, a, store ); - if ( !names.contains( entry.getName() ) ) - { - result.add( entry ); - names.add( entry.getName() ); + for (Artifact a : store.getArtifacts(groupId, artifactId, version)) { + ArtifactFileEntry entry = new ArtifactFileEntry(this, directory, a, store); + if (!names.contains(entry.getName())) { + result.add(entry); + names.add(entry.getName()); } } } } // sort - result.sort( Comparator.comparing( Entry::getName ) ); - return result.toArray( new Entry[0] ); + result.sort(Comparator.comparing(Entry::getName)); + return result.toArray(new Entry[0]); } @Override - @SuppressWarnings( "checkstyle:MethodLength" ) - protected Entry get( DirectoryEntry parent, String name ) - { + @SuppressWarnings("checkstyle:MethodLength") + protected Entry get(DirectoryEntry parent, String name) { String path = "/"; - if ( StringUtils.isNotEmpty( parent.toPath() ) ) - { + if (StringUtils.isNotEmpty(parent.toPath())) { path += parent.toPath() + "/"; } path += name; - if ( "favicon.ico".equals( name ) ) - { + if ("favicon.ico".equals(name)) { return null; } - if ( METADATA.matcher( path ).matches() ) - { - MetadataFileEntry entry = new MetadataFileEntry( this, parent, parent.toPath(), store ); - try - { + if (METADATA.matcher(path).matches()) { + MetadataFileEntry entry = new MetadataFileEntry(this, parent, parent.toPath(), store); + try { entry.getLastModified(); return entry; - } - catch ( IOException e ) - { + } catch (IOException e) { return null; } - } - else if ( ARCHETYPE_CATALOG.matcher( path ).matches() ) - { - ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry( this, parent, store ); - try - { + } else if (ARCHETYPE_CATALOG.matcher(path).matches()) { + ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry(this, parent, store); + try { entry.getLastModified(); return entry; - } - catch ( IOException e ) - { + } catch (IOException e) { return null; } - } - else - { - Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher( path ); - if ( snapshotArtifact.matches() ) - { - String groupId = StringUtils.stripEnd( snapshotArtifact.group( 1 ), "/" ).replace( '/', '.' ); - String artifactId = snapshotArtifact.group( 2 ); - String version = snapshotArtifact.group( 3 ) + "-SNAPSHOT"; - Pattern rule = Pattern.compile( - "\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd( version, "-SNAPSHOT" ) - + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" - + "\\.([^/]*)" ); - Matcher matcher = rule.matcher( name ); - if ( !matcher.matches() ) - { - String classifier = snapshotArtifact.group( 5 ); - String type = snapshotArtifact.group( 6 ); - if ( classifier != null ) - { - classifier = classifier.substring( 1 ); + } else { + Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher(path); + if (snapshotArtifact.matches()) { + String groupId = + StringUtils.stripEnd(snapshotArtifact.group(1), "/").replace('/', '.'); + String artifactId = snapshotArtifact.group(2); + String version = snapshotArtifact.group(3) + "-SNAPSHOT"; + Pattern rule = + Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT") + + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" + + "\\.([^/]*)"); + Matcher matcher = rule.matcher(name); + if (!matcher.matches()) { + String classifier = snapshotArtifact.group(5); + String type = snapshotArtifact.group(6); + if (classifier != null) { + classifier = classifier.substring(1); } - if ( StringUtils.isEmpty( classifier ) ) - { + if (StringUtils.isEmpty(classifier)) { classifier = null; } - return new ArtifactFileEntry( this, parent, - new Artifact( groupId, artifactId, version, classifier, type ), - store ); + return new ArtifactFileEntry( + this, parent, new Artifact(groupId, artifactId, version, classifier, type), store); } - if ( matcher.group( 1 ).equals( "SNAPSHOT" ) ) - { - Artifact artifact = new Artifact( groupId, artifactId, version, matcher.group( 9 ), - matcher.group( 10 ) ); - try - { + if (matcher.group(1).equals("SNAPSHOT")) { + Artifact artifact = new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10)); + try { // check if artifact exist - store.getSize( artifact ); - return new ArtifactFileEntry( this, parent, artifact, store ); - } - catch ( IOException | ArtifactNotFoundException e ) - { + store.getSize(artifact); + return new ArtifactFileEntry(this, parent, artifact, store); + } catch (IOException | ArtifactNotFoundException e) { return null; } } - try - { + try { Calendar cal = new GregorianCalendar(); - cal.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - cal.set( Calendar.YEAR, Integer.parseInt( matcher.group( 2 ) ) ); - cal.set( Calendar.MONTH, Integer.parseInt( matcher.group( 3 ) ) - 1 ); - cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( matcher.group( 4 ) ) ); - cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt( matcher.group( 5 ) ) ); - cal.set( Calendar.MINUTE, Integer.parseInt( matcher.group( 6 ) ) ); - cal.set( Calendar.SECOND, Integer.parseInt( matcher.group( 7 ) ) ); - cal.set( Calendar.MILLISECOND, 0 ); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2))); + cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1); + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4))); + cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5))); + cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6))); + cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7))); + cal.set(Calendar.MILLISECOND, 0); long timestamp = cal.getTimeInMillis(); - int buildNumber = Integer.parseInt( matcher.group( 8 ) ); + int buildNumber = Integer.parseInt(matcher.group(8)); - Artifact artifact = new Artifact( groupId, artifactId, version, matcher.group( 9 ), - matcher.group( 10 ), timestamp, buildNumber ); - try - { + Artifact artifact = new Artifact( + groupId, artifactId, version, matcher.group(9), matcher.group(10), timestamp, buildNumber); + try { // check if artifact exist - store.getSize( artifact ); - return new ArtifactFileEntry( this, parent, artifact, store ); - } - catch ( IOException | ArtifactNotFoundException e ) - { + store.getSize(artifact); + return new ArtifactFileEntry(this, parent, artifact, store); + } catch (IOException | ArtifactNotFoundException e) { return null; } + } catch (NullPointerException e) { + return new DefaultDirectoryEntry(this, parent, name); } - catch ( NullPointerException e ) - { - return new DefaultDirectoryEntry( this, parent, name ); - } - } - else - { - Matcher matcher = ARTIFACT.matcher( path ); - if ( matcher.matches() ) - { - String groupId = StringUtils.stripEnd( matcher.group( 1 ), "/" ).replace( '/', '.' ); - String artifactId = matcher.group( 2 ); - String version = matcher.group( 3 ); - String classifier = matcher.group( 5 ); - String type = matcher.group( 6 ); - if ( classifier != null ) - { - classifier = classifier.substring( 1 ); + } else { + Matcher matcher = ARTIFACT.matcher(path); + if (matcher.matches()) { + String groupId = StringUtils.stripEnd(matcher.group(1), "/").replace('/', '.'); + String artifactId = matcher.group(2); + String version = matcher.group(3); + String classifier = matcher.group(5); + String type = matcher.group(6); + if (classifier != null) { + classifier = classifier.substring(1); } - if ( StringUtils.isEmpty( classifier ) ) - { + if (StringUtils.isEmpty(classifier)) { classifier = null; } - Artifact artifact = new Artifact( groupId, artifactId, version, classifier, type ); - try - { + Artifact artifact = new Artifact(groupId, artifactId, version, classifier, type); + try { // check if artifact exist - store.getSize( artifact ); - return new ArtifactFileEntry( this, parent, artifact, store ); - } - catch ( ArtifactNotFoundException | IOException e ) - { + store.getSize(artifact); + return new ArtifactFileEntry(this, parent, artifact, store); + } catch (ArtifactNotFoundException | IOException e) { return null; } - } - else - { - return new DefaultDirectoryEntry( this, parent, name ); + } else { + return new DefaultDirectoryEntry(this, parent, name); } } } } @Override - public long getLastModified( DirectoryEntry entry ) - throws IOException - { + public long getLastModified(DirectoryEntry entry) throws IOException { return System.currentTimeMillis(); } @Override - public FileEntry put( DirectoryEntry parent, String name, InputStream content ) - throws IOException - { + public FileEntry put(DirectoryEntry parent, String name, InputStream content) throws IOException { String path = "/"; - if ( StringUtils.isNotEmpty( parent.toPath() ) ) - { + if (StringUtils.isNotEmpty(parent.toPath())) { path += parent.toPath() + "/"; } - if ( "maven-metadata.xml".equals( name ) ) - { + if ("maven-metadata.xml".equals(name)) { MetadataXpp3Reader reader = new MetadataXpp3Reader(); - try - { - Metadata metadata = reader.read( content ); + try { + Metadata metadata = reader.read(content); - if ( metadata == null ) - { + if (metadata == null) { return null; } - store.setMetadata( path, metadata ); - } - catch ( XmlPullParserException e1 ) - { + store.setMetadata(path, metadata); + } catch (XmlPullParserException e1) { throw new IOException(); } - return new MetadataFileEntry( this, parent, path, store ); + return new MetadataFileEntry(this, parent, path, store); } - Artifact artifact = getArtifact( parent, name ); + Artifact artifact = getArtifact(parent, name); - if ( artifact == null ) - { + if (artifact == null) { return null; } - store.set( artifact, content ); + store.set(artifact, content); - return new ArtifactFileEntry( this, parent, artifact, store ); + return new ArtifactFileEntry(this, parent, artifact, store); } - private Artifact getArtifact( DirectoryEntry parent, String name ) - { + private Artifact getArtifact(DirectoryEntry parent, String name) { String path = "/"; - if ( StringUtils.isNotEmpty( parent.toPath() ) ) - { + if (StringUtils.isNotEmpty(parent.toPath())) { path += parent.toPath() + "/"; } path += name; - Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher( path ); - if ( snapshotArtifact.matches() ) - { - String groupId = StringUtils.stripEnd( snapshotArtifact.group( 1 ), "/" ).replace( '/', '.' ); - String artifactId = snapshotArtifact.group( 2 ); - String version = snapshotArtifact.group( 3 ) + "-SNAPSHOT"; - Pattern rule = Pattern.compile( - "\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd( version, "-SNAPSHOT" ) - + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" - + "\\.([^/]*)" ); - Matcher matcher = rule.matcher( name ); - if ( !matcher.matches() ) - { - String classifier = snapshotArtifact.group( 5 ); - String type = snapshotArtifact.group( 6 ); - if ( classifier != null ) - { - classifier = classifier.substring( 1 ); + Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher(path); + if (snapshotArtifact.matches()) { + String groupId = + StringUtils.stripEnd(snapshotArtifact.group(1), "/").replace('/', '.'); + String artifactId = snapshotArtifact.group(2); + String version = snapshotArtifact.group(3) + "-SNAPSHOT"; + Pattern rule = + Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT") + + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" + + "\\.([^/]*)"); + Matcher matcher = rule.matcher(name); + if (!matcher.matches()) { + String classifier = snapshotArtifact.group(5); + String type = snapshotArtifact.group(6); + if (classifier != null) { + classifier = classifier.substring(1); } - if ( StringUtils.isEmpty( classifier ) ) - { + if (StringUtils.isEmpty(classifier)) { classifier = null; } - return new Artifact( groupId, artifactId, version, classifier, type ); + return new Artifact(groupId, artifactId, version, classifier, type); } - if ( matcher.group( 1 ).equals( "SNAPSHOT" ) ) - { - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), - matcher.group( 10 ) ); + if (matcher.group(1).equals("SNAPSHOT")) { + return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10)); } - try - { + try { Calendar cal = new GregorianCalendar(); - cal.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - cal.set( Calendar.YEAR, Integer.parseInt( matcher.group( 2 ) ) ); - cal.set( Calendar.MONTH, Integer.parseInt( matcher.group( 3 ) ) - 1 ); - cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( matcher.group( 4 ) ) ); - cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt( matcher.group( 5 ) ) ); - cal.set( Calendar.MINUTE, Integer.parseInt( matcher.group( 6 ) ) ); - cal.set( Calendar.SECOND, Integer.parseInt( matcher.group( 7 ) ) ); - cal.set( Calendar.MILLISECOND, 0 ); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2))); + cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1); + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4))); + cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5))); + cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6))); + cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7))); + cal.set(Calendar.MILLISECOND, 0); long timestamp = cal.getTimeInMillis(); - int buildNumber = Integer.parseInt( matcher.group( 8 ) ); + int buildNumber = Integer.parseInt(matcher.group(8)); - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), - matcher.group( 10 ), timestamp, buildNumber ); - } - catch ( NullPointerException e ) - { + return new Artifact( + groupId, artifactId, version, matcher.group(9), matcher.group(10), timestamp, buildNumber); + } catch (NullPointerException e) { return null; } - } - else - { - Matcher matcher = ARTIFACT.matcher( path ); - if ( matcher.matches() ) - { - String groupId = StringUtils.stripEnd( matcher.group( 1 ), "/" ).replace( '/', '.' ); - String artifactId = matcher.group( 2 ); - String version = matcher.group( 3 ); - String classifier = matcher.group( 5 ); - String type = matcher.group( 6 ); - if ( classifier != null ) - { - classifier = classifier.substring( 1 ); + } else { + Matcher matcher = ARTIFACT.matcher(path); + if (matcher.matches()) { + String groupId = StringUtils.stripEnd(matcher.group(1), "/").replace('/', '.'); + String artifactId = matcher.group(2); + String version = matcher.group(3); + String classifier = matcher.group(5); + String type = matcher.group(6); + if (classifier != null) { + classifier = classifier.substring(1); } - if ( StringUtils.isEmpty( classifier ) ) - { + if (StringUtils.isEmpty(classifier)) { classifier = null; } - return new Artifact( groupId, artifactId, version, classifier, type ); - } - else - { + return new Artifact(groupId, artifactId, version, classifier, type); + } else { 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 b20c75d7..4a37f4d3 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 @@ -41,9 +41,7 @@ * * @since 1.0 */ -public class CompositeArtifactStore - extends BaseArtifactStore -{ +public class CompositeArtifactStore extends BaseArtifactStore { /** * The backing artifact stores, in order of priority. @@ -58,23 +56,19 @@ public class CompositeArtifactStore * @param stores the artifact stores. * @since 1.0 */ - public CompositeArtifactStore( ArtifactStore[] stores ) - { + public CompositeArtifactStore(ArtifactStore[] stores) { this.stores = stores; } /** * {@inheritDoc} */ - public Set getGroupIds( String parentGroupId ) - { + public Set getGroupIds(String parentGroupId) { Set result = new TreeSet<>(); - for ( ArtifactStore store : stores ) - { - Set groupIds = store.getGroupIds( parentGroupId ); - if ( groupIds != null ) - { - result.addAll( groupIds ); + for (ArtifactStore store : stores) { + Set groupIds = store.getGroupIds(parentGroupId); + if (groupIds != null) { + result.addAll(groupIds); } } @@ -84,15 +78,12 @@ public Set getGroupIds( String parentGroupId ) /** * {@inheritDoc} */ - public Set getArtifactIds( String groupId ) - { + public Set getArtifactIds(String groupId) { Set result = new TreeSet<>(); - for ( ArtifactStore store : stores ) - { - Set artifactIds = store.getArtifactIds( groupId ); - if ( artifactIds != null ) - { - result.addAll( artifactIds ); + for (ArtifactStore store : stores) { + Set artifactIds = store.getArtifactIds(groupId); + if (artifactIds != null) { + result.addAll(artifactIds); } } return result; @@ -101,15 +92,12 @@ public Set getArtifactIds( String groupId ) /** * {@inheritDoc} */ - public Set getVersions( String groupId, String artifactId ) - { + public Set getVersions(String groupId, String artifactId) { Set result = new TreeSet<>(); - for ( ArtifactStore store : stores ) - { - Set versions = store.getVersions( groupId, artifactId ); - if ( versions != null ) - { - result.addAll( versions ); + for (ArtifactStore store : stores) { + Set versions = store.getVersions(groupId, artifactId); + if (versions != null) { + result.addAll(versions); } } return result; @@ -118,15 +106,12 @@ public Set getVersions( String groupId, String artifactId ) /** * {@inheritDoc} */ - public Set getArtifacts( String groupId, String artifactId, String version ) - { + public Set getArtifacts(String groupId, String artifactId, String version) { Set result = new TreeSet<>(); - for ( ArtifactStore store : stores ) - { - Set artifacts = store.getArtifacts( groupId, artifactId, version ); - if ( artifacts != null ) - { - result.addAll( artifacts ); + for (ArtifactStore store : stores) { + Set artifacts = store.getArtifacts(groupId, artifactId, version); + if (artifacts != null) { + result.addAll(artifacts); } } return result; @@ -135,189 +120,143 @@ public Set getArtifacts( String groupId, String artifactId, String ver /** * {@inheritDoc} */ - public long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - for ( ArtifactStore store : stores ) - { - try - { - return store.getLastModified( artifact ); - } - catch ( ArtifactNotFoundException e ) - { + public long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + for (ArtifactStore store : stores) { + try { + return store.getLastModified(artifact); + } catch (ArtifactNotFoundException e) { // ignore } } - throw new ArtifactNotFoundException( artifact ); + throw new ArtifactNotFoundException(artifact); } /** * {@inheritDoc} */ - public long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - for ( ArtifactStore store : stores ) - { - try - { - return store.getSize( artifact ); - } - catch ( ArtifactNotFoundException e ) - { + public long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + for (ArtifactStore store : stores) { + try { + return store.getSize(artifact); + } catch (ArtifactNotFoundException e) { // ignore } } - throw new ArtifactNotFoundException( artifact ); + throw new ArtifactNotFoundException(artifact); } /** * {@inheritDoc} */ - public InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - for ( ArtifactStore store : stores ) - { - try - { - return store.get( artifact ); - } - catch ( ArtifactNotFoundException e ) - { + public InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + for (ArtifactStore store : stores) { + try { + return store.get(artifact); + } catch (ArtifactNotFoundException e) { // ignore } } - throw new ArtifactNotFoundException( artifact ); + throw new ArtifactNotFoundException(artifact); } /** * {@inheritDoc} */ - public void set( Artifact artifact, InputStream content ) - throws IOException - { - throw new IOException( "Read-only store" ); + public void set(Artifact artifact, InputStream content) throws IOException { + throw new IOException("Read-only store"); } /** * {@inheritDoc} */ - public Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { + public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { boolean found = false; Metadata result = new Metadata(); Set pluginArtifactIds = new HashSet<>(); Set snapshotVersions = new HashSet<>(); - for ( ArtifactStore store : stores ) - { - try - { - Metadata partial = store.getMetadata( path ); - if ( StringUtils.isEmpty( result.getArtifactId() ) && !StringUtils.isEmpty( partial.getArtifactId() ) ) - { - result.setArtifactId( partial.getArtifactId() ); + for (ArtifactStore store : stores) { + try { + Metadata partial = store.getMetadata(path); + if (StringUtils.isEmpty(result.getArtifactId()) && !StringUtils.isEmpty(partial.getArtifactId())) { + result.setArtifactId(partial.getArtifactId()); found = true; } - if ( StringUtils.isEmpty( result.getGroupId() ) && !StringUtils.isEmpty( partial.getGroupId() ) ) - { - result.setGroupId( partial.getGroupId() ); + if (StringUtils.isEmpty(result.getGroupId()) && !StringUtils.isEmpty(partial.getGroupId())) { + result.setGroupId(partial.getGroupId()); found = true; } - if ( StringUtils.isEmpty( result.getVersion() ) && !StringUtils.isEmpty( partial.getVersion() ) ) - { - result.setVersion( partial.getVersion() ); + if (StringUtils.isEmpty(result.getVersion()) && !StringUtils.isEmpty(partial.getVersion())) { + result.setVersion(partial.getVersion()); found = true; } - if ( partial.getPlugins() != null && !partial.getPlugins().isEmpty() ) - { - for ( Plugin plugin : partial.getPlugins() ) - { - if ( !pluginArtifactIds.contains( plugin.getArtifactId() ) ) - { - result.addPlugin( plugin ); - pluginArtifactIds.add( plugin.getArtifactId() ); + if (partial.getPlugins() != null && !partial.getPlugins().isEmpty()) { + for (Plugin plugin : partial.getPlugins()) { + if (!pluginArtifactIds.contains(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.setRelease( pVers.getRelease() ); + if (!StringUtils.isEmpty(pVers.getRelease())) { + rVers.setRelease(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 } } - if ( !found ) - { - throw new MetadataNotFoundException( path ); + if (!found) { + throw new MetadataNotFoundException(path); } return result; } @@ -325,88 +264,61 @@ public Metadata getMetadata( String path ) /** * {@inheritDoc} */ - public long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { + public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { boolean found = false; long lastModified = 0; - for ( ArtifactStore store : stores ) - { - try - { - if ( !found ) - { - lastModified = store.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, store.getMetadataLastModified( path ) ); - } - } - catch ( MetadataNotFoundException e ) - { + } catch (MetadataNotFoundException e) { // ignore } } - if ( !found ) - { - throw new MetadataNotFoundException( path ); + if (!found) { + throw new MetadataNotFoundException(path); } return lastModified; } - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { boolean found = false; ArchetypeCatalog result = new ArchetypeCatalog(); - for ( ArtifactStore store : stores ) - { - try - { + for (ArtifactStore store : stores) { + try { ArchetypeCatalog partial = store.getArchetypeCatalog(); - result.getArchetypes().addAll( partial.getArchetypes() ); + result.getArchetypes().addAll(partial.getArchetypes()); found = true; - } - catch ( ArchetypeCatalogNotFoundException e ) - { + } catch (ArchetypeCatalogNotFoundException e) { // ignore } } - if ( !found ) - { + if (!found) { throw new ArchetypeCatalogNotFoundException(); } return result; } - public long getArchetypeCatalogLastModified() - throws IOException, ArchetypeCatalogNotFoundException - { + public long getArchetypeCatalogLastModified() throws IOException, ArchetypeCatalogNotFoundException { boolean found = false; long lastModified = 0; - for ( ArtifactStore store : stores ) - { - try - { - if ( !found ) - { + for (ArtifactStore store : stores) { + try { + if (!found) { lastModified = store.getArchetypeCatalogLastModified(); found = true; + } else { + lastModified = Math.max(lastModified, store.getArchetypeCatalogLastModified()); } - else - { - lastModified = Math.max( lastModified, store.getArchetypeCatalogLastModified() ); - } - } - catch ( ArchetypeCatalogNotFoundException e ) - { + } catch (ArchetypeCatalogNotFoundException e) { // ignore } } - if ( !found ) - { + if (!found) { throw new ArchetypeCatalogNotFoundException(); } return lastModified; 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 901a84e4..846daa5c 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 @@ -53,9 +53,7 @@ * * @since 1.0 */ -public class DiskArtifactStore - extends BaseArtifactStore -{ +public class DiskArtifactStore extends BaseArtifactStore { /** * The root of the artifact store. * @@ -71,13 +69,11 @@ public class DiskArtifactStore * @param root the root directory of the artifact store. * @since 1.0 */ - public DiskArtifactStore( File root ) - { + public DiskArtifactStore(File root) { this.root = root; } - public DiskArtifactStore canWrite( boolean canWrite ) - { + public DiskArtifactStore canWrite(boolean canWrite) { this.canWrite = canWrite; return this; } @@ -85,159 +81,133 @@ public DiskArtifactStore canWrite( boolean canWrite ) /** * {@inheritDoc} */ - public Set getGroupIds( String parentGroupId ) - { - File parentDir = - StringUtils.isEmpty( parentGroupId ) ? root : new File( root, parentGroupId.replace( '.', '/' ) ); - if ( !parentDir.isDirectory() ) - { + public Set getGroupIds(String parentGroupId) { + File parentDir = StringUtils.isEmpty(parentGroupId) ? root : new File(root, parentGroupId.replace('.', '/')); + if (!parentDir.isDirectory()) { return Collections.emptySet(); } File[] groupDirs = parentDir.listFiles(); - if ( groupDirs == null ) - { + if (groupDirs == null) { return Collections.emptySet(); } - return Arrays.stream( groupDirs ).filter( File::isDirectory ) - .map( File::getName ) - .collect( Collectors.toSet() ); - + return Arrays.stream(groupDirs) + .filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getArtifactIds( String groupId ) - { - File groupDir = new File( root, groupId.replace( '.', '/' ) ); - if ( !groupDir.isDirectory() ) - { + public Set getArtifactIds(String groupId) { + File groupDir = new File(root, groupId.replace('.', '/')); + if (!groupDir.isDirectory()) { return Collections.emptySet(); } File[] artifactDirs = groupDir.listFiles(); - if ( artifactDirs == null ) - { + if (artifactDirs == null) { return Collections.emptySet(); } - return Arrays.stream( artifactDirs ).filter( File::isDirectory ) - .map( File::getName ) - .collect( Collectors.toSet() ); - + return Arrays.stream(artifactDirs) + .filter(File::isDirectory) + .map(File::getName) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getVersions( String groupId, String artifactId ) - { - File groupDir = new File( root, groupId.replace( '.', '/' ) ); - File artifactDir = new File( groupDir, artifactId ); - if ( !artifactDir.isDirectory() ) - { + public Set getVersions(String groupId, String artifactId) { + File groupDir = new File(root, groupId.replace('.', '/')); + File artifactDir = new File(groupDir, artifactId); + if (!artifactDir.isDirectory()) { return Collections.emptySet(); } File[] dirs = artifactDir.listFiles(); - if ( dirs == null ) - { + if (dirs == null) { return Collections.emptySet(); } - return Arrays.stream( dirs ).filter( File::isDirectory ) - .map( File::getName ) - .collect( Collectors.toSet() ); + return Arrays.stream(dirs).filter(File::isDirectory).map(File::getName).collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getArtifacts( final String groupId, final String artifactId, final String version ) - { - File groupDir = new File( root, groupId.replace( '.', '/' ) ); - File artifactDir = new File( groupDir, artifactId ); - File versionDir = new File( artifactDir, version ); - if ( !versionDir.isDirectory() ) - { + public Set getArtifacts(final String groupId, final String artifactId, final String version) { + File groupDir = new File(root, groupId.replace('.', '/')); + File artifactDir = new File(groupDir, artifactId); + File versionDir = new File(artifactDir, version); + if (!versionDir.isDirectory()) { return Collections.emptySet(); } final Pattern rule; - abstract class ArtifactFactory - { - abstract Artifact get( File file ); + abstract class ArtifactFactory { + abstract Artifact get(File file); } final ArtifactFactory factory; - if ( version.endsWith( "-SNAPSHOT" ) ) - { - rule = Pattern.compile( - "\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd( version, "-SNAPSHOT" ) + if (version.endsWith("-SNAPSHOT")) { + rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT") + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" - + "\\.([^/]*)" ); - factory = new ArtifactFactory() - { - public Artifact get( File file ) - { - Matcher matcher = rule.matcher( file.getName() ); - if ( !matcher.matches() ) - { + + "\\.([^/]*)"); + factory = new ArtifactFactory() { + public Artifact get(File file) { + Matcher matcher = rule.matcher(file.getName()); + if (!matcher.matches()) { return null; } - if ( matcher.group( 1 ).equals( "SNAPSHOT" ) ) - { - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), matcher.group( 10 ) ); + if (matcher.group(1).equals("SNAPSHOT")) { + return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10)); } - try - { + try { Calendar cal = new GregorianCalendar(); - cal.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - cal.set( Calendar.YEAR, Integer.parseInt( matcher.group( 2 ) ) ); - cal.set( Calendar.MONTH, Integer.parseInt( matcher.group( 3 ) ) - 1 ); - cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( matcher.group( 4 ) ) ); - cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt( matcher.group( 5 ) ) ); - cal.set( Calendar.MINUTE, Integer.parseInt( matcher.group( 6 ) ) ); - cal.set( Calendar.SECOND, Integer.parseInt( matcher.group( 7 ) ) ); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2))); + cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1); + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4))); + cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5))); + cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6))); + cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7))); long timestamp = cal.getTimeInMillis(); - int buildNumber = Integer.parseInt( matcher.group( 8 ) ); - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), matcher.group( 10 ), - timestamp, buildNumber ); - } - catch ( NullPointerException e ) - { + int buildNumber = Integer.parseInt(matcher.group(8)); + return new Artifact( + groupId, + artifactId, + version, + matcher.group(9), + matcher.group(10), + timestamp, + buildNumber); + } catch (NullPointerException e) { return null; } } }; - } - else - { - rule = Pattern.compile( "\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)" ); - factory = new ArtifactFactory() - { - public Artifact get( File file ) - { - Matcher matcher = rule.matcher( file.getName() ); - if ( !matcher.matches() ) - { + } else { + rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)"); + factory = new ArtifactFactory() { + public Artifact get(File file) { + Matcher matcher = rule.matcher(file.getName()); + if (!matcher.matches()) { return null; } - return new Artifact( groupId, artifactId, version, matcher.group( 1 ), matcher.group( 2 ) ); + return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2)); } }; } File[] files = versionDir.listFiles(); - Set result = new HashSet<>( files.length ); - for ( File file : files ) - { - if ( !file.isFile() || !rule.matcher( file.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( file ); - if ( artifact != null ) - { - result.add( artifact ); + Artifact artifact = factory.get(file); + if (artifact != null) { + result.add(artifact); } } return result; @@ -246,13 +216,10 @@ public Artifact get( File file ) /** * {@inheritDoc} */ - public long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - File file = getFile( artifact ); - if ( !file.isFile() ) - { - throw new ArtifactNotFoundException( artifact ); + public long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + File file = getFile(artifact); + if (!file.isFile()) { + throw new ArtifactNotFoundException(artifact); } return file.lastModified(); } @@ -260,13 +227,10 @@ public long getLastModified( Artifact artifact ) /** * {@inheritDoc} */ - public long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - File file = getFile( artifact ); - if ( !file.isFile() ) - { - throw new ArtifactNotFoundException( artifact ); + public long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + File file = getFile(artifact); + if (!file.isFile()) { + throw new ArtifactNotFoundException(artifact); } return file.length(); } @@ -274,168 +238,127 @@ public long getSize( Artifact artifact ) /** * {@inheritDoc} */ - public InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - File file = getFile( artifact ); - if ( !file.isFile() ) - { - throw new ArtifactNotFoundException( artifact ); + public InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + File file = getFile(artifact); + if (!file.isFile()) { + throw new ArtifactNotFoundException(artifact); } - return new FileInputStream( file ); + return new FileInputStream(file); } /** * {@inheritDoc} */ - public void set( Artifact artifact, InputStream content ) - throws IOException - { - if ( !canWrite ) - { - throw new UnsupportedOperationException( "Read-only store" ); + public void set(Artifact artifact, InputStream content) throws IOException { + if (!canWrite) { + throw new UnsupportedOperationException("Read-only store"); } - File targetFile = getFile( artifact ); + File targetFile = getFile(artifact); - if ( !targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs() ) - { - throw new IOException( "Failed to create " + targetFile.getParentFile().getPath() ); + if (!targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs()) { + throw new IOException( + "Failed to create " + targetFile.getParentFile().getPath()); } - try ( OutputStream output = Files.newOutputStream( targetFile.toPath() ) ) - { - IOUtils.copy( content, output ); - } - finally - { - IOUtils.closeQuietly( content ); + try (OutputStream output = Files.newOutputStream(targetFile.toPath())) { + IOUtils.copy(content, output); + } finally { + IOUtils.closeQuietly(content); } } /** * {@inheritDoc} */ - public Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { + public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { File file = root; - String[] parts = StringUtils.strip( path, "/" ).split( "/" ); - for ( String part : parts ) - { - file = new File( file, part ); + String[] parts = StringUtils.strip(path, "/").split("/"); + for (String part : parts) { + file = new File(file, part); } - file = new File( file, "maven-metadata.xml" ); - if ( !file.isFile() ) - { - throw new MetadataNotFoundException( path ); + file = new File(file, "maven-metadata.xml"); + if (!file.isFile()) { + throw new MetadataNotFoundException(path); } - try ( InputStream inputStream = Files.newInputStream( file.toPath() ) ) - { - return new MetadataXpp3Reader().read( inputStream ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + try (InputStream inputStream = Files.newInputStream(file.toPath())) { + return new MetadataXpp3Reader().read(inputStream); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } } @Override - public void setMetadata( String path, Metadata metadata ) - throws IOException - { - if ( !canWrite ) - { - throw new UnsupportedOperationException( "Read-only store" ); + public void setMetadata(String path, Metadata metadata) throws IOException { + if (!canWrite) { + throw new UnsupportedOperationException("Read-only store"); } File file = root; - String[] parts = StringUtils.strip( path, "/" ).split( "/" ); - for ( String part : parts ) - { - file = new File( file, part ); + String[] parts = StringUtils.strip(path, "/").split("/"); + for (String part : parts) { + file = new File(file, part); } - file = new File( file, "maven-metadata.xml" ); + file = new File(file, "maven-metadata.xml"); - try ( OutputStream outputStream = Files.newOutputStream( file.toPath() ) ) - { - new MetadataXpp3Writer().write( outputStream, metadata ); + try (OutputStream outputStream = Files.newOutputStream(file.toPath())) { + new MetadataXpp3Writer().write(outputStream, metadata); } } /** * {@inheritDoc} */ - public long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { + public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { File file = root; - String[] parts = StringUtils.strip( path, "/" ).split( "/" ); + String[] parts = StringUtils.strip(path, "/").split("/"); Stack stack = new Stack<>(); - for ( int i = 0; i < parts.length; i++ ) - { - if ( "..".equals( parts[i] ) ) - { - if ( !stack.isEmpty() ) - { + for (int i = 0; i < parts.length; i++) { + if ("..".equals(parts[i])) { + if (!stack.isEmpty()) { file = stack.pop(); - } - else - { + } else { file = root; } - } - else if ( !".".equals( parts[i] ) ) - { - file = new File( file, parts[i] ); - stack.push( file ); + } else if (!".".equals(parts[i])) { + file = new File(file, parts[i]); + stack.push(file); } } - file = new File( file, "maven-metadata.xml" ); - if ( !file.isFile() ) - { - throw new MetadataNotFoundException( path ); + file = new File(file, "maven-metadata.xml"); + if (!file.isFile()) { + throw new MetadataNotFoundException(path); } return file.lastModified(); } - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { - File file = new File( root, "archetype-catalog.xml" ); - if ( !file.isFile() ) - { + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { + File file = new File(root, "archetype-catalog.xml"); + if (!file.isFile()) { throw new ArchetypeCatalogNotFoundException(); } - try ( InputStream inputStream = Files.newInputStream( file.toPath() ) ) - { - return new ArchetypeCatalogXpp3Reader().read( inputStream ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + try (InputStream inputStream = Files.newInputStream(file.toPath())) { + return new ArchetypeCatalogXpp3Reader().read(inputStream); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } } - public long getArchetypeCatalogLastModified() - throws IOException, ArchetypeCatalogNotFoundException - { - File file = new File( root, "archetype-catalog.xml" ); - if ( !file.isFile() ) - { + public long getArchetypeCatalogLastModified() throws IOException, ArchetypeCatalogNotFoundException { + File file = new File(root, "archetype-catalog.xml"); + if (!file.isFile()) { throw new ArchetypeCatalogNotFoundException(); } return file.lastModified(); } - 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() ); - return new File( versionDir, artifact.getName() ); + 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()); + 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 6884b5e2..e9263eec 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,6 +16,19 @@ package org.codehaus.mojo.mrm.impl.maven; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.Set; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + import org.apache.commons.lang.StringUtils; import org.apache.maven.archetype.catalog.ArchetypeCatalog; import org.apache.maven.archetype.catalog.io.xpp3.ArchetypeCatalogXpp3Reader; @@ -32,28 +45,13 @@ import org.codehaus.mojo.mrm.api.maven.MetadataNotFoundException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.Set; -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}. * * @see ArtifactStoreFileSystem for the oposite. * @since 1.0 */ -public class FileSystemArtifactStore - extends BaseArtifactStore -{ +public class FileSystemArtifactStore extends BaseArtifactStore { /** * The backing file system. * @@ -67,152 +65,134 @@ public class FileSystemArtifactStore * @param backing the backing file system. * @since 1.0 */ - public FileSystemArtifactStore( FileSystem backing ) - { + public FileSystemArtifactStore(FileSystem backing) { this.backing = backing; } /** * {@inheritDoc} */ - public Set getGroupIds( String parentGroupId ) - { + public Set getGroupIds(String parentGroupId) { Entry parentEntry = - StringUtils.isEmpty( parentGroupId ) ? backing.getRoot() : backing.get( parentGroupId.replace( '.', '/' ) ); - if ( !( parentEntry instanceof DirectoryEntry ) ) - { + StringUtils.isEmpty(parentGroupId) ? backing.getRoot() : backing.get(parentGroupId.replace('.', '/')); + if (!(parentEntry instanceof DirectoryEntry)) { return Collections.emptySet(); } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; - Entry[] entries = backing.listEntries( parentDir ); - return Arrays.stream( entries ).filter( entry -> entry instanceof DirectoryEntry ) - .map( Entry::getName ) - .collect( Collectors.toSet() ); + Entry[] entries = backing.listEntries(parentDir); + return Arrays.stream(entries) + .filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getArtifactIds( String groupId ) - { - Entry parentEntry = backing.get( groupId.replace( '.', '/' ) ); - if ( !( parentEntry instanceof DirectoryEntry ) ) - { + public Set getArtifactIds(String groupId) { + Entry parentEntry = backing.get(groupId.replace('.', '/')); + if (!(parentEntry instanceof DirectoryEntry)) { return Collections.emptySet(); } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; - Entry[] entries = backing.listEntries( parentDir ); - return Arrays.stream( entries ).filter( entry -> entry instanceof DirectoryEntry ) - .map( Entry::getName ) - .collect( Collectors.toSet() ); + Entry[] entries = backing.listEntries(parentDir); + return Arrays.stream(entries) + .filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getVersions( String groupId, String artifactId ) - { - Entry parentEntry = backing.get( groupId.replace( '.', '/' ) + "/" + artifactId ); - if ( !( parentEntry instanceof DirectoryEntry ) ) - { + public Set getVersions(String groupId, String artifactId) { + Entry parentEntry = backing.get(groupId.replace('.', '/') + "/" + artifactId); + if (!(parentEntry instanceof DirectoryEntry)) { return Collections.emptySet(); } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; - Entry[] entries = backing.listEntries( parentDir ); - return Arrays.stream( entries ).filter( entry -> entry instanceof DirectoryEntry ) - .map( Entry::getName ) - .collect( Collectors.toSet() ); + Entry[] entries = backing.listEntries(parentDir); + return Arrays.stream(entries) + .filter(entry -> entry instanceof DirectoryEntry) + .map(Entry::getName) + .collect(Collectors.toSet()); } /** * {@inheritDoc} */ - public Set getArtifacts( final String groupId, final String artifactId, final String version ) - { - Entry parentEntry = backing.get( groupId.replace( '.', '/' ) + "/" + artifactId + "/" + version ); - if ( !( parentEntry instanceof DirectoryEntry ) ) - { + public Set getArtifacts(final String groupId, final String artifactId, final String version) { + Entry parentEntry = backing.get(groupId.replace('.', '/') + "/" + artifactId + "/" + version); + if (!(parentEntry instanceof DirectoryEntry)) { return Collections.emptySet(); } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; - Entry[] entries = backing.listEntries( parentDir ); + Entry[] entries = backing.listEntries(parentDir); final Pattern rule; - abstract class ArtifactFactory - { - abstract Artifact get( Entry entry ); + abstract class ArtifactFactory { + abstract Artifact get(Entry entry); } final ArtifactFactory factory; - if ( version.endsWith( "-SNAPSHOT" ) ) - { - rule = Pattern.compile( - "\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd( version, "-SNAPSHOT" ) + if (version.endsWith("-SNAPSHOT")) { + rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT") + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?" - + "\\.([^/]*)" ); + + "\\.([^/]*)"); - factory = new ArtifactFactory() - { - public Artifact get( Entry entry ) - { - Matcher matcher = rule.matcher( entry.getName() ); - if ( !matcher.matches() ) - { + factory = new ArtifactFactory() { + public Artifact get(Entry entry) { + Matcher matcher = rule.matcher(entry.getName()); + if (!matcher.matches()) { return null; } - if ( matcher.group( 1 ).equals( "SNAPSHOT" ) ) - { - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), matcher.group( 10 ) ); + if (matcher.group(1).equals("SNAPSHOT")) { + return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10)); } - try - { + try { Calendar cal = new GregorianCalendar(); - cal.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - cal.set( Calendar.YEAR, Integer.parseInt( matcher.group( 2 ) ) ); - cal.set( Calendar.MONTH, Integer.parseInt( matcher.group( 3 ) ) - 1 ); - cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( matcher.group( 4 ) ) ); - cal.set( Calendar.HOUR_OF_DAY, Integer.parseInt( matcher.group( 5 ) ) ); - cal.set( Calendar.MINUTE, Integer.parseInt( matcher.group( 6 ) ) ); - cal.set( Calendar.SECOND, Integer.parseInt( matcher.group( 7 ) ) ); + cal.setTimeZone(TimeZone.getTimeZone("GMT")); + cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2))); + cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1); + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4))); + cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5))); + cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6))); + cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7))); long timestamp = cal.getTimeInMillis(); - int buildNumber = Integer.parseInt( matcher.group( 8 ) ); - return new Artifact( groupId, artifactId, version, matcher.group( 9 ), matcher.group( 10 ), - timestamp, buildNumber ); - } - catch ( NullPointerException e ) - { + int buildNumber = Integer.parseInt(matcher.group(8)); + return new Artifact( + groupId, + artifactId, + version, + matcher.group(9), + matcher.group(10), + timestamp, + buildNumber); + } catch (NullPointerException e) { return null; } } }; - } - else - { - rule = Pattern.compile( "\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)" ); - factory = new ArtifactFactory() - { - public Artifact get( Entry entry ) - { - Matcher matcher = rule.matcher( entry.getName() ); - if ( !matcher.matches() ) - { + } else { + rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)"); + factory = new ArtifactFactory() { + public Artifact get(Entry entry) { + Matcher matcher = rule.matcher(entry.getName()); + if (!matcher.matches()) { return null; } - return new Artifact( groupId, artifactId, version, matcher.group( 1 ), matcher.group( 2 ) ); + return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2)); } }; } - Set result = new HashSet<>( entries.length ); - for ( Entry entry : entries ) - { - if ( !( entry instanceof FileEntry ) || !rule.matcher( entry.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( entry ); - if ( artifact != null ) - { - result.add( artifact ); + Artifact artifact = factory.get(entry); + if (artifact != null) { + result.add(artifact); } } return result; @@ -221,15 +201,11 @@ public Artifact get( Entry entry ) /** * {@inheritDoc} */ - public long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Entry entry = backing.get( - artifact.getGroupId().replace( '.', '/' ) + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() - + "/" + artifact.getName() ); - if ( !( entry instanceof FileEntry ) ) - { - throw new ArtifactNotFoundException( artifact ); + public long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + Entry entry = backing.get(artifact.getGroupId().replace('.', '/') + "/" + artifact.getArtifactId() + "/" + + artifact.getVersion() + "/" + artifact.getName()); + if (!(entry instanceof FileEntry)) { + throw new ArtifactNotFoundException(artifact); } return entry.getLastModified(); } @@ -237,107 +213,79 @@ public long getLastModified( Artifact artifact ) /** * {@inheritDoc} */ - public long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Entry entry = backing.get( - artifact.getGroupId().replace( '.', '/' ) + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() - + "/" + artifact.getName() ); - if ( !( entry instanceof FileEntry ) ) - { - throw new ArtifactNotFoundException( artifact ); + public long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + Entry entry = backing.get(artifact.getGroupId().replace('.', '/') + "/" + artifact.getArtifactId() + "/" + + artifact.getVersion() + "/" + artifact.getName()); + if (!(entry instanceof FileEntry)) { + throw new ArtifactNotFoundException(artifact); } - return ( (FileEntry) entry ).getSize(); + return ((FileEntry) entry).getSize(); } /** * {@inheritDoc} */ - public InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Entry entry = backing.get( - artifact.getGroupId().replace( '.', '/' ) + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() - + "/" + artifact.getName() ); - if ( !( entry instanceof FileEntry ) ) - { - throw new ArtifactNotFoundException( artifact ); + public InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + Entry entry = backing.get(artifact.getGroupId().replace('.', '/') + "/" + artifact.getArtifactId() + "/" + + artifact.getVersion() + "/" + artifact.getName()); + if (!(entry instanceof FileEntry)) { + throw new ArtifactNotFoundException(artifact); } - return ( (FileEntry) entry ).getInputStream(); + return ((FileEntry) entry).getInputStream(); } /** * {@inheritDoc} */ - public void set( Artifact artifact, InputStream content ) - throws IOException - { - throw new UnsupportedOperationException( "Read-only store" ); + public void set(Artifact artifact, InputStream content) throws IOException { + throw new UnsupportedOperationException("Read-only store"); } /** * {@inheritDoc} */ - public Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { + public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { Entry entry = backing.get( - StringUtils.join( StringUtils.split( StringUtils.strip( path, "/" ), "/" ), "/" ) + "/maven-metadata.xml" ); - if ( !( entry instanceof FileEntry ) ) - { - throw new MetadataNotFoundException( path ); + StringUtils.join(StringUtils.split(StringUtils.strip(path, "/"), "/"), "/") + "/maven-metadata.xml"); + if (!(entry instanceof FileEntry)) { + throw new MetadataNotFoundException(path); } - try ( InputStream inputStream = ( (FileEntry) entry ).getInputStream() ) - { - return new MetadataXpp3Reader().read( inputStream ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + try (InputStream inputStream = ((FileEntry) entry).getInputStream()) { + return new MetadataXpp3Reader().read(inputStream); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } } /** * {@inheritDoc} */ - public long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { + public long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { Entry entry = backing.get( - StringUtils.join( StringUtils.split( StringUtils.strip( path, "/" ), "/" ), "/" ) + "/maven-metadata.xml" ); - if ( !( entry instanceof FileEntry ) ) - { - throw new MetadataNotFoundException( path ); + StringUtils.join(StringUtils.split(StringUtils.strip(path, "/"), "/"), "/") + "/maven-metadata.xml"); + if (!(entry instanceof FileEntry)) { + throw new MetadataNotFoundException(path); } return entry.getLastModified(); } - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { - Entry entry = backing.get( "archetype-catalog.xml" ); - if ( !( entry instanceof FileEntry ) ) - { + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { + Entry entry = backing.get("archetype-catalog.xml"); + if (!(entry instanceof FileEntry)) { throw new ArchetypeCatalogNotFoundException(); } - try ( InputStream inputStream = ( (FileEntry) entry ).getInputStream() ) - { + try (InputStream inputStream = ((FileEntry) entry).getInputStream()) { - return new ArchetypeCatalogXpp3Reader().read( inputStream ); - } - catch ( XmlPullParserException e ) - { - throw new IOException( e.getMessage(), e ); + return new ArchetypeCatalogXpp3Reader().read(inputStream); + } catch (XmlPullParserException e) { + throw new IOException(e.getMessage(), e); } } - public long getArchetypeCatalogLastModified() - throws IOException, ArchetypeCatalogNotFoundException - { - Entry entry = backing.get( "archetype-catalog.xml" ); - if ( !( entry instanceof FileEntry ) ) - { + public long getArchetypeCatalogLastModified() throws IOException, ArchetypeCatalogNotFoundException { + Entry entry = backing.get("archetype-catalog.xml"); + if (!(entry instanceof FileEntry)) { throw new ArchetypeCatalogNotFoundException(); } return entry.getLastModified(); 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 b77483a1..0a4161cb 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 @@ -16,6 +16,24 @@ package org.codehaus.mojo.mrm.impl.maven; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeSet; + import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.archetype.catalog.ArchetypeCatalog; @@ -39,33 +57,12 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeSet; - /** * An artifact store that keeps all its artifacts in memory. * * @since 1.0 */ -public class MemoryArtifactStore - extends BaseArtifactStore - implements Serializable -{ +public class MemoryArtifactStore extends BaseArtifactStore implements Serializable { /** * Ensure consistent serialization. * @@ -85,27 +82,20 @@ public class MemoryArtifactStore /** * {@inheritDoc} */ - public synchronized Set getGroupIds( String parentGroupId ) - { + public synchronized Set getGroupIds(String parentGroupId) { Set result = new TreeSet<>(); - if ( StringUtils.isEmpty( parentGroupId ) ) - { - for ( String groupId : contents.keySet() ) - { - int index = groupId.indexOf( '.' ); - result.add( index == -1 ? groupId : groupId.substring( 0, index ) ); + if (StringUtils.isEmpty(parentGroupId)) { + for (String groupId : contents.keySet()) { + int index = groupId.indexOf('.'); + result.add(index == -1 ? groupId : groupId.substring(0, index)); } - } - else - { + } else { String prefix = parentGroupId + '.'; int start = prefix.length(); - for ( String groupId : contents.keySet() ) - { - if ( groupId.startsWith( prefix ) ) - { - int index = groupId.indexOf( '.', start ); - result.add( index == -1 ? groupId.substring( start ) : groupId.substring( start, index ) ); + for (String groupId : contents.keySet()) { + if (groupId.startsWith(prefix)) { + int index = groupId.indexOf('.', start); + result.add(index == -1 ? groupId.substring(start) : groupId.substring(start, index)); } } } @@ -115,68 +105,55 @@ public synchronized Set getGroupIds( String parentGroupId ) /** * {@inheritDoc} */ - public synchronized Set getArtifactIds( String groupId ) - { - Map>> artifactMap = contents.get( groupId ); - return artifactMap == null ? Collections.emptySet() : new TreeSet<>( artifactMap.keySet() ); + public synchronized Set getArtifactIds(String groupId) { + Map>> artifactMap = contents.get(groupId); + return artifactMap == null ? Collections.emptySet() : new TreeSet<>(artifactMap.keySet()); } /** * {@inheritDoc} */ - public synchronized Set getVersions( String groupId, String artifactId ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - return versionMap == null ? Collections.emptySet() : new TreeSet<>( versionMap.keySet() ); + public synchronized Set getVersions(String groupId, String artifactId) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + return versionMap == null ? Collections.emptySet() : new TreeSet<>(versionMap.keySet()); } /** * {@inheritDoc} */ - public synchronized Set getArtifacts( String groupId, String artifactId, String version ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); + public synchronized Set getArtifacts(String groupId, String artifactId, String version) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); - return filesMap == null ? Collections.emptySet() : new HashSet<>( filesMap.keySet() ); + return filesMap == null ? Collections.emptySet() : new HashSet<>(filesMap.keySet()); } /** * {@inheritDoc} */ - public synchronized long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); - + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } return content.getLastModified(); @@ -185,37 +162,27 @@ public synchronized long getLastModified( Artifact artifact ) /** * {@inheritDoc} */ - public synchronized long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); - + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } return content.getBytes().length; @@ -224,269 +191,211 @@ public synchronized long getSize( Artifact artifact ) /** * {@inheritDoc} */ - public synchronized InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); - + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } - return new ByteArrayInputStream( content.getBytes() ); + return new ByteArrayInputStream(content.getBytes()); } /** * {@inheritDoc} */ - public synchronized void set( Artifact artifact, InputStream content ) - throws IOException - { + public synchronized void set(Artifact artifact, InputStream content) throws IOException { Map>> artifactMap = - contents.computeIfAbsent( artifact.getGroupId(), k -> new HashMap<>() ); + 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 ) ) ); - } - finally - { - IOUtils.closeQuietly( content ); + 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))); + } finally { + IOUtils.closeQuietly(content); } } - @SuppressWarnings( "checkstyle:MethodLength" ) - public synchronized Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { + @SuppressWarnings("checkstyle:MethodLength") + public synchronized Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { Metadata metadata = new Metadata(); boolean foundMetadata = false; - path = StringUtils.stripEnd( StringUtils.stripStart( path, "/" ), "/" ); - String groupId = path.replace( '/', '.' ); - Set pluginArtifactIds = getArtifactIds( groupId ); - if ( pluginArtifactIds != null ) - { + path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); + String groupId = path.replace('/', '.'); + Set pluginArtifactIds = getArtifactIds(groupId); + if (pluginArtifactIds != null) { List plugins = new ArrayList<>(); - for ( String artifactId : pluginArtifactIds ) - { - Set pluginVersions = getVersions( groupId, artifactId ); - if ( pluginVersions == null || pluginVersions.isEmpty() ) - { + for (String artifactId : pluginArtifactIds) { + Set pluginVersions = getVersions(groupId, artifactId); + if (pluginVersions == null || pluginVersions.isEmpty()) { continue; } - String[] versions = pluginVersions.toArray( new String[0] ); - Arrays.sort( versions, INSTANCE ); + String[] versions = pluginVersions.toArray(new String[0]); + Arrays.sort(versions, INSTANCE); MavenXpp3Reader reader = new MavenXpp3Reader(); - for ( int j = versions.length - 1; j >= 0; j-- ) - { - try ( InputStream inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) ); - XmlStreamReader xmlStreamReader = new XmlStreamReader( inputStream ) ) - { - Model model = reader.read( xmlStreamReader ); - if ( model == null || !"maven-plugin".equals( model.getPackaging() ) ) - { + for (int j = versions.length - 1; j >= 0; j--) { + try (InputStream inputStream = get(new Artifact(groupId, artifactId, versions[j], "pom")); + XmlStreamReader xmlStreamReader = new XmlStreamReader(inputStream)) { + Model model = reader.read(xmlStreamReader); + if (model == null || !"maven-plugin".equals(model.getPackaging())) { continue; } Plugin plugin = new Plugin(); - plugin.setArtifactId( artifactId ); - plugin.setName( model.getName() ); + plugin.setArtifactId(artifactId); + plugin.setName(model.getName()); // TODO proper goal-prefix determination // ugh! this is incredibly hacky and does not handle some fool that sets the goal prefix in // a parent pom... ok unlikely, but stupid is as stupid does boolean havePrefix = false; final Build build = model.getBuild(); - if ( build != null && build.getPlugins() != null ) - { - havePrefix = setPluginGoalPrefixFromConfiguration( plugin, build.getPlugins() ); + if (build != null && build.getPlugins() != null) { + havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPlugins()); } - if ( !havePrefix && build != null && build.getPluginManagement() != null - && build.getPluginManagement().getPlugins() != null ) - { - havePrefix = setPluginGoalPrefixFromConfiguration( plugin, - build.getPluginManagement() - .getPlugins() ); + if (!havePrefix + && build != null + && build.getPluginManagement() != null + && build.getPluginManagement().getPlugins() != null) { + havePrefix = setPluginGoalPrefixFromConfiguration( + plugin, build.getPluginManagement().getPlugins()); } - if ( !havePrefix && artifactId.startsWith( "maven-" ) && artifactId.endsWith( "-plugin" ) ) - { + if (!havePrefix && artifactId.startsWith("maven-") && artifactId.endsWith("-plugin")) { plugin.setPrefix( - StringUtils.removeStart( StringUtils.removeEnd( artifactId, "-plugin" ), "maven-" ) ); + StringUtils.removeStart(StringUtils.removeEnd(artifactId, "-plugin"), "maven-")); havePrefix = true; } - if ( !havePrefix && artifactId.endsWith( "-maven-plugin" ) ) - { - plugin.setPrefix( StringUtils.removeEnd( artifactId, "-maven-plugin" ) ); + if (!havePrefix && artifactId.endsWith("-maven-plugin")) { + plugin.setPrefix(StringUtils.removeEnd(artifactId, "-maven-plugin")); havePrefix = true; } - if ( !havePrefix ) - { - plugin.setPrefix( artifactId ); + if (!havePrefix) { + plugin.setPrefix(artifactId); } - plugins.add( plugin ); + plugins.add(plugin); foundMetadata = true; break; - } - catch ( ArtifactNotFoundException | XmlPullParserException e ) - { + } catch (ArtifactNotFoundException | XmlPullParserException e) { // ignore } } } - if ( !plugins.isEmpty() ) - { - metadata.setPlugins( plugins ); + if (!plugins.isEmpty()) { + metadata.setPlugins(plugins); } } - int index = path.lastIndexOf( '/' ); - groupId = ( index == -1 ? groupId : groupId.substring( 0, index ) ).replace( '/', '.' ); - String artifactId = ( index == -1 ? null : path.substring( index + 1 ) ); - if ( artifactId != null ) - { - Set artifactVersions = getVersions( groupId, artifactId ); - if ( artifactVersions != null && !artifactVersions.isEmpty() ) - { - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); + int index = path.lastIndexOf('/'); + groupId = (index == -1 ? groupId : groupId.substring(0, index)).replace('/', '.'); + String artifactId = (index == -1 ? null : path.substring(index + 1)); + if (artifactId != null) { + Set artifactVersions = getVersions(groupId, artifactId); + if (artifactVersions != null && !artifactVersions.isEmpty()) { + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); Versioning versioning = new Versioning(); - List versions = new ArrayList<>( artifactVersions ); - versions.sort( INSTANCE ); // sort the Maven way + List versions = new ArrayList<>(artifactVersions); + versions.sort(INSTANCE); // sort the Maven way long lastUpdated = 0; - for ( String version : versions ) - { - try - { - long lastModified = getLastModified( new Artifact( groupId, artifactId, version, "pom" ) ); - versioning.addVersion( version ); - if ( lastModified >= lastUpdated ) - { + for (String version : versions) { + try { + long lastModified = getLastModified(new Artifact(groupId, artifactId, version, "pom")); + versioning.addVersion(version); + if (lastModified >= lastUpdated) { lastUpdated = lastModified; - versioning.setLastUpdatedTimestamp( new Date( lastModified ) ); - versioning.setLatest( version ); - if ( !version.endsWith( "-SNAPSHOT" ) ) - { - versioning.setRelease( version ); + versioning.setLastUpdatedTimestamp(new Date(lastModified)); + versioning.setLatest(version); + if (!version.endsWith("-SNAPSHOT")) { + versioning.setRelease(version); } } - } - catch ( ArtifactNotFoundException e ) - { + } catch (ArtifactNotFoundException e) { // ignore } } - metadata.setVersioning( versioning ); + metadata.setVersioning(versioning); foundMetadata = true; } } - int index2 = index == -1 ? -1 : path.lastIndexOf( '/', index - 1 ); - groupId = index2 == -1 ? groupId : groupId.substring( 0, index2 ).replace( '/', '.' ); - artifactId = index2 == -1 ? artifactId : path.substring( index2 + 1, index ); - String version = index2 == -1 ? null : path.substring( index + 1 ); - if ( version != null && version.endsWith( "-SNAPSHOT" ) ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - if ( filesMap != null ) - { + int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); + groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); + artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); + String version = index2 == -1 ? null : path.substring(index + 1); + if (version != null && version.endsWith("-SNAPSHOT")) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); + if (filesMap != null) { List snapshotVersions = new ArrayList<>(); int maxBuildNumber = 0; long lastUpdated = 0; String timestamp = null; boolean found = false; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { 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() ) ); - try - { - Maven3.addSnapshotVersion( snapshotVersions, artifact, lastUpdatedTime ); - } - catch ( LinkageError e ) - { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss"); + fmt.setTimeZone(TimeZone.getTimeZone("GMT")); + String lastUpdatedTime = fmt.format(new Date(content.getLastModified())); + try { + Maven3.addSnapshotVersion(snapshotVersions, artifact, lastUpdatedTime); + } catch (LinkageError e) { // Maven 2 } - if ( "pom".equals( artifact.getType() ) ) - { - if ( artifact.getBuildNumber() != null - && maxBuildNumber < artifact.getBuildNumber() ) - { + if ("pom".equals(artifact.getType())) { + if (artifact.getBuildNumber() != null && maxBuildNumber < artifact.getBuildNumber()) { maxBuildNumber = artifact.getBuildNumber(); timestamp = artifact.getTimestampString(); + } else { + maxBuildNumber = Math.max(1, maxBuildNumber); } - else - { - maxBuildNumber = Math.max( 1, maxBuildNumber ); - } - lastUpdated = Math.max( lastUpdated, content.getLastModified() ); + lastUpdated = Math.max(lastUpdated, content.getLastModified()); found = true; } } - if ( !snapshotVersions.isEmpty() || found ) - { + if (!snapshotVersions.isEmpty() || found) { Versioning versioning = metadata.getVersioning(); - if ( versioning == null ) - { + if (versioning == null) { versioning = new Versioning(); } - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); - metadata.setVersion( version ); - try - { - Maven3.addSnapshotVersions( versioning, snapshotVersions ); - } - catch ( LinkageError e ) - { + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); + metadata.setVersion(version); + try { + Maven3.addSnapshotVersions(versioning, snapshotVersions); + } catch (LinkageError e) { // Maven 2 } - if ( maxBuildNumber > 0 ) - { + if (maxBuildNumber > 0) { Snapshot snapshot = new Snapshot(); - snapshot.setBuildNumber( maxBuildNumber ); - snapshot.setTimestamp( timestamp ); - versioning.setSnapshot( snapshot ); + snapshot.setBuildNumber(maxBuildNumber); + snapshot.setTimestamp(timestamp); + versioning.setSnapshot(snapshot); } - versioning.setLastUpdatedTimestamp( new Date( lastUpdated ) ); - metadata.setVersioning( versioning ); + versioning.setLastUpdatedTimestamp(new Date(lastUpdated)); + metadata.setVersioning(versioning); foundMetadata = true; } } - } - if ( !foundMetadata ) - { - throw new MetadataNotFoundException( path ); + if (!foundMetadata) { + throw new MetadataNotFoundException(path); } return metadata; } @@ -494,115 +403,83 @@ public synchronized Metadata getMetadata( String path ) /** * {@inheritDoc} */ - public synchronized long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { + public synchronized long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { boolean haveResult = false; long result = 0; - path = StringUtils.stripEnd( StringUtils.stripStart( path, "/" ), "/" ); - String groupId = path.replace( '/', '.' ); - Map>> artifactMap = contents.get( groupId ); - if ( artifactMap != null ) - { - for ( Map> versionMap : artifactMap.values() ) - { - for ( Map filesMap : versionMap.values() ) - { - for ( Content content : filesMap.values() ) - { + path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); + String groupId = path.replace('/', '.'); + Map>> artifactMap = contents.get(groupId); + if (artifactMap != null) { + for (Map> versionMap : artifactMap.values()) { + for (Map filesMap : versionMap.values()) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } } - int index = path.lastIndexOf( '/' ); - groupId = index == -1 ? groupId : groupId.substring( 0, index ).replace( '/', '.' ); - String artifactId = ( index == -1 ? null : path.substring( index + 1 ) ); - if ( artifactId != null ) - { - artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - if ( versionMap != null ) - { - for ( Map filesMap : versionMap.values() ) - { - for ( Content content : filesMap.values() ) - { + int index = path.lastIndexOf('/'); + groupId = index == -1 ? groupId : groupId.substring(0, index).replace('/', '.'); + String artifactId = (index == -1 ? null : path.substring(index + 1)); + if (artifactId != null) { + artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + if (versionMap != null) { + for (Map filesMap : versionMap.values()) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } } - int index2 = index == -1 ? -1 : path.lastIndexOf( '/', index - 1 ); - groupId = index2 == -1 ? groupId : groupId.substring( 0, index2 ).replace( '/', '.' ); - artifactId = index2 == -1 ? artifactId : path.substring( index2 + 1, index ); - String version = index2 == -1 ? null : path.substring( index + 1 ); - if ( version != null && version.endsWith( "-SNAPSHOT" ) ) - { - artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - if ( filesMap != null ) - { - for ( Content content : filesMap.values() ) - { + int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); + groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); + artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); + String version = index2 == -1 ? null : path.substring(index + 1); + if (version != null && version.endsWith("-SNAPSHOT")) { + artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); + if (filesMap != null) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } - if ( haveResult ) - { + if (haveResult) { return result; } - throw new MetadataNotFoundException( path ); + throw new MetadataNotFoundException(path); } @Override - public synchronized void setArchetypeCatalog( InputStream content ) - throws IOException - { - archetypeCatalog = new Content( IOUtils.toByteArray( content ) ); + public synchronized void setArchetypeCatalog(InputStream content) throws IOException { + archetypeCatalog = new Content(IOUtils.toByteArray(content)); } - public synchronized ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { - if ( archetypeCatalog != null ) - { - try ( InputStream inputStream = new ByteArrayInputStream( archetypeCatalog.getBytes() ) ) - { - return new ArchetypeCatalogXpp3Reader().read( inputStream ); - } - catch ( XmlPullParserException e ) - { - throw new ArchetypeCatalogNotFoundException( e.getMessage(), e ); + public synchronized ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { + if (archetypeCatalog != null) { + try (InputStream inputStream = new ByteArrayInputStream(archetypeCatalog.getBytes())) { + return new ArchetypeCatalogXpp3Reader().read(inputStream); + } catch (XmlPullParserException e) { + throw new ArchetypeCatalogNotFoundException(e.getMessage(), e); } - } - else - { + } else { throw new ArchetypeCatalogNotFoundException(); } } - public synchronized long getArchetypeCatalogLastModified() - throws ArchetypeCatalogNotFoundException - { - if ( archetypeCatalog != null ) - { + public synchronized long getArchetypeCatalogLastModified() throws ArchetypeCatalogNotFoundException { + if (archetypeCatalog != null) { return archetypeCatalog.getLastModified(); - } - else - { + } else { throw new ArchetypeCatalogNotFoundException(); } } - /** * If the plugin configurations contain a reference to the maven-plugin-plugin and that contains * configuration of the goalPrefix, update the supplied plugin with that prefix. @@ -612,21 +489,16 @@ public synchronized long getArchetypeCatalogLastModified() * @return true if the prefix has been set. * @since 1.0 */ - private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, - List pluginConfigs ) - { - for ( org.apache.maven.model.Plugin def : pluginConfigs ) - { - if ( ( def.getGroupId() == null || StringUtils.equals( "org.apache.maven.plugins", def.getGroupId() ) ) - && StringUtils.equals( "maven-plugin-plugin", def.getArtifactId() ) ) - { + private boolean setPluginGoalPrefixFromConfiguration( + Plugin plugin, List pluginConfigs) { + for (org.apache.maven.model.Plugin def : pluginConfigs) { + if ((def.getGroupId() == null || StringUtils.equals("org.apache.maven.plugins", def.getGroupId())) + && StringUtils.equals("maven-plugin-plugin", def.getArtifactId())) { Xpp3Dom configuration = (Xpp3Dom) def.getConfiguration(); - if ( configuration != null ) - { - final Xpp3Dom goalPrefix = configuration.getChild( "goalPrefix" ); - if ( goalPrefix != null ) - { - plugin.setPrefix( goalPrefix.getValue() ); + if (configuration != null) { + final Xpp3Dom goalPrefix = configuration.getChild("goalPrefix"); + if (goalPrefix != null) { + plugin.setPrefix(goalPrefix.getValue()); return true; } } @@ -643,17 +515,14 @@ private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, * * @since 1.0 */ - private static class VersionComparator - implements Comparator - { + private static class VersionComparator implements Comparator { /** * {@inheritDoc} */ - public int compare( String o1, String o2 ) - { - ArtifactVersion v1 = new DefaultArtifactVersion( o1 ); - ArtifactVersion v2 = new DefaultArtifactVersion( o2 ); - return v1.compareTo( v2 ); + public int compare(String o1, String o2) { + ArtifactVersion v1 = new DefaultArtifactVersion(o1); + ArtifactVersion v2 = new DefaultArtifactVersion(o2); + return v1.compareTo(v2); } } @@ -662,9 +531,7 @@ public int compare( String o1, String o2 ) * * @since 1.0 */ - private static class Content - implements Serializable - { + private static class Content implements Serializable { /** * Ensure consistent serialization. @@ -693,8 +560,7 @@ private static class Content * @param bytes the content. * @since 1.0 */ - private Content( byte[] bytes ) - { + private Content(byte[] bytes) { this.lastModified = System.currentTimeMillis(); this.bytes = bytes; } @@ -705,8 +571,7 @@ private Content( byte[] bytes ) * @return the last modified timestamp. * @since 1.0 */ - public long getLastModified() - { + public long getLastModified() { return lastModified; } @@ -716,8 +581,7 @@ public long getLastModified() * @return the content. * @since 1.0 */ - public byte[] getBytes() - { + public byte[] getBytes() { return bytes; } } @@ -729,8 +593,7 @@ public byte[] getBytes() * * @since 1.0 */ - private static class Maven3 - { + private static class Maven3 { /** * Adds a snapshot version to the list of snapshot versions. * @@ -739,20 +602,16 @@ private static class Maven3 * @param lastUpdatedTime the time to flag for last updated. * @since 1.0 */ - private static void addSnapshotVersion( List snapshotVersions, Artifact artifact, - String lastUpdatedTime ) - { - try - { + private static void addSnapshotVersion( + List snapshotVersions, Artifact artifact, String lastUpdatedTime) { + try { SnapshotVersion snapshotVersion = new SnapshotVersion(); - snapshotVersion.setExtension( artifact.getType() ); - snapshotVersion.setClassifier( artifact.getClassifier() == null ? "" : artifact.getClassifier() ); - snapshotVersion.setVersion( artifact.getTimestampVersion() ); - snapshotVersion.setUpdated( lastUpdatedTime ); - snapshotVersions.add( snapshotVersion ); - } - catch ( NoClassDefFoundError e ) - { + snapshotVersion.setExtension(artifact.getType()); + snapshotVersion.setClassifier(artifact.getClassifier() == null ? "" : artifact.getClassifier()); + snapshotVersion.setVersion(artifact.getTimestampVersion()); + snapshotVersion.setUpdated(lastUpdatedTime); + snapshotVersions.add(snapshotVersion); + } catch (NoClassDefFoundError e) { // Maven 2 } } @@ -764,17 +623,12 @@ private static void addSnapshotVersion( List snapshotVersions, * @param snapshotVersions the snapshot versions to add. * @since 1.0 */ - private static void addSnapshotVersions( Versioning versioning, List snapshotVersions ) - { - try - { - for ( SnapshotVersion snapshotVersion : snapshotVersions ) - { - versioning.addSnapshotVersion( snapshotVersion ); + private static void addSnapshotVersions(Versioning versioning, List snapshotVersions) { + try { + for (SnapshotVersion snapshotVersion : snapshotVersions) { + versioning.addSnapshotVersion(snapshotVersion); } - } - catch ( NoClassDefFoundError e ) - { + } catch (NoClassDefFoundError e) { // Maven 2 } } 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 93f67d5a..440f55c1 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 @@ -16,6 +16,11 @@ package org.codehaus.mojo.mrm.impl.maven; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer; import org.codehaus.mojo.mrm.api.BaseFileEntry; @@ -24,19 +29,12 @@ import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.codehaus.mojo.mrm.api.maven.MetadataNotFoundException; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; - /** * A file entry backed by {@link Metadata} in a {@link ArtifactStore}. * * @since 1.0 */ -public class MetadataFileEntry - extends BaseFileEntry -{ +public class MetadataFileEntry extends BaseFileEntry { /** * Ensure consistent serialization. @@ -70,9 +68,8 @@ public class MetadataFileEntry * @param store the artifact store. * @since 1.0 */ - public MetadataFileEntry( FileSystem fileSystem, DirectoryEntry parent, String path, ArtifactStore store ) - { - super( fileSystem, parent, "maven-metadata.xml" ); + public MetadataFileEntry(FileSystem fileSystem, DirectoryEntry parent, String path, ArtifactStore store) { + super(fileSystem, parent, "maven-metadata.xml"); this.path = path; this.store = store; } @@ -80,39 +77,29 @@ public MetadataFileEntry( FileSystem fileSystem, DirectoryEntry parent, String p /** * {@inheritDoc} */ - public long getSize() - throws IOException - { - try - { - Metadata metadata = store.getMetadata( path ); + public long getSize() throws IOException { + try { + Metadata metadata = store.getMetadata(path); MetadataXpp3Writer writer = new MetadataXpp3Writer(); StringWriter stringWriter = new StringWriter(); - writer.write( stringWriter, metadata ); + writer.write(stringWriter, metadata); return stringWriter.toString().getBytes().length; - } - catch ( MetadataNotFoundException e ) - { - throw new IOException( "File not found", e ); + } catch (MetadataNotFoundException e) { + throw new IOException("File not found", e); } } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - try - { - Metadata metadata = store.getMetadata( path ); + public InputStream getInputStream() throws IOException { + try { + Metadata metadata = store.getMetadata(path); MetadataXpp3Writer writer = new MetadataXpp3Writer(); StringWriter stringWriter = new StringWriter(); - writer.write( stringWriter, metadata ); - return new ByteArrayInputStream( stringWriter.toString().getBytes() ); - } - catch ( MetadataNotFoundException e ) - { + writer.write(stringWriter, metadata); + return new ByteArrayInputStream(stringWriter.toString().getBytes()); + } catch (MetadataNotFoundException e) { return null; } } @@ -120,17 +107,11 @@ public InputStream getInputStream() /** * {@inheritDoc} */ - public long getLastModified() - throws IOException - { - try - { - return store.getMetadataLastModified( path ); - } - catch ( MetadataNotFoundException e ) - { - throw new IOException( "File not found", e ); + public long getLastModified() throws IOException { + try { + return store.getMetadataLastModified(path); + } catch (MetadataNotFoundException e) { + 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 b65b7b14..641e35ae 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 @@ -71,9 +71,7 @@ * * @since 1.0 */ -public class MockArtifactStore - extends BaseArtifactStore -{ +public class MockArtifactStore extends BaseArtifactStore { private final Log log; @@ -93,7 +91,6 @@ public class MockArtifactStore */ private Map>>> contents = new HashMap<>(); - private Content archetypeCatalog; /** @@ -102,9 +99,8 @@ public class MockArtifactStore * @param root the root to search for POMs within. * @since 1.0 */ - public MockArtifactStore( File root ) - { - this( null, root ); + public MockArtifactStore(File root) { + this(null, root); } /** @@ -114,9 +110,8 @@ public MockArtifactStore( File root ) * @param log the {@link Log} to log to. * @since 1.0 */ - public MockArtifactStore( Log log, File root ) - { - this( log, root, true ); + public MockArtifactStore(Log log, File root) { + this(log, root, true); } /** @@ -126,93 +121,76 @@ public MockArtifactStore( Log log, File root ) * @param log the {@link Log} to log to. * @since 1.0 */ - public MockArtifactStore( Log log, File root, boolean lazyArchiver ) - { + public MockArtifactStore(Log log, File root, boolean lazyArchiver) { this.log = log; this.lazyArchiver = lazyArchiver; - if ( root.isDirectory() ) - { + if (root.isDirectory()) { MavenXpp3Reader pomReader = new MavenXpp3Reader(); - Collection poms = FileUtils.listFiles( root, POM_EXTENSIONS, true ); - for ( File file : poms ) - { - try ( FileReader 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(); - set( new Artifact( groupId, model.getArtifactId(), version, "pom" ), - new FileContent( file ) ); - - final String basename = FilenameUtils.getBaseName( file.getName() ); - - if ( StringUtils.isEmpty( model.getPackaging() ) || "jar".equals( model.getPackaging() ) ) - { - File mainFile = new File( file.getParentFile(), basename + ".jar" ); + Collection poms = FileUtils.listFiles(root, POM_EXTENSIONS, true); + for (File file : poms) { + try (FileReader 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(); + set(new Artifact(groupId, model.getArtifactId(), version, "pom"), new FileContent(file)); + + final String basename = FilenameUtils.getBaseName(file.getName()); + + if (StringUtils.isEmpty(model.getPackaging()) || "jar".equals(model.getPackaging())) { + File mainFile = new File(file.getParentFile(), basename + ".jar"); Content content; - if ( mainFile.isDirectory() ) - { - content = new DirectoryContent( mainFile, lazyArchiver ); - } - else - { - content = new BytesContent( Utils.newEmptyJarContent() ); + if (mainFile.isDirectory()) { + content = new DirectoryContent(mainFile, lazyArchiver); + } else { + content = new BytesContent(Utils.newEmptyJarContent()); } - set( new Artifact( groupId, model.getArtifactId(), version, "jar" ), content ); - } - else if ( "maven-plugin".equals( model.getPackaging() ) ) - { - set( new Artifact( groupId, model.getArtifactId(), version, "jar" ), - new BytesContent( - Utils.newEmptyMavenPluginJarContent( groupId, model.getArtifactId(), - version ) ) ); + set(new Artifact(groupId, model.getArtifactId(), version, "jar"), content); + } else if ("maven-plugin".equals(model.getPackaging())) { + set( + new Artifact(groupId, model.getArtifactId(), version, "jar"), + new BytesContent( + Utils.newEmptyMavenPluginJarContent(groupId, model.getArtifactId(), version))); } File[] classifiedFiles = file.getParentFile() - .listFiles( ( dir, name ) -> FilenameUtils.getBaseName( name ).startsWith( basename + '-' ) ); + .listFiles((dir, name) -> + FilenameUtils.getBaseName(name).startsWith(basename + '-')); - for ( File classifiedFile : classifiedFiles ) - { - String type = org.codehaus.plexus.util.FileUtils.extension( classifiedFile.getName() ); - String classifier = - FilenameUtils.getBaseName( classifiedFile.getName() ).substring( basename.length() + 1 ); + for (File classifiedFile : classifiedFiles) { + String type = org.codehaus.plexus.util.FileUtils.extension(classifiedFile.getName()); + String classifier = FilenameUtils.getBaseName(classifiedFile.getName()) + .substring(basename.length() + 1); Content content; - if ( classifiedFile.isDirectory() ) - { - content = new DirectoryContent( classifiedFile, lazyArchiver ); - } - else - { - content = new FileContent( classifiedFile ); + if (classifiedFile.isDirectory()) { + content = new DirectoryContent(classifiedFile, lazyArchiver); + } else { + content = new FileContent(classifiedFile); } - set( new Artifact( groupId, model.getArtifactId(), version, classifier, type ), content ); + set(new Artifact(groupId, model.getArtifactId(), version, classifier, type), content); } - } - catch ( IOException e ) - { - if ( log != null ) - { - log.warn( "Could not read from " + file, e ); + } catch (IOException e) { + if (log != null) { + log.warn("Could not read from " + file, e); } - } - catch ( XmlPullParserException e ) - { - if ( log != null ) - { - log.warn( "Could not parse " + file, e ); + } catch (XmlPullParserException e) { + if (log != null) { + log.warn("Could not parse " + file, e); } } } - File archetypeCatalogFile = new File( root, "archetype-catalog.xml" ); - if ( archetypeCatalogFile.isFile() ) - { - archetypeCatalog = new FileContent( archetypeCatalogFile ); + File archetypeCatalogFile = new File(root, "archetype-catalog.xml"); + if (archetypeCatalogFile.isFile()) { + archetypeCatalog = new FileContent(archetypeCatalogFile); } } } @@ -220,27 +198,20 @@ else if ( "maven-plugin".equals( model.getPackaging() ) ) /** * {@inheritDoc} */ - public synchronized Set getGroupIds( String parentGroupId ) - { + public synchronized Set getGroupIds(String parentGroupId) { TreeSet result = new TreeSet<>(); - if ( StringUtils.isEmpty( parentGroupId ) ) - { - for ( String groupId : contents.keySet() ) - { - int index = groupId.indexOf( '.' ); - result.add( index == -1 ? groupId : groupId.substring( 0, index ) ); + if (StringUtils.isEmpty(parentGroupId)) { + for (String groupId : contents.keySet()) { + int index = groupId.indexOf('.'); + result.add(index == -1 ? groupId : groupId.substring(0, index)); } - } - else - { + } else { String prefix = parentGroupId + '.'; int start = prefix.length(); - for ( String groupId : contents.keySet() ) - { - if ( groupId.startsWith( prefix ) ) - { - int index = groupId.indexOf( '.', start ); - result.add( index == -1 ? groupId.substring( start ) : groupId.substring( start, index ) ); + for (String groupId : contents.keySet()) { + if (groupId.startsWith(prefix)) { + int index = groupId.indexOf('.', start); + result.add(index == -1 ? groupId.substring(start) : groupId.substring(start, index)); } } } @@ -250,67 +221,55 @@ public synchronized Set getGroupIds( String parentGroupId ) /** * {@inheritDoc} */ - public synchronized Set getArtifactIds( String groupId ) - { - Map>> artifactMap = contents.get( groupId ); - return artifactMap == null ? Collections.emptySet() : new TreeSet<>( artifactMap.keySet() ); + public synchronized Set getArtifactIds(String groupId) { + Map>> artifactMap = contents.get(groupId); + return artifactMap == null ? Collections.emptySet() : new TreeSet<>(artifactMap.keySet()); } /** * {@inheritDoc} */ - public synchronized Set getVersions( String groupId, String artifactId ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - return versionMap == null ? Collections.emptySet() : new TreeSet<>( versionMap.keySet() ); + public synchronized Set getVersions(String groupId, String artifactId) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + return versionMap == null ? Collections.emptySet() : new TreeSet<>(versionMap.keySet()); } /** * {@inheritDoc} */ - public synchronized Set getArtifacts( String groupId, String artifactId, String version ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); + public synchronized Set getArtifacts(String groupId, String artifactId, String version) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); - return filesMap == null ? Collections.emptySet() : new HashSet<>( filesMap.keySet() ); + return filesMap == null ? Collections.emptySet() : new HashSet<>(filesMap.keySet()); } /** * {@inheritDoc} */ - public synchronized long getLastModified( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized long getLastModified(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } return content.getLastModified(); @@ -319,36 +278,27 @@ public synchronized long getLastModified( Artifact artifact ) /** * {@inheritDoc} */ - public synchronized long getSize( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized long getSize(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } return content.getLength(); @@ -357,36 +307,27 @@ public synchronized long getSize( Artifact artifact ) /** * {@inheritDoc} */ - public synchronized InputStream get( Artifact artifact ) - throws IOException, ArtifactNotFoundException - { - Map>> artifactMap = contents.get( artifact.getGroupId() ); + public synchronized InputStream get(Artifact artifact) throws IOException, ArtifactNotFoundException { + Map>> artifactMap = contents.get(artifact.getGroupId()); Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifact.getArtifactId() ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( artifact.getVersion() ) ); - Content content = ( filesMap == null ? null : filesMap.get( artifact ) ); - if ( content == null ) - { - if ( artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null ) - { + (artifactMap == null ? null : artifactMap.get(artifact.getArtifactId())); + Map filesMap = (versionMap == null ? null : versionMap.get(artifact.getVersion())); + Content content = (filesMap == null ? null : filesMap.get(artifact)); + if (content == null) { + if (artifact.isSnapshot() && artifact.getTimestamp() == null && filesMap != null) { Artifact best = null; - for ( Map.Entry entry : filesMap.entrySet() ) - { + for (Map.Entry entry : filesMap.entrySet()) { Artifact a = entry.getKey(); - if ( artifact.equalSnapshots( a ) && ( best == null || best.compareTo( a ) < 0 ) ) - { + if (artifact.equalSnapshots(a) && (best == null || best.compareTo(a) < 0)) { best = a; content = entry.getValue(); } } - if ( content == null ) - { - throw new ArtifactNotFoundException( artifact ); + if (content == null) { + throw new ArtifactNotFoundException(artifact); } - } - else - { - throw new ArtifactNotFoundException( artifact ); + } else { + throw new ArtifactNotFoundException(artifact); } } return content.getInputStream(); @@ -395,16 +336,11 @@ public synchronized InputStream get( Artifact artifact ) /** * {@inheritDoc} */ - public synchronized void set( Artifact artifact, InputStream content ) - throws IOException - { - try - { - set( artifact, new BytesContent( IOUtils.toByteArray( content ) ) ); - } - finally - { - IOUtils.closeQuietly( content ); + public synchronized void set(Artifact artifact, InputStream content) throws IOException { + try { + set(artifact, new BytesContent(IOUtils.toByteArray(content))); + } finally { + IOUtils.closeQuietly(content); } } @@ -415,223 +351,179 @@ public synchronized void set( Artifact artifact, InputStream content ) * @param content the content. * @since 1.0 */ - private synchronized void set( Artifact artifact, Content content ) - { + private synchronized void set(Artifact artifact, Content content) { Map>> artifactMap = - contents.computeIfAbsent( artifact.getGroupId(), k -> new HashMap<>() ); + 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 ); + artifactMap.computeIfAbsent(artifact.getArtifactId(), k -> new HashMap<>()); + Map filesMap = versionMap.computeIfAbsent(artifact.getVersion(), k -> new HashMap<>()); + filesMap.put(artifact, content); } /** * {@inheritDoc} */ - @SuppressWarnings( "checkstyle:MethodLength" ) - public synchronized Metadata getMetadata( String path ) - throws IOException, MetadataNotFoundException - { + @SuppressWarnings("checkstyle:MethodLength") + public synchronized Metadata getMetadata(String path) throws IOException, MetadataNotFoundException { Metadata metadata = new Metadata(); boolean foundMetadata = false; - path = StringUtils.stripEnd( StringUtils.stripStart( path, "/" ), "/" ); - String groupId = path.replace( '/', '.' ); - Set pluginArtifactIds = getArtifactIds( groupId ); - if ( pluginArtifactIds != null ) - { + path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); + String groupId = path.replace('/', '.'); + Set pluginArtifactIds = getArtifactIds(groupId); + if (pluginArtifactIds != null) { List plugins = new ArrayList<>(); - for ( String artifactId : pluginArtifactIds ) - { - Set pluginVersions = getVersions( groupId, artifactId ); - if ( pluginVersions == null || pluginVersions.isEmpty() ) - { + for (String artifactId : pluginArtifactIds) { + Set pluginVersions = getVersions(groupId, artifactId); + if (pluginVersions == null || pluginVersions.isEmpty()) { continue; } - String[] versions = pluginVersions.toArray( new String[0] ); - Arrays.sort( versions, INSTANCE ); - for ( int j = versions.length - 1; j >= 0; j-- ) - { - try ( InputStream inputStream = get( new Artifact( groupId, artifactId, versions[j], "pom" ) ) ) - { - Model model = new MavenXpp3Reader().read( new XmlStreamReader( inputStream ) ); - if ( model == null || !"maven-plugin".equals( model.getPackaging() ) ) - { + String[] versions = pluginVersions.toArray(new String[0]); + Arrays.sort(versions, INSTANCE); + for (int j = versions.length - 1; j >= 0; j--) { + try (InputStream inputStream = get(new Artifact(groupId, artifactId, versions[j], "pom"))) { + Model model = new MavenXpp3Reader().read(new XmlStreamReader(inputStream)); + if (model == null || !"maven-plugin".equals(model.getPackaging())) { continue; } Plugin plugin = new Plugin(); - plugin.setArtifactId( artifactId ); - plugin.setName( model.getName() ); + plugin.setArtifactId(artifactId); + plugin.setName(model.getName()); // TODO proper goal-prefix determination // ugh! this is incredibly hacky and does not handle some fool that sets the goal prefix in // a parent pom... ok unlikely, but stupid is as stupid does boolean havePrefix = false; final Build build = model.getBuild(); - if ( build != null && build.getPlugins() != null ) - { - havePrefix = setPluginGoalPrefixFromConfiguration( plugin, build.getPlugins() ); + if (build != null && build.getPlugins() != null) { + havePrefix = setPluginGoalPrefixFromConfiguration(plugin, build.getPlugins()); } - if ( !havePrefix && build != null && build.getPluginManagement() != null - && build.getPluginManagement().getPlugins() != null ) - { - havePrefix = setPluginGoalPrefixFromConfiguration( plugin, - build.getPluginManagement() - .getPlugins() ); + if (!havePrefix + && build != null + && build.getPluginManagement() != null + && build.getPluginManagement().getPlugins() != null) { + havePrefix = setPluginGoalPrefixFromConfiguration( + plugin, build.getPluginManagement().getPlugins()); } - if ( !havePrefix && artifactId.startsWith( "maven-" ) && artifactId.endsWith( "-plugin" ) ) - { + if (!havePrefix && artifactId.startsWith("maven-") && artifactId.endsWith("-plugin")) { plugin.setPrefix( - StringUtils.removeStart( StringUtils.removeEnd( artifactId, "-plugin" ), "maven-" ) ); + StringUtils.removeStart(StringUtils.removeEnd(artifactId, "-plugin"), "maven-")); havePrefix = true; } - if ( !havePrefix && artifactId.endsWith( "-maven-plugin" ) ) - { - plugin.setPrefix( StringUtils.removeEnd( artifactId, "-maven-plugin" ) ); + if (!havePrefix && artifactId.endsWith("-maven-plugin")) { + plugin.setPrefix(StringUtils.removeEnd(artifactId, "-maven-plugin")); havePrefix = true; } - if ( !havePrefix ) - { - plugin.setPrefix( artifactId ); + if (!havePrefix) { + plugin.setPrefix(artifactId); } - plugins.add( plugin ); + plugins.add(plugin); foundMetadata = true; break; - } - catch ( ArtifactNotFoundException | XmlPullParserException e ) - { + } catch (ArtifactNotFoundException | XmlPullParserException e) { // ignore } } } - if ( !plugins.isEmpty() ) - { - metadata.setPlugins( plugins ); + if (!plugins.isEmpty()) { + metadata.setPlugins(plugins); } } - int index = path.lastIndexOf( '/' ); - groupId = ( index == -1 ? groupId : groupId.substring( 0, index ) ).replace( '/', '.' ); - String artifactId = ( index == -1 ? null : path.substring( index + 1 ) ); - if ( artifactId != null ) - { - Set artifactVersions = getVersions( groupId, artifactId ); - if ( artifactVersions != null && !artifactVersions.isEmpty() ) - { - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); + int index = path.lastIndexOf('/'); + groupId = (index == -1 ? groupId : groupId.substring(0, index)).replace('/', '.'); + String artifactId = (index == -1 ? null : path.substring(index + 1)); + if (artifactId != null) { + Set artifactVersions = getVersions(groupId, artifactId); + if (artifactVersions != null && !artifactVersions.isEmpty()) { + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); Versioning versioning = new Versioning(); - List versions = new ArrayList<>( artifactVersions ); - versions.sort( INSTANCE ); // sort the Maven way + List versions = new ArrayList<>(artifactVersions); + versions.sort(INSTANCE); // sort the Maven way long lastUpdated = 0; - for ( String version : versions ) - { - try - { - long lastModified = getLastModified( new Artifact( groupId, artifactId, version, "pom" ) ); - versioning.addVersion( version ); - if ( lastModified >= lastUpdated ) - { + for (String version : versions) { + try { + long lastModified = getLastModified(new Artifact(groupId, artifactId, version, "pom")); + versioning.addVersion(version); + if (lastModified >= lastUpdated) { lastUpdated = lastModified; - versioning.setLastUpdatedTimestamp( new Date( lastModified ) ); - versioning.setLatest( version ); - if ( !version.endsWith( "-SNAPSHOT" ) ) - { - versioning.setRelease( version ); + versioning.setLastUpdatedTimestamp(new Date(lastModified)); + versioning.setLatest(version); + if (!version.endsWith("-SNAPSHOT")) { + versioning.setRelease(version); } } - } - catch ( ArtifactNotFoundException e ) - { + } catch (ArtifactNotFoundException e) { // ignore } } - metadata.setVersioning( versioning ); + metadata.setVersioning(versioning); foundMetadata = true; } } - int index2 = index == -1 ? -1 : path.lastIndexOf( '/', index - 1 ); - groupId = index2 == -1 ? groupId : groupId.substring( 0, index2 ).replace( '/', '.' ); - artifactId = index2 == -1 ? artifactId : path.substring( index2 + 1, index ); - String version = index2 == -1 ? null : path.substring( index + 1 ); - if ( version != null && version.endsWith( "-SNAPSHOT" ) ) - { - Map>> artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - if ( filesMap != null ) - { + int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); + groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); + artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); + String version = index2 == -1 ? null : path.substring(index + 1); + if (version != null && version.endsWith("-SNAPSHOT")) { + Map>> artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); + if (filesMap != null) { List snapshotVersions = new ArrayList<>(); int maxBuildNumber = 0; long lastUpdated = 0; String timestamp = null; boolean found = false; - for ( final Map.Entry entry : filesMap.entrySet() ) - { + for (final Map.Entry entry : filesMap.entrySet()) { final Artifact artifact = entry.getKey(); final Content content = entry.getValue(); - SimpleDateFormat fmt = new SimpleDateFormat( "yyyyMMddHHmmss" ); - fmt.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - String lastUpdatedTime = fmt.format( new Date( content.getLastModified() ) ); - try - { - Maven3.addSnapshotVersion( snapshotVersions, artifact, lastUpdatedTime ); - } - catch ( LinkageError e ) - { + SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss"); + fmt.setTimeZone(TimeZone.getTimeZone("GMT")); + String lastUpdatedTime = fmt.format(new Date(content.getLastModified())); + try { + Maven3.addSnapshotVersion(snapshotVersions, artifact, lastUpdatedTime); + } catch (LinkageError e) { // Maven 2 } - if ( "pom".equals( artifact.getType() ) ) - { - if ( artifact.getBuildNumber() != null - && maxBuildNumber < artifact.getBuildNumber() ) - { + if ("pom".equals(artifact.getType())) { + if (artifact.getBuildNumber() != null && maxBuildNumber < artifact.getBuildNumber()) { maxBuildNumber = artifact.getBuildNumber(); timestamp = artifact.getTimestampString(); + } else { + maxBuildNumber = Math.max(1, maxBuildNumber); } - else - { - maxBuildNumber = Math.max( 1, maxBuildNumber ); - } - lastUpdated = Math.max( lastUpdated, content.getLastModified() ); + lastUpdated = Math.max(lastUpdated, content.getLastModified()); found = true; } } - if ( !snapshotVersions.isEmpty() || found ) - { + if (!snapshotVersions.isEmpty() || found) { Versioning versioning = metadata.getVersioning(); - if ( versioning == null ) - { + if (versioning == null) { versioning = new Versioning(); } - metadata.setGroupId( groupId ); - metadata.setArtifactId( artifactId ); - metadata.setVersion( version ); - try - { - Maven3.addSnapshotVersions( versioning, snapshotVersions ); - } - catch ( LinkageError e ) - { + metadata.setGroupId(groupId); + metadata.setArtifactId(artifactId); + metadata.setVersion(version); + try { + Maven3.addSnapshotVersions(versioning, snapshotVersions); + } catch (LinkageError e) { // Maven 2 } - if ( maxBuildNumber > 0 ) - { + if (maxBuildNumber > 0) { Snapshot snapshot = new Snapshot(); - snapshot.setBuildNumber( maxBuildNumber ); - snapshot.setTimestamp( timestamp ); - versioning.setSnapshot( snapshot ); + snapshot.setBuildNumber(maxBuildNumber); + snapshot.setTimestamp(timestamp); + versioning.setSnapshot(snapshot); } - versioning.setLastUpdatedTimestamp( new Date( lastUpdated ) ); - metadata.setVersioning( versioning ); + versioning.setLastUpdatedTimestamp(new Date(lastUpdated)); + metadata.setVersioning(versioning); foundMetadata = true; } } - } - if ( !foundMetadata ) - { - throw new MetadataNotFoundException( path ); + if (!foundMetadata) { + throw new MetadataNotFoundException(path); } return metadata; } @@ -639,132 +531,95 @@ public synchronized Metadata getMetadata( String path ) /** * {@inheritDoc} */ - public synchronized long getMetadataLastModified( String path ) - throws IOException, MetadataNotFoundException - { + public synchronized long getMetadataLastModified(String path) throws IOException, MetadataNotFoundException { boolean haveResult = false; long result = 0; - path = StringUtils.stripEnd( StringUtils.stripStart( path, "/" ), "/" ); - String groupId = path.replace( '/', '.' ); - Map>> artifactMap = contents.get( groupId ); - if ( artifactMap != null ) - { - for ( Map> versionMap : artifactMap.values() ) - { - for ( Map filesMap : versionMap.values() ) - { - for ( Content content : filesMap.values() ) - { + path = StringUtils.stripEnd(StringUtils.stripStart(path, "/"), "/"); + String groupId = path.replace('/', '.'); + Map>> artifactMap = contents.get(groupId); + if (artifactMap != null) { + for (Map> versionMap : artifactMap.values()) { + for (Map filesMap : versionMap.values()) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } } - int index = path.lastIndexOf( '/' ); - groupId = index == -1 ? groupId : groupId.substring( 0, index ).replace( '/', '.' ); - String artifactId = ( index == -1 ? null : path.substring( index + 1 ) ); - if ( artifactId != null ) - { - artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - if ( versionMap != null ) - { - for ( Map filesMap : versionMap.values() ) - { - for ( Content content : filesMap.values() ) - { + int index = path.lastIndexOf('/'); + groupId = index == -1 ? groupId : groupId.substring(0, index).replace('/', '.'); + String artifactId = (index == -1 ? null : path.substring(index + 1)); + if (artifactId != null) { + artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + if (versionMap != null) { + for (Map filesMap : versionMap.values()) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } } - int index2 = index == -1 ? -1 : path.lastIndexOf( '/', index - 1 ); - groupId = index2 == -1 ? groupId : groupId.substring( 0, index2 ).replace( '/', '.' ); - artifactId = index2 == -1 ? artifactId : path.substring( index2 + 1, index ); - String version = index2 == -1 ? null : path.substring( index + 1 ); - if ( version != null && version.endsWith( "-SNAPSHOT" ) ) - { - artifactMap = contents.get( groupId ); - Map> versionMap = - ( artifactMap == null ? null : artifactMap.get( artifactId ) ); - Map filesMap = ( versionMap == null ? null : versionMap.get( version ) ); - if ( filesMap != null ) - { - for ( Content content : filesMap.values() ) - { + int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1); + groupId = index2 == -1 ? groupId : groupId.substring(0, index2).replace('/', '.'); + artifactId = index2 == -1 ? artifactId : path.substring(index2 + 1, index); + String version = index2 == -1 ? null : path.substring(index + 1); + if (version != null && version.endsWith("-SNAPSHOT")) { + artifactMap = contents.get(groupId); + Map> versionMap = (artifactMap == null ? null : artifactMap.get(artifactId)); + Map filesMap = (versionMap == null ? null : versionMap.get(version)); + if (filesMap != null) { + for (Content content : filesMap.values()) { haveResult = true; - result = Math.max( result, content.getLastModified() ); + result = Math.max(result, content.getLastModified()); } } } - if ( haveResult ) - { + if (haveResult) { return result; } - throw new MetadataNotFoundException( path ); + throw new MetadataNotFoundException(path); } - public ArchetypeCatalog getArchetypeCatalog() - throws IOException, ArchetypeCatalogNotFoundException - { - if ( archetypeCatalog != null ) - { + public ArchetypeCatalog getArchetypeCatalog() throws IOException, ArchetypeCatalogNotFoundException { + if (archetypeCatalog != null) { ArchetypeCatalogXpp3Reader reader = new ArchetypeCatalogXpp3Reader(); - try - { - return reader.read( archetypeCatalog.getInputStream() ); - } - catch ( IOException e ) - { - if ( log != null ) - { - log.warn( "Could not read from archetype-catalog.xml", e ); + try { + return reader.read(archetypeCatalog.getInputStream()); + } catch (IOException e) { + if (log != null) { + log.warn("Could not read from archetype-catalog.xml", e); } - } - catch ( XmlPullParserException e ) - { + } catch (XmlPullParserException e) { - if ( log != null ) - { - log.warn( "Could not parse archetype-catalog.xml", e ); + if (log != null) { + log.warn("Could not parse archetype-catalog.xml", e); } } } throw new ArchetypeCatalogNotFoundException(); } - - public long getArchetypeCatalogLastModified() - throws ArchetypeCatalogNotFoundException - { - if ( archetypeCatalog != null ) - { + public long getArchetypeCatalogLastModified() throws ArchetypeCatalogNotFoundException { + if (archetypeCatalog != null) { return archetypeCatalog.getLastModified(); - } - else - { + } else { throw new ArchetypeCatalogNotFoundException(); } } - private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, - List pluginConfigs ) - { - for ( org.apache.maven.model.Plugin def : pluginConfigs ) - { - if ( ( def.getGroupId() == null || StringUtils.equals( "org.apache.maven.plugins", def.getGroupId() ) ) - && StringUtils.equals( "maven-plugin-plugin", def.getArtifactId() ) ) - { + private boolean setPluginGoalPrefixFromConfiguration( + Plugin plugin, List pluginConfigs) { + for (org.apache.maven.model.Plugin def : pluginConfigs) { + if ((def.getGroupId() == null || StringUtils.equals("org.apache.maven.plugins", def.getGroupId())) + && StringUtils.equals("maven-plugin-plugin", def.getArtifactId())) { Xpp3Dom configuration = (Xpp3Dom) def.getConfiguration(); - if ( configuration != null ) - { - final Xpp3Dom goalPrefix = configuration.getChild( "goalPrefix" ); - if ( goalPrefix != null ) - { - plugin.setPrefix( goalPrefix.getValue() ); + if (configuration != null) { + final Xpp3Dom goalPrefix = configuration.getChild("goalPrefix"); + if (goalPrefix != null) { + plugin.setPrefix(goalPrefix.getValue()); return true; } } @@ -781,18 +636,15 @@ private boolean setPluginGoalPrefixFromConfiguration( Plugin plugin, * * @since 1.0 */ - private static class VersionComparator - implements Comparator - { + private static class VersionComparator implements Comparator { /** * {@inheritDoc} */ - @SuppressWarnings( "unchecked" ) - public int compare( String o1, String o2 ) - { - ArtifactVersion v1 = new DefaultArtifactVersion( o1 ); - ArtifactVersion v2 = new DefaultArtifactVersion( o2 ); - return v1.compareTo( v2 ); + @SuppressWarnings("unchecked") + public int compare(String o1, String o2) { + ArtifactVersion v1 = new DefaultArtifactVersion(o1); + ArtifactVersion v2 = new DefaultArtifactVersion(o2); + return v1.compareTo(v2); } } @@ -801,8 +653,7 @@ public int compare( String o1, String o2 ) * * @since 1.0 */ - private interface Content - { + private interface Content { /** * Returns the last modified timestamp. @@ -818,8 +669,7 @@ private interface Content * @return the content. * @throws IOException if something went wrong. */ - InputStream getInputStream() - throws IOException; + InputStream getInputStream() throws IOException; /** * Returns the length of the content. @@ -834,9 +684,7 @@ InputStream getInputStream() * * @since 1.0 */ - private static class BytesContent - implements Content - { + private static class BytesContent implements Content { /** * The last modified timestamp. @@ -858,8 +706,7 @@ private static class BytesContent * @param bytes the content. * @since 1.0 */ - private BytesContent( byte[] bytes ) - { + private BytesContent(byte[] bytes) { this.lastModified = System.currentTimeMillis(); this.bytes = bytes; } @@ -867,25 +714,21 @@ private BytesContent( byte[] bytes ) /** * {@inheritDoc} */ - public long getLastModified() - { + public long getLastModified() { return lastModified; } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new ByteArrayInputStream( bytes ); + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(bytes); } /** * {@inheritDoc} */ - public long getLength() - { + public long getLength() { return bytes.length; } } @@ -895,9 +738,7 @@ public long getLength() * * @since 1.0 */ - private static class FileContent - implements Content - { + private static class FileContent implements Content { /** * The backing file. @@ -912,39 +753,33 @@ private static class FileContent * @param file the backing file. * @since 1.0 */ - private FileContent( File file ) - { + private FileContent(File file) { this.file = file; } /** * {@inheritDoc} */ - public long getLastModified() - { + public long getLastModified() { return file.lastModified(); } /** * {@inheritDoc} */ - public InputStream getInputStream() - throws IOException - { - return new FileInputStream( file ); + public InputStream getInputStream() throws IOException { + return new FileInputStream(file); } /** * {@inheritDoc} */ - public long getLength() - { + public long getLength() { return file.length(); } } - private static class DirectoryContent implements Content - { + private static class DirectoryContent implements Content { private final File directory; private File archivedFile; @@ -953,56 +788,43 @@ private static class DirectoryContent implements Content * @param directory the directory to archive * @param lazy {@code false} if the archive should be created immediately */ - private DirectoryContent( File directory, boolean lazy ) - { + private DirectoryContent(File directory, boolean lazy) { this.directory = directory; - if ( !lazy ) - { + if (!lazy) { createArchive(); } } - private void createArchive() - { + private void createArchive() { JarArchiver archiver = new JarArchiver(); - archivedFile = new File( directory.getParentFile(), "_" + directory.getName() ); - archiver.setDestFile( archivedFile ); - archiver.addDirectory( directory ); + archivedFile = new File(directory.getParentFile(), "_" + directory.getName()); + archiver.setDestFile(archivedFile); + archiver.addDirectory(directory); - try - { + try { archiver.createArchive(); - } - catch ( ArchiverException | IOException e ) - { - throw new RuntimeException( e.getMessage(), e ); + } catch (ArchiverException | IOException e) { + throw new RuntimeException(e.getMessage(), e); } } - public long getLastModified() - { - if ( archivedFile == null ) - { + public long getLastModified() { + if (archivedFile == null) { createArchive(); } return archivedFile.lastModified(); } - public InputStream getInputStream() - throws IOException - { - if ( archivedFile == null ) - { + public InputStream getInputStream() throws IOException { + if (archivedFile == null) { createArchive(); } - return new FileInputStream( archivedFile ); + return new FileInputStream(archivedFile); } - public long getLength() - { - if ( archivedFile == null ) - { + public long getLength() { + if (archivedFile == null) { createArchive(); } return archivedFile.length(); @@ -1016,8 +838,7 @@ public long getLength() * * @since 1.0 */ - private static class Maven3 - { + private static class Maven3 { /** * Adds a snapshot version to the list of snapshot versions. * @@ -1026,20 +847,16 @@ private static class Maven3 * @param lastUpdatedTime the time to flag for last updated. * @since 1.0 */ - private static void addSnapshotVersion( List snapshotVersions, Artifact artifact, - String lastUpdatedTime ) - { - try - { + private static void addSnapshotVersion( + List snapshotVersions, Artifact artifact, String lastUpdatedTime) { + try { SnapshotVersion snapshotVersion = new SnapshotVersion(); - snapshotVersion.setExtension( artifact.getType() ); - snapshotVersion.setClassifier( artifact.getClassifier() == null ? "" : artifact.getClassifier() ); - snapshotVersion.setVersion( artifact.getTimestampVersion() ); - snapshotVersion.setUpdated( lastUpdatedTime ); - snapshotVersions.add( snapshotVersion ); - } - catch ( NoClassDefFoundError e ) - { + snapshotVersion.setExtension(artifact.getType()); + snapshotVersion.setClassifier(artifact.getClassifier() == null ? "" : artifact.getClassifier()); + snapshotVersion.setVersion(artifact.getTimestampVersion()); + snapshotVersion.setUpdated(lastUpdatedTime); + snapshotVersions.add(snapshotVersion); + } catch (NoClassDefFoundError e) { // Maven 2 } } @@ -1051,17 +868,12 @@ private static void addSnapshotVersion( List snapshotVersions, * @param snapshotVersions the snapshot versions to add. * @since 1.0 */ - private static void addSnapshotVersions( Versioning versioning, List snapshotVersions ) - { - try - { - for ( SnapshotVersion snapshotVersion : snapshotVersions ) - { - versioning.addSnapshotVersion( snapshotVersion ); + private static void addSnapshotVersions(Versioning versioning, List snapshotVersions) { + try { + for (SnapshotVersion snapshotVersion : snapshotVersions) { + versioning.addSnapshotVersion(snapshotVersion); } - } - catch ( NoClassDefFoundError e ) - { + } catch (NoClassDefFoundError e) { // Maven 2 } } 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 0e7d3ebc..593ac1df 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 @@ -7,30 +7,26 @@ /** * Repository used for distribution management - * + * * @author Robert Scholte * @since 1.1.0 */ -public class HostedRepo implements ArtifactStoreFactory -{ +public class HostedRepo implements ArtifactStoreFactory { /** * The directory to store the uploaded files */ private File target; - + @Override - public ArtifactStore newInstance() - { - if ( target == null ) - { - throw new IllegalStateException( "Must provide the 'target' of the hosted repository" ); + public ArtifactStore newInstance() { + if (target == null) { + throw new IllegalStateException("Must provide the 'target' of the hosted repository"); } - return new DiskArtifactStore( target ).canWrite( true ); + return new DiskArtifactStore(target).canWrite(true); } @Override - public String toString() - { + public String 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 ef38e5a9..fa89979f 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 @@ -1,18 +1,16 @@ package org.codehaus.mojo.mrm.plugin; +import java.io.File; + import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.codehaus.mojo.mrm.impl.maven.DiskArtifactStore; -import java.io.File; - /** * A locally stored Maven repository. * * @since 1.0 */ -public class LocalRepo - implements ArtifactStoreFactory -{ +public class LocalRepo implements ArtifactStoreFactory { /** * Our source. @@ -24,20 +22,17 @@ public class LocalRepo /** * {@inheritDoc} */ - public ArtifactStore newInstance() - { - if ( source == null ) - { - throw new IllegalStateException( "Must provide the 'source' of the local repository" ); + public ArtifactStore newInstance() { + if (source == null) { + throw new IllegalStateException("Must provide the 'source' of the local repository"); } - return new DiskArtifactStore( source ); + return new DiskArtifactStore(source); } /** * {@inheritDoc} */ - public String toString() - { + public String 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 11715677..ef954dad 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 @@ -1,20 +1,18 @@ package org.codehaus.mojo.mrm.plugin; +import java.io.File; +import java.io.IOException; + import org.apache.commons.io.FileUtils; import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.codehaus.mojo.mrm.impl.maven.MockArtifactStore; -import java.io.File; -import java.io.IOException; - /** * A mock Maven repository. * * @since 1.0 */ -public class MockRepo - implements ArtifactStoreFactory, FactoryHelperRequired -{ +public class MockRepo implements ArtifactStoreFactory, FactoryHelperRequired { /** * Our helper. @@ -55,59 +53,46 @@ public class MockRepo /** * {@inheritDoc} */ - public ArtifactStore newInstance() - { - if ( factoryHelper == null ) - { - throw new IllegalStateException( "FactoryHelper has not been set" ); + public ArtifactStore newInstance() { + if (factoryHelper == null) { + throw new IllegalStateException("FactoryHelper has not been set"); } - if ( source == null ) - { - throw new IllegalStateException( "Must provide the 'source' of the mock repository" ); + if (source == null) { + throw new IllegalStateException("Must provide the 'source' of the mock repository"); } File root = source; - if ( cloneTo != null ) - { - if ( !cloneTo.mkdirs() && cloneClean ) - { - try - { - FileUtils.cleanDirectory( cloneTo ); - } - catch ( IOException e ) - { - throw new IllegalStateException( "Failed to clean directory: " + e.getMessage() ); + if (cloneTo != null) { + if (!cloneTo.mkdirs() && cloneClean) { + try { + FileUtils.cleanDirectory(cloneTo); + } catch (IOException e) { + throw new IllegalStateException("Failed to clean directory: " + e.getMessage()); } } - try - { - FileUtils.copyDirectory( source, cloneTo ); + try { + FileUtils.copyDirectory(source, cloneTo); root = cloneTo; - } - catch ( IOException e ) - { - throw new IllegalStateException( "Failed to copy directory: " + e.getMessage() ); + } catch (IOException e) { + throw new IllegalStateException("Failed to copy directory: " + e.getMessage()); } } - return new MockArtifactStore( factoryHelper.getLog(), root, lazyArchiver ); + return new MockArtifactStore(factoryHelper.getLog(), root, lazyArchiver); } /** * {@inheritDoc} */ - public void setFactoryHelper( FactoryHelper factoryHelper ) - { + public void setFactoryHelper(FactoryHelper factoryHelper) { this.factoryHelper = factoryHelper; } /** * {@inheritDoc} */ - public String toString() - { + public String 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 d9f61df2..0b415f2f 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 @@ -54,9 +54,7 @@ * * @since 1.0 */ -public class FileSystemServlet - extends HttpServlet -{ +public class FileSystemServlet extends HttpServlet { /** * Width of the name column in the HTML view. @@ -79,20 +77,17 @@ public class FileSystemServlet */ private final FileSystem fileSystem; - /** * @since 1.0 */ private String settingsServletPath; - /** * Default constructor. * * @since 1.0 */ - public FileSystemServlet() - { + public FileSystemServlet() { this.fileSystem = new MemoryFileSystem(); } @@ -102,8 +97,7 @@ public FileSystemServlet() * @param fileSystem the file systen to serve. * @since 1.0 */ - public FileSystemServlet( FileSystem fileSystem, String settingsServletPath ) - { + public FileSystemServlet(FileSystem fileSystem, String settingsServletPath) { this.fileSystem = fileSystem; this.settingsServletPath = settingsServletPath; } @@ -111,259 +105,196 @@ public FileSystemServlet( FileSystem fileSystem, String settingsServletPath ) /** * {@inheritDoc} */ - @SuppressWarnings( "checkstyle:MethodLength" ) - protected void doGet( HttpServletRequest req, HttpServletResponse resp ) - throws ServletException, IOException - { + @SuppressWarnings("checkstyle:MethodLength") + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); String context; - if ( path == null ) - { + if (path == null) { path = req.getServletPath(); context = req.getContextPath(); - } - else - { + } else { context = req.getContextPath() + req.getServletPath(); } - if ( path.equals( "/" + settingsServletPath ) ) - { - resp.setContentType( "text/xml" ); + if (path.equals("/" + settingsServletPath)) { + resp.setContentType("text/xml"); PrintWriter w = resp.getWriter(); String hostAddress; - try - { + try { hostAddress = InetAddress.getLocalHost().getHostAddress(); - } - catch ( UnknownHostException e ) - { + } catch (UnknownHostException e) { 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 ); + 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; } - Entry entry = fileSystem.get( path ); - if ( entry instanceof FileEntry ) - { + Entry entry = fileSystem.get(path); + if (entry instanceof FileEntry) { FileEntry fileEntry = (FileEntry) entry; long size = fileEntry.getSize(); - if ( size >= 0 && size < Integer.MAX_VALUE ) - { - resp.setContentLength( (int) size ); + if (size >= 0 && size < Integer.MAX_VALUE) { + resp.setContentLength((int) size); } - resp.setContentType( getServletContext().getMimeType( fileEntry.getName() ) ); + resp.setContentType(getServletContext().getMimeType(fileEntry.getName())); - LocalDateTime lastModifiedDate = LocalDateTime.ofEpochSecond( fileEntry.getLastModified() / 1000, - (int) ( fileEntry.getLastModified() % 1000 ), - ZoneOffset.UTC ); + LocalDateTime lastModifiedDate = LocalDateTime.ofEpochSecond( + fileEntry.getLastModified() / 1000, (int) (fileEntry.getLastModified() % 1000), ZoneOffset.UTC); String formattedLastModifiedDate = - lastModifiedDate.atZone( ZoneId.of( "UTC" ) ).format( DateTimeFormatter.RFC_1123_DATE_TIME ); - resp.addHeader( "Last-Modified", formattedLastModifiedDate ); + lastModifiedDate.atZone(ZoneId.of("UTC")).format(DateTimeFormatter.RFC_1123_DATE_TIME); + resp.addHeader("Last-Modified", formattedLastModifiedDate); - try ( InputStream source = fileEntry.getInputStream() ) - { - IOUtils.copy( source, resp.getOutputStream() ); + try (InputStream source = fileEntry.getInputStream()) { + IOUtils.copy(source, resp.getOutputStream()); } return; - } - else if ( entry instanceof DirectoryEntry ) - { - if ( !path.endsWith( "/" ) ) - { - resp.sendRedirect( entry.getName() + "/" ); + } else if (entry instanceof DirectoryEntry) { + if (!path.endsWith("/")) { + resp.sendRedirect(entry.getName() + "/"); return; } DirectoryEntry dirEntry = (DirectoryEntry) entry; - Entry[] entries = fileSystem.listEntries( dirEntry ); - resp.setContentType( "text/html" ); + Entry[] entries = fileSystem.listEntries(dirEntry); + resp.setContentType("text/html"); PrintWriter w = resp.getWriter(); - w.println( "" ); - w.println( " " ); - w.println( " Index of " + context + path + "" ); - w.println( " " ); - w.println( "" ); - w.println( "" ); - w.println( "

Index of " + context + path + "

" ); - w.println( "
" ); - w.write( "
" );
+            w.println("");
+            w.println("  ");
+            w.println("    Index of " + context + path + "");
+            w.println("    ");
+            w.println("");
+            w.println("");
+            w.println("

Index of " + context + path + "

"); + w.println("
"); + w.write("
");
 
-            if ( dirEntry.getParent() != null )
-            {
-                w.println( "../" );
+            if (dirEntry.getParent() != null) {
+                w.println("../");
             }
-            SimpleDateFormat format = new SimpleDateFormat( "dd-MMM-yyyy hh:mm" );
-            if ( entries != null )
-            {
-                for ( int i = 0; i < entries.length; i++ )
-                {
+            SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm");
+            if (entries != null) {
+                for (int i = 0; i < entries.length; i++) {
                     final String childName = entries[i].getName();
                     boolean directory = entries[i] instanceof DirectoryEntry;
-                    if ( directory )
-                    {
+                    if (directory) {
                         String dirName = childName + "/";
-                        w.write(
-                            "" + formatName( dirName )
-                                + "" + StringUtils.repeat( " ",
-                                                               Math.max( 0, NAME_COL_WIDTH - dirName.length() ) ) );
-                    }
-                    else
-                    {
-                        w.write(
-                            "" + formatName( childName )
-                                + "" + StringUtils.repeat( " ",
-                                                               Math.max( 0, NAME_COL_WIDTH - childName.length() ) ) );
+                        w.write("" + formatName(dirName)
+                                + "" + StringUtils.repeat(" ", Math.max(0, NAME_COL_WIDTH - dirName.length())));
+                    } else {
+                        w.write("" + formatName(childName)
+                                + "" + StringUtils.repeat(" ", Math.max(0, NAME_COL_WIDTH - childName.length())));
                     }
 
                     long timestamp = 0;
-                    try
-                    {
+                    try {
                         timestamp = entries[i].getLastModified();
-                    }
-                    catch ( IOException e )
-                    {
+                    } catch (IOException e) {
                         // ignore
                     }
 
-                    w.write( " " );
-                    w.write( format.format( timestamp != -1 ? new Date( timestamp ) : new Date() ) );
-                    if ( directory )
-                    {
-                        w.println( StringUtils.leftPad( "-", SIZE_COL_WIDTH ) );
-                    }
-                    else if ( entries[i] instanceof FileEntry )
-                    {
+                    w.write(" ");
+                    w.write(format.format(timestamp != -1 ? new Date(timestamp) : new Date()));
+                    if (directory) {
+                        w.println(StringUtils.leftPad("-", SIZE_COL_WIDTH));
+                    } else if (entries[i] instanceof FileEntry) {
                         FileEntry fileEntry = (FileEntry) entries[i];
-                        try
-                        {
+                        try {
                             long size = fileEntry.getSize();
-                            if ( size >= 0 )
-                            {
-                                w.println( StringUtils.leftPad( Long.toString( size ), SIZE_COL_WIDTH ) );
+                            if (size >= 0) {
+                                w.println(StringUtils.leftPad(Long.toString(size), SIZE_COL_WIDTH));
+                            } else {
+                                w.println(StringUtils.leftPad("-", SIZE_COL_WIDTH));
                             }
-                            else
-                            {
-                                w.println( StringUtils.leftPad( "-", SIZE_COL_WIDTH ) );
-                            }
-                        }
-                        catch ( IOException e )
-                        {
-                            w.println( StringUtils.leftPad( "-", SIZE_COL_WIDTH ) );
+                        } catch (IOException e) {
+                            w.println(StringUtils.leftPad("-", SIZE_COL_WIDTH));
                         }
-                    }
-                    else
-                    {
-                        w.println( StringUtils.leftPad( "-", SIZE_COL_WIDTH ) );
+                    } else {
+                        w.println(StringUtils.leftPad("-", SIZE_COL_WIDTH));
                     }
                 }
             }
-            w.write( "
" ); - w.println( "
" ); - w.println( "" ); - w.println( "" ); + w.write("
"); + w.println("
"); + w.println(""); + w.println(""); return; } - resp.sendError( HttpURLConnection.HTTP_NOT_FOUND ); + resp.sendError(HttpURLConnection.HTTP_NOT_FOUND); } /** * {@inheritDoc} */ - protected void doPut( HttpServletRequest req, HttpServletResponse resp ) - throws ServletException, IOException - { + protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); String context; - if ( path == null ) - { + if (path == null) { path = req.getServletPath(); context = req.getContextPath(); - } - else - { + } else { context = req.getContextPath() + req.getServletPath(); } - if ( path.endsWith( "/" ) ) - { - resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); + if (path.endsWith("/")) { + resp.sendError(HttpURLConnection.HTTP_BAD_METHOD); return; } - if ( path.startsWith( "/" ) ) - { - path = path.substring( 1 ); + if (path.startsWith("/")) { + path = path.substring(1); } - String[] parts = path.split( "/" ); - if ( parts.length == 0 ) - { - resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); + String[] parts = path.split("/"); + if (parts.length == 0) { + resp.sendError(HttpURLConnection.HTTP_BAD_METHOD); return; } String name = parts[parts.length - 1]; - if ( StringUtils.isEmpty( name ) ) - { - resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); + if (StringUtils.isEmpty(name)) { + resp.sendError(HttpURLConnection.HTTP_BAD_METHOD); return; } DirectoryEntry parent = fileSystem.getRoot(); - for ( int i = 0; i < parts.length - 1; i++ ) - { - parent = new DefaultDirectoryEntry( fileSystem, parent, parts[i] ); + for (int i = 0; i < parts.length - 1; i++) { + parent = new DefaultDirectoryEntry(fileSystem, parent, parts[i]); } - FileEntry put = fileSystem.put( parent, name, req.getInputStream() ); - if ( put != null ) - { - resp.setStatus( HttpURLConnection.HTTP_OK ); + FileEntry put = fileSystem.put(parent, name, req.getInputStream()); + if (put != null) { + resp.setStatus(HttpURLConnection.HTTP_OK); return; } - resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); + resp.sendError(HttpURLConnection.HTTP_BAD_METHOD); } /** * {@inheritDoc} */ - protected void doDelete( HttpServletRequest req, HttpServletResponse resp ) - throws ServletException, IOException - { + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); String context; - if ( path == null ) - { + if (path == null) { path = req.getServletPath(); context = req.getContextPath(); - } - else - { + } else { context = req.getContextPath() + req.getServletPath(); } - Entry entry = fileSystem.get( path ); - if ( entry == null ) - { - resp.setStatus( HttpURLConnection.HTTP_OK ); + Entry entry = fileSystem.get(path); + if (entry == null) { + resp.setStatus(HttpURLConnection.HTTP_OK); return; } - try - { - fileSystem.remove( entry ); - resp.setStatus( HttpURLConnection.HTTP_OK ); - } - catch ( UnsupportedOperationException e ) - { - resp.sendError( HttpURLConnection.HTTP_BAD_METHOD ); + try { + fileSystem.remove(entry); + resp.setStatus(HttpURLConnection.HTTP_OK); + } catch (UnsupportedOperationException e) { + resp.sendError(HttpURLConnection.HTTP_BAD_METHOD); } } @@ -373,13 +304,10 @@ protected void doDelete( HttpServletRequest req, HttpServletResponse resp ) * @param name the name. * @return the name or the name shortened to 50 characters. */ - private static String formatName( String name ) - { - if ( name.length() < NAME_COL_WIDTH ) - { + private static String formatName(String name) { + if (name.length() < NAME_COL_WIDTH) { return name; } - return name.substring( 0, NAME_COL_WIDTH - 1 ) + ">"; + return name.substring(0, NAME_COL_WIDTH - 1) + ">"; } - } diff --git a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntryTest.java b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntryTest.java index 467893db..bc716347 100644 --- a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntryTest.java +++ b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArchetypeCatalogFileEntryTest.java @@ -1,84 +1,71 @@ -package org.codehaus.mojo.mrm.impl.maven; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.maven.archetype.catalog.ArchetypeCatalog; -import org.codehaus.mojo.mrm.api.DirectoryEntry; -import org.codehaus.mojo.mrm.api.FileSystem; -import org.codehaus.mojo.mrm.api.maven.ArtifactStore; -import org.junit.Test; - -public class ArchetypeCatalogFileEntryTest -{ - - @Test - public void testCleanArchetypeCatalogFileEntry() - throws Exception - { - ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry( null, null, null ); - assertEquals( null, entry.getFileSystem() ); - assertEquals( null, entry.getParent() ); - assertEquals( "archetype-catalog.xml", entry.getName() ); - } - - @Test - public void testFileSystem() - throws Exception - { - FileSystem fileSystem = mock( FileSystem.class ); - DirectoryEntry root = mock( DirectoryEntry.class ); - when( fileSystem.getRoot() ).thenReturn( root ); - ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry( fileSystem, null, null ); - assertEquals( fileSystem, entry.getFileSystem() ); - assertEquals( null, entry.getParent() ); - assertEquals( "archetype-catalog.xml", entry.getName() ); - assertEquals( "archetype-catalog.xml", entry.toPath() ); - } - - @Test - public void testParent() - throws Exception - { - FileSystem fileSystem = mock( FileSystem.class ); - DirectoryEntry parent = mock( DirectoryEntry.class ); - when( fileSystem.getRoot() ).thenReturn( parent ); - ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry( fileSystem, parent, null ); - assertEquals( fileSystem, entry.getFileSystem() ); - assertEquals( parent, entry.getParent() ); - assertEquals( "archetype-catalog.xml", entry.getName() ); - assertEquals( "archetype-catalog.xml", entry.toPath() ); - } - - @Test - public void testArtifactStore() - throws Exception - { - final long lastModified = System.currentTimeMillis(); - FileSystem fileSystem = mock( FileSystem.class ); - DirectoryEntry parent = mock( DirectoryEntry.class ); - when( fileSystem.getRoot() ).thenReturn( parent ); - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getArchetypeCatalog() ).thenReturn( new ArchetypeCatalog() ); - when( store.getArchetypeCatalogLastModified() ).thenReturn( lastModified ); - ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry( fileSystem, parent, store ); - assertEquals( fileSystem, entry.getFileSystem() ); - assertEquals( parent, entry.getParent() ); - assertEquals( "archetype-catalog.xml", entry.getName() ); - assertEquals( "archetype-catalog.xml", entry.toPath() ); - assertEquals( entry.getLastModified(), lastModified ); - assertTrue( entry.getSize() > 0 ); - try - { - assertNotNull( entry.getInputStream() ); - } - finally - { - entry.getInputStream().close(); - } - } - -} +package org.codehaus.mojo.mrm.impl.maven; + +import org.apache.maven.archetype.catalog.ArchetypeCatalog; +import org.codehaus.mojo.mrm.api.DirectoryEntry; +import org.codehaus.mojo.mrm.api.FileSystem; +import org.codehaus.mojo.mrm.api.maven.ArtifactStore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ArchetypeCatalogFileEntryTest { + + @Test + public void testCleanArchetypeCatalogFileEntry() throws Exception { + ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry(null, null, null); + assertEquals(null, entry.getFileSystem()); + assertEquals(null, entry.getParent()); + assertEquals("archetype-catalog.xml", entry.getName()); + } + + @Test + public void testFileSystem() throws Exception { + FileSystem fileSystem = mock(FileSystem.class); + DirectoryEntry root = mock(DirectoryEntry.class); + when(fileSystem.getRoot()).thenReturn(root); + ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry(fileSystem, null, null); + assertEquals(fileSystem, entry.getFileSystem()); + assertEquals(null, entry.getParent()); + assertEquals("archetype-catalog.xml", entry.getName()); + assertEquals("archetype-catalog.xml", entry.toPath()); + } + + @Test + public void testParent() throws Exception { + FileSystem fileSystem = mock(FileSystem.class); + DirectoryEntry parent = mock(DirectoryEntry.class); + when(fileSystem.getRoot()).thenReturn(parent); + ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry(fileSystem, parent, null); + assertEquals(fileSystem, entry.getFileSystem()); + assertEquals(parent, entry.getParent()); + assertEquals("archetype-catalog.xml", entry.getName()); + assertEquals("archetype-catalog.xml", entry.toPath()); + } + + @Test + public void testArtifactStore() throws Exception { + final long lastModified = System.currentTimeMillis(); + FileSystem fileSystem = mock(FileSystem.class); + DirectoryEntry parent = mock(DirectoryEntry.class); + when(fileSystem.getRoot()).thenReturn(parent); + ArtifactStore store = mock(ArtifactStore.class); + when(store.getArchetypeCatalog()).thenReturn(new ArchetypeCatalog()); + when(store.getArchetypeCatalogLastModified()).thenReturn(lastModified); + ArchetypeCatalogFileEntry entry = new ArchetypeCatalogFileEntry(fileSystem, parent, store); + assertEquals(fileSystem, entry.getFileSystem()); + assertEquals(parent, entry.getParent()); + assertEquals("archetype-catalog.xml", entry.getName()); + assertEquals("archetype-catalog.xml", entry.toPath()); + assertEquals(entry.getLastModified(), lastModified); + assertTrue(entry.getSize() > 0); + try { + assertNotNull(entry.getInputStream()); + } finally { + entry.getInputStream().close(); + } + } +} diff --git a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystemTest.java b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystemTest.java index 7e2920b3..c3757d97 100644 --- a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystemTest.java +++ b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/ArtifactStoreFileSystemTest.java @@ -16,14 +16,6 @@ package org.codehaus.mojo.mrm.impl.maven; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import java.util.regex.Matcher; import org.apache.maven.archetype.catalog.ArchetypeCatalog; @@ -35,162 +27,160 @@ import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.junit.Test; -public class ArtifactStoreFileSystemTest -{ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ArtifactStoreFileSystemTest { @Test - public void testGroupMetadataRegex() - { - Matcher matcher = ArtifactStoreFileSystem.METADATA.matcher( "/commons/maven-metadata.xml" ); - assertTrue( matcher.matches() ); - assertEquals( "commons/", matcher.group( 1 ) ); - matcher = ArtifactStoreFileSystem.METADATA.matcher( "/org/apache/maven/maven-metadata.xml" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - matcher = ArtifactStoreFileSystem.METADATA.matcher( "/commons/commons/1.0/commons-1.0.pom" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.METADATA.matcher( "/org/apache/maven/pom/1.0/pom-1.0.pom" ); - assertFalse( matcher.matches() ); + public void testGroupMetadataRegex() { + Matcher matcher = ArtifactStoreFileSystem.METADATA.matcher("/commons/maven-metadata.xml"); + assertTrue(matcher.matches()); + assertEquals("commons/", matcher.group(1)); + matcher = ArtifactStoreFileSystem.METADATA.matcher("/org/apache/maven/maven-metadata.xml"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + matcher = ArtifactStoreFileSystem.METADATA.matcher("/commons/commons/1.0/commons-1.0.pom"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.METADATA.matcher("/org/apache/maven/pom/1.0/pom-1.0.pom"); + assertFalse(matcher.matches()); } @Test - public void testArtifactRegex() - { - Matcher matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/commons/maven-metadata.xml" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/org/apache/maven/maven-metadata.xml" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/commons/commons/1.0/commons-1.0.pom" ); - assertTrue( matcher.matches() ); - assertEquals( "commons/", matcher.group( 1 ) ); - assertEquals( "commons", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "commons-1.0.pom", matcher.group( 4 ) ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/org/apache/maven/pom/1.0/pom-1.0.pom" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0.pom", matcher.group( 4 ) ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT.pom" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0-SNAPSHOT", matcher.group( 3 ) ); - assertEquals( "pom-1.0-SNAPSHOT.pom", matcher.group( 4 ) ); + public void testArtifactRegex() { + Matcher matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/commons/maven-metadata.xml"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/org/apache/maven/maven-metadata.xml"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/commons/commons/1.0/commons-1.0.pom"); + assertTrue(matcher.matches()); + assertEquals("commons/", matcher.group(1)); + assertEquals("commons", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("commons-1.0.pom", matcher.group(4)); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/org/apache/maven/pom/1.0/pom-1.0.pom"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0.pom", matcher.group(4)); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT.pom"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0-SNAPSHOT", matcher.group(3)); + assertEquals("pom-1.0-SNAPSHOT.pom", matcher.group(4)); matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56.pom" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/commons/commons/1.0/commons-1.0-tests.jar" ); - assertTrue( matcher.matches() ); - assertEquals( "commons/", matcher.group( 1 ) ); - assertEquals( "commons", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "commons-1.0-tests.jar", matcher.group( 4 ) ); - matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( "/org/apache/maven/pom/1.0/pom-1.0-tests.jar" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0-tests.jar", matcher.group( 4 ) ); - matcher = - ArtifactStoreFileSystem.ARTIFACT.matcher( "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT-tests.jar" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0-SNAPSHOT", matcher.group( 3 ) ); - assertEquals( "pom-1.0-SNAPSHOT-tests.jar", matcher.group( 4 ) ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56.pom"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/commons/commons/1.0/commons-1.0-tests.jar"); + assertTrue(matcher.matches()); + assertEquals("commons/", matcher.group(1)); + assertEquals("commons", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("commons-1.0-tests.jar", matcher.group(4)); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher("/org/apache/maven/pom/1.0/pom-1.0-tests.jar"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0-tests.jar", matcher.group(4)); matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56-tests.jar" ); - assertFalse( matcher.matches() ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT-tests.jar"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0-SNAPSHOT", matcher.group(3)); + assertEquals("pom-1.0-SNAPSHOT-tests.jar", matcher.group(4)); + matcher = ArtifactStoreFileSystem.ARTIFACT.matcher( + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56-tests.jar"); + assertFalse(matcher.matches()); } @Test - public void testSnapshotArtifactRegex() - { - Matcher matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/commons/maven-metadata.xml" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/org/apache/maven/maven-metadata.xml" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/commons/commons/1.0/commons-1.0.pom" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/org/apache/maven/pom/1.0/pom-1.0.pom" ); - assertFalse( matcher.matches() ); + public void testSnapshotArtifactRegex() { + Matcher matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/commons/maven-metadata.xml"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/org/apache/maven/maven-metadata.xml"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/commons/commons/1.0/commons-1.0.pom"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/org/apache/maven/pom/1.0/pom-1.0.pom"); + assertFalse(matcher.matches()); matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT.pom" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0-SNAPSHOT.pom", matcher.group( 4 ) ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT.pom"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0-SNAPSHOT.pom", matcher.group(4)); matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56.pom" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0-20110101.123456-56.pom", matcher.group( 4 ) ); - matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/commons/commons/1.0/commons-1.0-tests.jar" ); - assertFalse( matcher.matches() ); - matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( "/org/apache/maven/pom/1.0/pom-1.0-tests.jar" ); - assertFalse( matcher.matches() ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56.pom"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0-20110101.123456-56.pom", matcher.group(4)); + matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/commons/commons/1.0/commons-1.0-tests.jar"); + assertFalse(matcher.matches()); + matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher("/org/apache/maven/pom/1.0/pom-1.0-tests.jar"); + assertFalse(matcher.matches()); matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT-tests.jar" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0-SNAPSHOT-tests.jar", matcher.group( 4 ) ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-SNAPSHOT-tests.jar"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0-SNAPSHOT-tests.jar", matcher.group(4)); matcher = ArtifactStoreFileSystem.SNAPSHOT_ARTIFACT.matcher( - "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56-tests.jar" ); - assertTrue( matcher.matches() ); - assertEquals( "org/apache/maven/", matcher.group( 1 ) ); - assertEquals( "pom", matcher.group( 2 ) ); - assertEquals( "1.0", matcher.group( 3 ) ); - assertEquals( "pom-1.0-20110101.123456-56-tests.jar", matcher.group( 4 ) ); + "/org/apache/maven/pom/1.0-SNAPSHOT/pom-1.0-20110101.123456-56-tests.jar"); + assertTrue(matcher.matches()); + assertEquals("org/apache/maven/", matcher.group(1)); + assertEquals("pom", matcher.group(2)); + assertEquals("1.0", matcher.group(3)); + assertEquals("pom-1.0-20110101.123456-56-tests.jar", matcher.group(4)); } - - + // MMOCKRM-5 @Test - public void testSiteXmlReleaseVersion() throws Exception - { - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getSize( isA( Artifact.class ) ) ).thenThrow( ArtifactNotFoundException.class ); - ArtifactStoreFileSystem system = new ArtifactStoreFileSystem( store ); - FileEntry entry = (FileEntry) system.get( "/localhost/mmockrm-5/1/mmockrm-5-1-site_en.xml" ); - assertNull( entry ); + public void testSiteXmlReleaseVersion() throws Exception { + ArtifactStore store = mock(ArtifactStore.class); + when(store.getSize(isA(Artifact.class))).thenThrow(ArtifactNotFoundException.class); + ArtifactStoreFileSystem system = new ArtifactStoreFileSystem(store); + FileEntry entry = (FileEntry) system.get("/localhost/mmockrm-5/1/mmockrm-5-1-site_en.xml"); + assertNull(entry); } - + @Test - public void testSiteXmlSnapshotVersion() throws Exception - { - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getSize( isA( Artifact.class ) ) ).thenThrow( ArtifactNotFoundException.class ); - ArtifactStoreFileSystem system = new ArtifactStoreFileSystem( store ); - FileEntry entry = (FileEntry) system.get( - "/localhost/mmockrm-5/1.0-SNAPSHOT/mmockrm-5-1.0-SNAPSHOT-site_en.xml" ); - assertNull( entry ); + public void testSiteXmlSnapshotVersion() throws Exception { + ArtifactStore store = mock(ArtifactStore.class); + when(store.getSize(isA(Artifact.class))).thenThrow(ArtifactNotFoundException.class); + ArtifactStoreFileSystem system = new ArtifactStoreFileSystem(store); + FileEntry entry = + (FileEntry) system.get("/localhost/mmockrm-5/1.0-SNAPSHOT/mmockrm-5-1.0-SNAPSHOT-site_en.xml"); + assertNull(entry); } - + @Test - public void testArchetypeCatalogNotFound() throws Exception - { - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getArchetypeCatalogLastModified() ).thenThrow( ArchetypeCatalogNotFoundException.class ); - ArtifactStoreFileSystem system = new ArtifactStoreFileSystem( store ); - Entry entry = system.get( "/archetype-catalog.xml" ); - assertNull( entry ); + public void testArchetypeCatalogNotFound() throws Exception { + ArtifactStore store = mock(ArtifactStore.class); + when(store.getArchetypeCatalogLastModified()).thenThrow(ArchetypeCatalogNotFoundException.class); + ArtifactStoreFileSystem system = new ArtifactStoreFileSystem(store); + Entry entry = system.get("/archetype-catalog.xml"); + assertNull(entry); } @Test - public void testArchetypeCatalog() throws Exception - { - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getArchetypeCatalog() ).thenReturn( new ArchetypeCatalog() ) ; - ArtifactStoreFileSystem system = new ArtifactStoreFileSystem( store ); - FileEntry entry = (FileEntry) system.get( "archetype-catalog.xml" ); - assertEquals( "archetype-catalog.xml", entry.getName() ); + public void testArchetypeCatalog() throws Exception { + ArtifactStore store = mock(ArtifactStore.class); + when(store.getArchetypeCatalog()).thenReturn(new ArchetypeCatalog()); + ArtifactStoreFileSystem system = new ArtifactStoreFileSystem(store); + FileEntry entry = (FileEntry) system.get("archetype-catalog.xml"); + assertEquals("archetype-catalog.xml", entry.getName()); } - } diff --git a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStoreTest.java b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStoreTest.java index 09ab5f8b..025368fb 100644 --- a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStoreTest.java +++ b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/CompositeArtifactStoreTest.java @@ -1,26 +1,23 @@ package org.codehaus.mojo.mrm.impl.maven; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import org.apache.maven.archetype.catalog.ArchetypeCatalog; import org.codehaus.mojo.mrm.api.maven.ArtifactStore; import org.junit.Test; -public class CompositeArtifactStoreTest -{ +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CompositeArtifactStoreTest { @Test - public void testGetArchetypeCatalog() - throws Exception - { - ArtifactStore store = mock( ArtifactStore.class ); - when( store.getArchetypeCatalog() ).thenReturn( new ArchetypeCatalog() ); - ArtifactStore[] stores = new ArtifactStore[] { store }; + public void testGetArchetypeCatalog() throws Exception { + ArtifactStore store = mock(ArtifactStore.class); + when(store.getArchetypeCatalog()).thenReturn(new ArchetypeCatalog()); + ArtifactStore[] stores = new ArtifactStore[] {store}; - CompositeArtifactStore artifactStore = new CompositeArtifactStore( stores ); + CompositeArtifactStore artifactStore = new CompositeArtifactStore(stores); ArchetypeCatalog catalog = artifactStore.getArchetypeCatalog(); - - assertNotNull( catalog ); + + assertNotNull(catalog); } } diff --git a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStoreTest.java b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStoreTest.java index 678fc3b2..d089d276 100644 --- a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStoreTest.java +++ b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/DiskArtifactStoreTest.java @@ -1,31 +1,28 @@ -package org.codehaus.mojo.mrm.impl.maven; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import org.apache.maven.archetype.catalog.Archetype; -import org.apache.maven.archetype.catalog.ArchetypeCatalog; -import org.junit.Test; - -public class DiskArtifactStoreTest -{ - - // MMOCKRM-10 - @Test - public void testArchetypeCatalog() throws Exception - { - DiskArtifactStore artifactStore = new DiskArtifactStore( new File( "src/test/resources/mmockrm-10" ) ); - ArchetypeCatalog catalog = artifactStore.getArchetypeCatalog(); - assertNotNull( catalog ); - assertEquals( 1, catalog.getArchetypes().size() ); - Archetype archetype = catalog.getArchetypes().get( 0 ); - assertEquals( "archetypes", archetype.getGroupId() ); - assertEquals( "fileset", archetype.getArtifactId() ); - assertEquals( "1.0", archetype.getVersion() ); - assertEquals( "Fileset test archetype", archetype.getDescription() ); - assertEquals( "file://${basedir}/target/test-classes/repositories/central", archetype.getRepository() ); - } - -} +package org.codehaus.mojo.mrm.impl.maven; + +import java.io.File; + +import org.apache.maven.archetype.catalog.Archetype; +import org.apache.maven.archetype.catalog.ArchetypeCatalog; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DiskArtifactStoreTest { + + // MMOCKRM-10 + @Test + public void testArchetypeCatalog() throws Exception { + DiskArtifactStore artifactStore = new DiskArtifactStore(new File("src/test/resources/mmockrm-10")); + ArchetypeCatalog catalog = artifactStore.getArchetypeCatalog(); + assertNotNull(catalog); + assertEquals(1, catalog.getArchetypes().size()); + Archetype archetype = catalog.getArchetypes().get(0); + assertEquals("archetypes", archetype.getGroupId()); + assertEquals("fileset", archetype.getArtifactId()); + assertEquals("1.0", archetype.getVersion()); + assertEquals("Fileset test archetype", archetype.getDescription()); + assertEquals("file://${basedir}/target/test-classes/repositories/central", archetype.getRepository()); + } +} diff --git a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStoreTest.java b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStoreTest.java index b1e25fb8..aa83505b 100644 --- a/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStoreTest.java +++ b/mrm-servlet/src/test/java/org/codehaus/mojo/mrm/impl/maven/MockArtifactStoreTest.java @@ -1,197 +1,194 @@ -package org.codehaus.mojo.mrm.impl.maven; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.jar.Manifest; - -import org.apache.commons.io.IOUtils; -import org.apache.maven.archetype.catalog.Archetype; -import org.apache.maven.archetype.catalog.ArchetypeCatalog; -import org.codehaus.mojo.mrm.api.maven.Artifact; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class MockArtifactStoreTest -{ - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - // MMOCKRM-3 - @Test - public void testInheritGavFromParent() - { - // don't fail - MockArtifactStore mockArtifactStore = new MockArtifactStore( new File( "src/test/resources/mmockrm-3" ) ); - assertEquals( 2, mockArtifactStore.getArtifactIds( "localhost" ).size() ); - } - - // MMOCKRM-6 - @Test - public void testClassifiers() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "src/test/resources/mmockrm-7" ) ); - - Artifact pomArtifact = new Artifact( "localhost", "mmockrm-7", "1.0", "pom" ); - assertNotNull( artifactStore.get( pomArtifact ) ); - assertTrue( "Content equals", - IOUtils.contentEquals( new FileInputStream( "src/test/resources/mmockrm-7/mmockrm-7-1.0.pom" ), - artifactStore.get( pomArtifact ) ) ); - - Artifact siteArtifact = new Artifact( "localhost", "mmockrm-7", "1.0", "site", "xml" ); - assertNotNull( artifactStore.get( siteArtifact ) ); - assertTrue( "Content equals", - IOUtils.contentEquals( new FileInputStream( "src/test/resources/mmockrm-7/mmockrm-7-1.0-site.xml" ), - artifactStore.get( siteArtifact ) ) ); - } - - // MMOCKRM-10 - @Test - public void testArchetypeCatalog() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "src/test/resources/mmockrm-10" ) ); - ArchetypeCatalog catalog = artifactStore.getArchetypeCatalog(); - assertNotNull( catalog ); - assertEquals( 1, catalog.getArchetypes().size() ); - Archetype archetype = catalog.getArchetypes().get( 0 ); - assertEquals( "archetypes", archetype.getGroupId() ); - assertEquals( "fileset", archetype.getArtifactId() ); - assertEquals( "1.0", archetype.getVersion() ); - assertEquals( "Fileset test archetype", archetype.getDescription() ); - assertEquals( "file://${basedir}/target/test-classes/repositories/central", archetype.getRepository() ); - } - - @Test - public void testDirectoryContent() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "target/test-classes/mrm-15" ) ); - - Artifact pomArtifact = new Artifact( "localhost", "mrm-15", "1.0", "pom" ); - assertNotNull( artifactStore.get( pomArtifact ) ); - assertTrue( "Content equals", - IOUtils.contentEquals( new FileInputStream( "target/test-classes/mrm-15/mrm-15-1.0.pom" ), - artifactStore.get( pomArtifact ) ) ); - - Artifact mainArtifact = new Artifact( "localhost", "mrm-15", "1.0", "jar" ); - InputStream inputStreamJar = artifactStore.get( mainArtifact ); - assertNotNull( inputStreamJar ); - - List names = new ArrayList<>(); - - File jarFile = temporaryFolder.newFile(); - Files.copy( inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); - - try ( JarFile jar = new JarFile( jarFile ) ) - { - Enumeration entries = jar.entries(); - while ( entries.hasMoreElements() ) - { - JarEntry entry = entries.nextElement(); - names.add( entry.getName() ); - } - Manifest manifest = jar.getManifest(); - assertNotNull( manifest ); - assertEquals( 2, manifest.getMainAttributes().size() ); - } - - assertTrue( names.contains( "README.txt" ) ); - } - - @Test - public void testEmptyJarContent() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "target/test-classes/empty-jar" ) ); - - Artifact pomArtifact = new Artifact( "localhost", "mrm-empty-jar", "1.0", "pom" ); - InputStream inputStreamPom = artifactStore.get( pomArtifact ); - assertNotNull( inputStreamPom ); - assertTrue( "Content equals", - IOUtils.contentEquals( new FileInputStream( "target/test-classes/empty-jar/mrm-empty-jar-1.0.pom" ), - inputStreamPom ) ); - - Artifact mainArtifact = new Artifact( "localhost", "mrm-empty-jar", "1.0", "jar" ); - InputStream inputStreamJar = artifactStore.get( mainArtifact ); - assertNotNull( inputStreamJar ); - - File jarFile = temporaryFolder.newFile(); - Files.copy( inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); - - List names = new ArrayList<>(); - try ( JarFile jar = new JarFile( jarFile ) ) - { - Enumeration entries = jar.entries(); - while ( entries.hasMoreElements() ) - { - JarEntry entry = entries.nextElement(); - names.add( entry.getName() ); - } - Manifest manifest = jar.getManifest(); - assertNotNull( manifest ); - assertEquals( 3, manifest.getMainAttributes().size() ); - } - assertTrue( names.contains( "META-INF/MANIFEST.MF" ) ); - } - - @Test - public void testEmptyPluginJarContent() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "target/test-classes/empty-plugin-jar" ) ); - - Artifact pomArtifact = new Artifact( "localhost", "mrm-empty-plugin-jar", "1.0", "pom" ); - InputStream inputStreamPom = artifactStore.get( pomArtifact ); - assertNotNull( inputStreamPom ); - assertTrue( "Content equals", IOUtils.contentEquals( - new FileInputStream( "target/test-classes/empty-plugin-jar/mrm-empty-plugin-jar-1.0.pom" ), - inputStreamPom ) ); - - Artifact mainArtifact = new Artifact( "localhost", "mrm-empty-plugin-jar", "1.0", "jar" ); - InputStream inputStreamJar = artifactStore.get( mainArtifact ); - assertNotNull( inputStreamJar ); - - File jarFile = temporaryFolder.newFile(); - Files.copy( inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); - - List names = new ArrayList<>(); - try ( JarFile jar = new JarFile( jarFile ) ) - { - Enumeration entries = jar.entries(); - while ( entries.hasMoreElements() ) - { - JarEntry entry = entries.nextElement(); - names.add( entry.getName() ); - } - Manifest manifest = jar.getManifest(); - assertNotNull( manifest ); - assertEquals( 3, manifest.getMainAttributes().size() ); - } - assertTrue( names.contains( "META-INF/MANIFEST.MF" ) ); - assertTrue( names.contains( "META-INF/maven/plugin.xml" ) ); - } - - @Test - public void testDirectoryWithClassifierContent() throws Exception - { - MockArtifactStore artifactStore = new MockArtifactStore( new File( "target/test-classes/mrm-xx" ) ); - - Artifact pomArtifact = new Artifact( "localhost", "mrm-xx", "1.0", "pom" ); - assertNotNull( artifactStore.get( pomArtifact ) ); - assertTrue( "Content equals", - IOUtils.contentEquals( new FileInputStream( "target/test-classes/mrm-xx/mrm-xx-1.0.pom" ), - artifactStore.get( pomArtifact ) ) ); - - Artifact classifiedArtifact = new Artifact( "localhost", "mrm-xx", "1.0", "javadoc-resources", "jar" ); - assertNotNull( artifactStore.get( classifiedArtifact ) ); - } -} +package org.codehaus.mojo.mrm.impl.maven; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import org.apache.commons.io.IOUtils; +import org.apache.maven.archetype.catalog.Archetype; +import org.apache.maven.archetype.catalog.ArchetypeCatalog; +import org.codehaus.mojo.mrm.api.maven.Artifact; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class MockArtifactStoreTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + // MMOCKRM-3 + @Test + public void testInheritGavFromParent() { + // don't fail + MockArtifactStore mockArtifactStore = new MockArtifactStore(new File("src/test/resources/mmockrm-3")); + assertEquals(2, mockArtifactStore.getArtifactIds("localhost").size()); + } + + // MMOCKRM-6 + @Test + public void testClassifiers() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("src/test/resources/mmockrm-7")); + + Artifact pomArtifact = new Artifact("localhost", "mmockrm-7", "1.0", "pom"); + assertNotNull(artifactStore.get(pomArtifact)); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("src/test/resources/mmockrm-7/mmockrm-7-1.0.pom"), + artifactStore.get(pomArtifact))); + + Artifact siteArtifact = new Artifact("localhost", "mmockrm-7", "1.0", "site", "xml"); + assertNotNull(artifactStore.get(siteArtifact)); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("src/test/resources/mmockrm-7/mmockrm-7-1.0-site.xml"), + artifactStore.get(siteArtifact))); + } + + // MMOCKRM-10 + @Test + public void testArchetypeCatalog() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("src/test/resources/mmockrm-10")); + ArchetypeCatalog catalog = artifactStore.getArchetypeCatalog(); + assertNotNull(catalog); + assertEquals(1, catalog.getArchetypes().size()); + Archetype archetype = catalog.getArchetypes().get(0); + assertEquals("archetypes", archetype.getGroupId()); + assertEquals("fileset", archetype.getArtifactId()); + assertEquals("1.0", archetype.getVersion()); + assertEquals("Fileset test archetype", archetype.getDescription()); + assertEquals("file://${basedir}/target/test-classes/repositories/central", archetype.getRepository()); + } + + @Test + public void testDirectoryContent() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("target/test-classes/mrm-15")); + + Artifact pomArtifact = new Artifact("localhost", "mrm-15", "1.0", "pom"); + assertNotNull(artifactStore.get(pomArtifact)); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("target/test-classes/mrm-15/mrm-15-1.0.pom"), + artifactStore.get(pomArtifact))); + + Artifact mainArtifact = new Artifact("localhost", "mrm-15", "1.0", "jar"); + InputStream inputStreamJar = artifactStore.get(mainArtifact); + assertNotNull(inputStreamJar); + + List names = new ArrayList<>(); + + File jarFile = temporaryFolder.newFile(); + Files.copy(inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + try (JarFile jar = new JarFile(jarFile)) { + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + names.add(entry.getName()); + } + Manifest manifest = jar.getManifest(); + assertNotNull(manifest); + assertEquals(2, manifest.getMainAttributes().size()); + } + + assertTrue(names.contains("README.txt")); + } + + @Test + public void testEmptyJarContent() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("target/test-classes/empty-jar")); + + Artifact pomArtifact = new Artifact("localhost", "mrm-empty-jar", "1.0", "pom"); + InputStream inputStreamPom = artifactStore.get(pomArtifact); + assertNotNull(inputStreamPom); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("target/test-classes/empty-jar/mrm-empty-jar-1.0.pom"), inputStreamPom)); + + Artifact mainArtifact = new Artifact("localhost", "mrm-empty-jar", "1.0", "jar"); + InputStream inputStreamJar = artifactStore.get(mainArtifact); + assertNotNull(inputStreamJar); + + File jarFile = temporaryFolder.newFile(); + Files.copy(inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + List names = new ArrayList<>(); + try (JarFile jar = new JarFile(jarFile)) { + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + names.add(entry.getName()); + } + Manifest manifest = jar.getManifest(); + assertNotNull(manifest); + assertEquals(3, manifest.getMainAttributes().size()); + } + assertTrue(names.contains("META-INF/MANIFEST.MF")); + } + + @Test + public void testEmptyPluginJarContent() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("target/test-classes/empty-plugin-jar")); + + Artifact pomArtifact = new Artifact("localhost", "mrm-empty-plugin-jar", "1.0", "pom"); + InputStream inputStreamPom = artifactStore.get(pomArtifact); + assertNotNull(inputStreamPom); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("target/test-classes/empty-plugin-jar/mrm-empty-plugin-jar-1.0.pom"), + inputStreamPom)); + + Artifact mainArtifact = new Artifact("localhost", "mrm-empty-plugin-jar", "1.0", "jar"); + InputStream inputStreamJar = artifactStore.get(mainArtifact); + assertNotNull(inputStreamJar); + + File jarFile = temporaryFolder.newFile(); + Files.copy(inputStreamJar, jarFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + List names = new ArrayList<>(); + try (JarFile jar = new JarFile(jarFile)) { + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + names.add(entry.getName()); + } + Manifest manifest = jar.getManifest(); + assertNotNull(manifest); + assertEquals(3, manifest.getMainAttributes().size()); + } + assertTrue(names.contains("META-INF/MANIFEST.MF")); + assertTrue(names.contains("META-INF/maven/plugin.xml")); + } + + @Test + public void testDirectoryWithClassifierContent() throws Exception { + MockArtifactStore artifactStore = new MockArtifactStore(new File("target/test-classes/mrm-xx")); + + Artifact pomArtifact = new Artifact("localhost", "mrm-xx", "1.0", "pom"); + assertNotNull(artifactStore.get(pomArtifact)); + assertTrue( + "Content equals", + IOUtils.contentEquals( + new FileInputStream("target/test-classes/mrm-xx/mrm-xx-1.0.pom"), + artifactStore.get(pomArtifact))); + + Artifact classifiedArtifact = new Artifact("localhost", "mrm-xx", "1.0", "javadoc-resources", "jar"); + assertNotNull(artifactStore.get(classifiedArtifact)); + } +} diff --git a/pom.xml b/pom.xml index 07598c34..10770712 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,10 +29,8 @@ pom Mock Repository Manager :: Project - - Mock Repository Manager for Maven. The Mock Repository Manager provides a mock Maven - repository manager. - + Mock Repository Manager for Maven. The Mock Repository Manager provides a mock Maven + repository manager. https://www.mojohaus.org/mrm 2009 @@ -58,10 +54,10 @@ rscholte Robert Scholte - Europe/Amsterdam Java Developer + Europe/Amsterdam @@ -74,8 +70,8 @@ scm:git:https://github.com/mojohaus/mrm.git scm:git:ssh://git@github.com/mojohaus/mrm.git - https://github.com/mojohaus/mrm/tree/master HEAD + https://github.com/mojohaus/mrm/tree/master GitHub @@ -231,11 +227,11 @@ default-site - site site stage + site