From fd42e69cff4239c99f4f6b4b4d1421fe075bdbd8 Mon Sep 17 00:00:00 2001 From: Karel Piwko Date: Mon, 5 Sep 2011 18:33:18 +0200 Subject: [PATCH] SHRINKWRAP-324 Updated Formatting Rules to JBoss Community --- api-maven/pom.xml | 113 +- .../resolver/api/maven/MavenDependency.java | 172 +- .../api/maven/MavenDependencyResolver.java | 277 ++- .../api/maven/MavenResolutionFilter.java | 17 +- .../resolver/api/maven/SecurityActions.java | 319 ++- .../api/maven/filter/AcceptAllFilter.java | 51 +- .../api/maven/filter/CombinedFilter.java | 85 +- .../api/maven/filter/ScopeFilter.java | 91 +- .../api/maven/filter/StrictFilter.java | 59 +- api/pom.xml | 74 +- .../resolver/api/DependencyBuilder.java | 53 +- .../api/DependencyBuilderInstantiator.java | 309 ++- .../api/DependencyResolutionFilter.java | 32 +- .../resolver/api/DependencyResolver.java | 96 +- .../resolver/api/DependencyResolvers.java | 30 +- .../resolver/api/ResolutionElement.java | 24 +- .../resolver/api/ResolutionException.java | 54 +- .../resolver/api/SecurityActions.java | 150 +- build-resources/pom.xml | 26 + .../main/resources/code-style/checkstyle.xml | 53 + .../code-style/eclipse-cleanup-rules.xml | 56 + .../code-style/eclipse-formatting-rules.xml | 269 +++ .../code-style/eclipse-java-templates.xml | 21 + impl-maven/pom.xml | 483 ++--- .../resolver/impl/maven/ArtifactAsKey.java | 191 +- .../impl/maven/LogRepositoryListener.java | 360 ++-- .../impl/maven/LogTransferListerer.java | 293 ++- .../resolver/impl/maven/MavenBuilderImpl.java | 1702 ++++++++--------- .../resolver/impl/maven/MavenConverter.java | 652 +++---- .../impl/maven/MavenDependencyImpl.java | 158 +- .../MavenDependencyResolverInternal.java | 12 +- .../MavenDependencyResolverSettings.java | 326 ++-- .../impl/maven/MavenManagerBuilder.java | 207 +- .../impl/maven/MavenModelResolver.java | 206 +- .../impl/maven/MavenRepositorySystem.java | 382 ++-- .../impl/maven/MavenSettingsBuilder.java | 238 ++- .../resolver/impl/maven/SecurityActions.java | 242 +-- .../resolver/impl/maven/util/IOUtil.java | 285 ++- .../resolver/impl/maven/util/Validate.java | 148 +- .../ArtifactDependenciesUnitTestCase.java | 149 +- .../impl/maven/DependenciesUnitTestCase.java | 286 ++- .../impl/maven/DependencyTreeDescription.java | 688 +++---- .../DisabledCentralRepositoryTestCase.java | 38 +- .../impl/maven/ExclusionsUnitTestCase.java | 280 ++- .../MavenResolutionFilterUnitTestCase.java | 856 ++++----- .../resolver/impl/maven/MirrorTestCase.java | 33 +- .../resolver/impl/maven/MiscUnitTestCase.java | 58 +- .../impl/maven/OfflineRepositoryTestCase.java | 386 ++-- .../maven/PomDependenciesUnitTestCase.java | 553 +++--- .../impl/maven/ProfilesUnitTestCase.java | 94 +- .../shrinkwrap/resolver/util/FileUtil.java | 63 +- .../resolver/util/JarGenerator.java | 74 +- .../resolver/util/WarGenerator.java | 48 +- pom.xml | 534 +++--- 54 files changed, 6079 insertions(+), 6377 deletions(-) create mode 100644 build-resources/pom.xml create mode 100644 build-resources/src/main/resources/code-style/checkstyle.xml create mode 100644 build-resources/src/main/resources/code-style/eclipse-cleanup-rules.xml create mode 100644 build-resources/src/main/resources/code-style/eclipse-formatting-rules.xml create mode 100644 build-resources/src/main/resources/code-style/eclipse-java-templates.xml diff --git a/api-maven/pom.xml b/api-maven/pom.xml index 63aecc8a..569a10b5 100644 --- a/api-maven/pom.xml +++ b/api-maven/pom.xml @@ -1,57 +1,64 @@ - - - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-parent - 1.1.0-alpha-1-SNAPSHOT - ../pom.xml - - - - 4.0.0 - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api-maven - ShrinkWrap Resolver Maven API - ShrinkWrap Extension for Resolving Dependencies from a Maven backend - - - - - - - - - - - - - - - org.jboss.shrinkwrap - shrinkwrap-api - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api - ${project.version} - - - - - junit - junit - test - - - + + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-parent + 1.1.0-alpha-1-SNAPSHOT + ../pom.xml + + + + 4.0.0 + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api-maven + ShrinkWrap Resolver Maven API + ShrinkWrap Extension for Resolving Dependencies from a Maven backend + + + + + + + + + + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api + ${project.version} + + + + + junit + junit + test + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenDependency.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenDependency.java index da4a89df..04640ceb 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenDependency.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenDependency.java @@ -1,95 +1,115 @@ -/** - * +/* + * JBoss, Home of Professional Open Source + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.jboss.shrinkwrap.resolver.api.maven; import org.jboss.shrinkwrap.resolver.api.ResolutionElement; /** - * Describes Maven Resolution Element. - * - * Contract encapsulates Maven dependency as known from POM files. - * + * Describes Maven Resolution Element. + * + * Contract encapsulates Maven dependency as known from POM files. + * * @author Karel Piwko * @author Andrew Lee Rubinger - * @author Jose Rodolfo freitas + * @author Jose Rodolfo Freitas */ -public interface MavenDependencyResolver - extends - DependencyBuilder, - DependencyResolver -{ - /** - * Configures Maven from a settings.xml file - * - * @param path - * A path to a settings.xml configuration file - * @return A dependency builder with a configuration from given file - */ - MavenDependencyResolver configureFrom(String path); +public interface MavenDependencyResolver extends DependencyBuilder, + DependencyResolver { + /** + * Configures Maven from a settings.xml file + * + * @param path A path to a settings.xml configuration file + * @return A dependency builder with a configuration from given file + */ + MavenDependencyResolver configureFrom(String path); + + /** + * Loads remote repositories for a POM file. If repositories are defined in the parent of the POM file and there are + * accessible via local file system, they are set as well. + * + * These remote repositories are used to resolve the artifacts during dependency resolution. + * + * Additionally, it loads dependencies defined in the POM file model in an internal cache, which can be later used to + * resolve an artifact without explicitly specifying its version. + * + * @param pathx A path to the POM file, must not be {@code null} or empty + * @return A dependency builder with remote repositories set according to the content of POM file. + * @throws Exception + */ + MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException; - /** - * Loads remote repositories for a POM file. If repositories are defined in - * the parent of the POM file and there are accessible via local file - * system, they are set as well. - * - * These remote repositories are used to resolve the artifacts during - * dependency resolution. - * - * Additionally, it loads dependencies defined in the POM file model in an - * internal cache, which can be later used to resolve an artifact without - * explicitly specifying its version. - * - * @param pathx - * A path to the POM file, must not be {@code null} or empty - * @return A dependency builder with remote repositories set according to - * the content of POM file. - * @throws Exception - */ - MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException; + /** + * Loads remote repositories for a POM file. If repositories are defined in the parent of the POM file and there are + * accessible via local file system, they are set as well. + * + * These remote repositories are used to resolve the artifacts during dependency resolution. + * + * Additionally, it loads dependencies defined in the POM file model in an internal cache, which can be later used to + * resolve an artifact without explicitly specifying its version. + * + * @param path A path to the POM file, must not be {@code null} or empty + * @return A dependency builder with remote repositories set according to the content of POM file. + * @throws Exception + * @deprecated please use {@link #loadMetadataFromPom(String)} instead + */ + @Deprecated + MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException; - /** - * Loads remote repositories for a POM file. If repositories are defined in - * the parent of the POM file and there are accessible via local file - * system, they are set as well. - * - * These remote repositories are used to resolve the artifacts during - * dependency resolution. - * - * Additionally, it loads dependencies defined in the POM file model in an - * internal cache, which can be later used to resolve an artifact without - * explicitly specifying its version. - * - * @param path - * A path to the POM file, must not be {@code null} or empty - * @return A dependency builder with remote repositories set according to - * the content of POM file. - * @throws Exception - * @deprecated please use {@link #loadMetadataFromPom(String)} instead - */ - @Deprecated - MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException; + /** + * Sets a scope of dependency + * + * @param scope A scope, for example @{code compile}, @{code test} and others + * @return Artifact builder with scope set + */ + MavenDependencyResolver scope(String scope); - /** - * Sets a scope of dependency - * - * @param scope A scope, for example @{code compile}, @{code test} and others - * @return Artifact builder with scope set - */ - MavenDependencyResolver scope(String scope); + /** + * Sets dependency as optional. If dependency is marked as optional, it is always resolved, however, the dependency graph + * can later be filtered based on {@code optional} flag + * + * @param optional Optional flag + * @return Artifact builder with optional flag set + */ + MavenDependencyResolver optional(boolean optional); - /** - * Sets dependency as optional. If dependency is marked as optional, it is - * always resolved, however, the dependency graph can later be filtered based - * on {@code optional} flag - * - * @param optional Optional flag - * @return Artifact builder with optional flag set - */ - MavenDependencyResolver optional(boolean optional); + /** + * Adds an exclusion for current dependency. + * + * @param exclusion the exclusion to be added to list of artifacts to be excluded, specified in the format + * {@code :[:[:]]}, an empty string or {@code *} will match all + * exclusions, you can pass an {@code *} instead of any part of the coordinates to match all possible values + * @return Artifact builder with added exclusion + */ + MavenDependencyResolver exclusion(String exclusion); - /** - * Adds an exclusion for current dependency. - * - * @param exclusion the exclusion to be added to list of artifacts to be - * excluded, specified in the format - * {@code :[:[:]]}, an - * empty string or {@code *} will match all exclusions, you can - * pass an {@code *} instead of any part of the coordinates to - * match all possible values - * @return Artifact builder with added exclusion - */ - MavenDependencyResolver exclusion(String exclusion); + /** + * Adds multiple exclusions for current dependency + * + * @param exclusions the exclusions to be added to the list of artifacts to be excluded, specified in the format + * {@code :[:[:]]}, an empty string or {@code *} will match all + * exclusions, you can pass an {@code *} instead of any part of the coordinates to match all possible values + * @return Artifact builder with added exclusions + */ + MavenDependencyResolver exclusions(String... exclusions); - /** - * Adds multiple exclusions for current dependency - * - * @param exclusions the exclusions to be added to the list of artifacts to - * be excluded, specified in the format - * {@code :[:[:]]}, an - * empty string or {@code *} will match all exclusions, you can - * pass an {@code *} instead of any part of the coordinates to - * match all possible values - * @return Artifact builder with added exclusions - */ - MavenDependencyResolver exclusions(String... exclusions); + /** + * Adds multiple exclusions for current dependency + * + * @param exclusions the exclusions to be added to the list of artifacts to be excluded, specified in the format + * {@code :[:[:]]}, an empty string or {@code *} will match all + * exclusions, you can pass an {@code *} instead of any part of the coordinates to match all possible values + * @return Artifact builder with added exclusions + */ + MavenDependencyResolver exclusions(Collection exclusions); - /** - * Adds multiple exclusions for current dependency - * - * @param exclusions the exclusions to be added to the list of artifacts to - * be excluded, specified in the format - * {@code :[:[:]]}, an - * empty string or {@code *} will match all exclusions, you can - * pass an {@code *} instead of any part of the coordinates to - * match all possible values - * @return Artifact builder with added exclusions - */ - MavenDependencyResolver exclusions(Collection exclusions); + /** + * Resolves based upon dependencies declared in the POM at the specified path + * + * @param path + * @return + * @throws ResolutionException + */ + MavenDependencyResolver includeDependenciesFromPom(final String path) throws ResolutionException; - /** - * Resolves based upon dependencies declared in the POM at the specified path - * - * @param path - * @return - * @throws ResolutionException - */ - MavenDependencyResolver includeDependenciesFromPom(final String path) throws ResolutionException; - - /** - * Resolves based upon dependencies declared in the POM at the specified path - * - * @param path - * @return - * @throws ResolutionException - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - @Deprecated - MavenDependencyResolver loadDependenciesFromPom(final String path) throws ResolutionException; + /** + * Resolves based upon dependencies declared in the POM at the specified path + * + * @param path + * @return + * @throws ResolutionException + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + @Deprecated + MavenDependencyResolver loadDependenciesFromPom(final String path) throws ResolutionException; - /** - * Resolves based upon dependencies declared in the POM at the specified path - * - * @param path - * @param filter - * @return - * @throws ResolutionException - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - @Deprecated - MavenDependencyResolver loadDependenciesFromPom(final String path, final MavenResolutionFilter filter) throws ResolutionException; + /** + * Resolves based upon dependencies declared in the POM at the specified path + * + * @param path + * @param filter + * @return + * @throws ResolutionException + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + @Deprecated + MavenDependencyResolver loadDependenciesFromPom(final String path, final MavenResolutionFilter filter) + throws ResolutionException; - /** - * Sets the resolver to either consider (or not) Maven Central in resolution - * @param useCentral a flag whether to use Maven central - * @return - */ - MavenDependencyResolver useCentralRepo(final boolean useCentral); + /** + * Sets the resolver to either consider (or not) Maven Central in resolution + * + * @param useCentral a flag whether to use Maven central + * @return + */ + MavenDependencyResolver useCentralRepo(final boolean useCentral); - /** - * Disables touching remote repositories at all, rely on local repository only - * @return Modified MavenDependencyResolution - */ - MavenDependencyResolver goOffline(); + /** + * Disables touching remote repositories at all, rely on local repository only + * + * @return Modified MavenDependencyResolution + */ + MavenDependencyResolver goOffline(); } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenResolutionFilter.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenResolutionFilter.java index 50cf5e25..28d7c4f7 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenResolutionFilter.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/MavenResolutionFilter.java @@ -21,22 +21,19 @@ import org.jboss.shrinkwrap.resolver.api.DependencyResolutionFilter; /** - * A filter which can filter results retrieved by a particular dependency - * builder. + * A filter which can filter results retrieved by a particular dependency builder. * - * The filter affects directly the dependency chain. Specifying it can save - * bandwidth and number of resolved dependencies, thus making your tests run - * faster. + * The filter affects directly the dependency chain. Specifying it can save bandwidth and number of resolved dependencies, thus + * making your tests run faster. * * @see org.sonatype.aether.graph.DependencyFilter * @see MavenDependencyResolver * @author Karel Piwko * */ -public interface MavenResolutionFilter extends DependencyResolutionFilter -{ - @Override - boolean accept(MavenDependency element); +public interface MavenResolutionFilter extends DependencyResolutionFilter { + @Override + boolean accept(MavenDependency element); - MavenResolutionFilter configure(Collection dependencies); + MavenResolutionFilter configure(Collection dependencies); } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/SecurityActions.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/SecurityActions.java index b25a0414..a432d401 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/SecurityActions.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/SecurityActions.java @@ -24,203 +24,166 @@ /** * SecurityActions - * + * * A set of privileged actions that are not to leak out of this package - * - * + * + * * @author ALR * @author Karel Piwko - * + * * @version $Revision: $ */ -final class SecurityActions -{ +final class SecurityActions { - // -------------------------------------------------------------------------------|| - // Constructor -------------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Constructor -------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * No instantiation - */ - private SecurityActions() - { - throw new UnsupportedOperationException("No instantiation"); - } + /** + * No instantiation + */ + private SecurityActions() { + throw new UnsupportedOperationException("No instantiation"); + } - // -------------------------------------------------------------------------------|| - // Utility Methods ---------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Utility Methods ---------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * Obtains the Thread Context ClassLoader - */ - static ClassLoader getThreadContextClassLoader() - { - return AccessController.doPrivileged(GetTcclAction.INSTANCE); - } + /** + * Obtains the Thread Context ClassLoader + */ + static ClassLoader getThreadContextClassLoader() { + return AccessController.doPrivileged(GetTcclAction.INSTANCE); + } - /** - * Obtains the Constructor specified from the given Class and argument types - * - * @param clazz - * @param argumentTypes - * @return - * @throws NoSuchMethodException - */ - static Constructor getConstructor(final Class clazz, final Class... argumentTypes) throws NoSuchMethodException - { - try - { - return AccessController.doPrivileged(new PrivilegedExceptionAction>() - { - public Constructor run() throws NoSuchMethodException - { - return clazz.getConstructor(argumentTypes); + /** + * Obtains the Constructor specified from the given Class and argument types + * + * @param clazz + * @param argumentTypes + * @return + * @throws NoSuchMethodException + */ + static Constructor getConstructor(final Class clazz, final Class... argumentTypes) throws NoSuchMethodException { + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction>() { + public Constructor run() throws NoSuchMethodException { + return clazz.getConstructor(argumentTypes); + } + }); + } + // Unwrap + catch (final PrivilegedActionException pae) { + final Throwable t = pae.getCause(); + // Rethrow + if (t instanceof NoSuchMethodException) { + throw (NoSuchMethodException) t; + } else { + // No other checked Exception thrown by Class.getConstructor + try { + throw (RuntimeException) t; + } + // Just in case we've really messed up + catch (final ClassCastException cce) { + throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + } } - }); - } - // Unwrap - catch (final PrivilegedActionException pae) - { - final Throwable t = pae.getCause(); - // Rethrow - if (t instanceof NoSuchMethodException) - { - throw (NoSuchMethodException) t; - } - else - { - // No other checked Exception thrown by Class.getConstructor - try - { - throw (RuntimeException) t; - } - // Just in case we've really messed up - catch (final ClassCastException cce) - { - throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); - } - } - } - } + } + } - /** - * Create a new instance by finding a constructor that matches the - * argumentTypes signature using the arguments for instantiation. - * - * @param className Full classname of class to create - * @param argumentTypes The constructor argument types - * @param arguments The constructor arguments - * @return a new instance - * @throws IllegalArgumentException if className, argumentTypes, or arguments - * are null - * @throws RuntimeException if any exceptions during creation - * @author Aslak Knutsen - * @author ALR - */ - static T newInstance(final String className, final Class[] argumentTypes, final Object[] arguments, final Class expectedType) - { - if (className == null) - { - throw new IllegalArgumentException("ClassName must be specified"); - } - if (argumentTypes == null) - { - throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments"); - } - if (arguments == null) - { - throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments"); - } - final Object obj; - try - { - final ClassLoader tccl = getThreadContextClassLoader(); - final Class implClass = Class.forName(className, false, tccl); - Constructor constructor = getConstructor(implClass, argumentTypes); - obj = constructor.newInstance(arguments); - } - catch (Exception e) - { - throw new RuntimeException("Could not create new instance of " + className + ", missing package from classpath?", e); - } + /** + * Create a new instance by finding a constructor that matches the argumentTypes signature using the arguments for + * instantiation. + * + * @param className Full classname of class to create + * @param argumentTypes The constructor argument types + * @param arguments The constructor arguments + * @return a new instance + * @throws IllegalArgumentException if className, argumentTypes, or arguments are null + * @throws RuntimeException if any exceptions during creation + * @author Aslak Knutsen + * @author ALR + */ + static T newInstance(final String className, final Class[] argumentTypes, final Object[] arguments, + final Class expectedType) { + if (className == null) { + throw new IllegalArgumentException("ClassName must be specified"); + } + if (argumentTypes == null) { + throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments"); + } + if (arguments == null) { + throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments"); + } + final Object obj; + try { + final ClassLoader tccl = getThreadContextClassLoader(); + final Class implClass = Class.forName(className, false, tccl); + Constructor constructor = getConstructor(implClass, argumentTypes); + obj = constructor.newInstance(arguments); + } catch (Exception e) { + throw new RuntimeException("Could not create new instance of " + className + ", missing package from classpath?", e); + } - // Cast - try - { - return expectedType.cast(obj); - } - catch (final ClassCastException cce) - { - // Reconstruct so we get some useful information - throw new ClassCastException("Incorrect expected type, " + expectedType.getName() + ", defined for " + obj.getClass().getName()); - } - } + // Cast + try { + return expectedType.cast(obj); + } catch (final ClassCastException cce) { + // Reconstruct so we get some useful information + throw new ClassCastException("Incorrect expected type, " + expectedType.getName() + ", defined for " + + obj.getClass().getName()); + } + } - static String getProperty(final String key) - { - try - { - String value = AccessController.doPrivileged(new PrivilegedExceptionAction() - { - public String run() - { - return System.getProperty(key); - } - }); - return value; - } - // Unwrap - catch (final PrivilegedActionException pae) - { - final Throwable t = pae.getCause(); - // Rethrow - if (t instanceof SecurityException) - { - throw (SecurityException) t; - } - if (t instanceof NullPointerException) - { - throw (NullPointerException) t; - } - else if (t instanceof IllegalArgumentException) - { - throw (IllegalArgumentException) t; - } - else - { - // No other checked Exception thrown by System.getProperty - try - { - throw (RuntimeException) t; + static String getProperty(final String key) { + try { + String value = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public String run() { + return System.getProperty(key); + } + }); + return value; + } + // Unwrap + catch (final PrivilegedActionException pae) { + final Throwable t = pae.getCause(); + // Rethrow + if (t instanceof SecurityException) { + throw (SecurityException) t; } - // Just in case we've really messed up - catch (final ClassCastException cce) - { - throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + if (t instanceof NullPointerException) { + throw (NullPointerException) t; + } else if (t instanceof IllegalArgumentException) { + throw (IllegalArgumentException) t; + } else { + // No other checked Exception thrown by System.getProperty + try { + throw (RuntimeException) t; + } + // Just in case we've really messed up + catch (final ClassCastException cce) { + throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + } } - } - } - } + } + } - // -------------------------------------------------------------------------------|| - // Inner Classes - // ----------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Inner Classes + // ----------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * Single instance to get the TCCL - */ - private enum GetTcclAction implements PrivilegedAction - { - INSTANCE; + /** + * Single instance to get the TCCL + */ + private enum GetTcclAction implements PrivilegedAction { + INSTANCE; - public ClassLoader run() - { - return Thread.currentThread().getContextClassLoader(); - } + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } - } + } } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/AcceptAllFilter.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/AcceptAllFilter.java index 77a9bd2a..673913d4 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/AcceptAllFilter.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/AcceptAllFilter.java @@ -22,37 +22,30 @@ import org.jboss.shrinkwrap.resolver.api.maven.MavenResolutionFilter; /** - * A filter which accept all dependencies. This is the default behavior is no - * other filter is specified. - * + * A filter which accept all dependencies. This is the default behavior is no other filter is specified. + * * @author Karel Piwko * @author Andrew Lee Rubinger */ -public enum AcceptAllFilter implements MavenResolutionFilter -{ - INSTANCE; - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java - * .util.Collection) - */ - public MavenResolutionFilter configure(Collection dependencies) - { - return this; - } +public enum AcceptAllFilter implements MavenResolutionFilter { + INSTANCE; + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java .util.Collection) + */ + public MavenResolutionFilter configure(Collection dependencies) { + return this; + } - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#accept(org.jboss - * .shrinkwrap.resolver.maven.MavenResolutionElement) - */ - public boolean accept(MavenDependency element) - { - return true; - } + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#accept(org.jboss + * .shrinkwrap.resolver.maven.MavenResolutionElement) + */ + public boolean accept(MavenDependency element) { + return true; + } } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/CombinedFilter.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/CombinedFilter.java index 2dba8fd6..8e9dd583 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/CombinedFilter.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/CombinedFilter.java @@ -26,59 +26,48 @@ /** * A combinator for multiple filters. - * + * * @author Karel Piwko - * + * */ -public class CombinedFilter implements MavenResolutionFilter -{ - private List filters; - - /** - * Combines multiple filters in a such way that all must pass. - * - * Implementation note: The varargs arguments cannot have a type bound, - * because this leads to an unchecked cast while invoked - * - * @param filters The filters to be combined - * @throws DependencyException If any of the filter cannot be used to filter - * MavenDependencies - * @see MavenBuilderImpl - */ - public CombinedFilter(MavenResolutionFilter... filters) +public class CombinedFilter implements MavenResolutionFilter { + private List filters; - { - this.filters = new ArrayList(filters.length); - this.filters.addAll(Arrays.asList(filters)); - } + /** + * Combines multiple filters in a such way that all must pass. + * + * Implementation note: The varargs arguments cannot have a type bound, because this leads to an unchecked cast while + * invoked + * + * @param filters The filters to be combined + * @throws DependencyException If any of the filter cannot be used to filter MavenDependencies + * @see MavenBuilderImpl + */ + public CombinedFilter(MavenResolutionFilter... filters) { + this.filters = new ArrayList(filters.length); + this.filters.addAll(Arrays.asList(filters)); + } - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java - * .util.Collection) - */ - public MavenResolutionFilter configure(Collection dependencies) - { - for (MavenResolutionFilter f : filters) - { - f.configure(dependencies); - } - return this; - } + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java .util.Collection) + */ + public MavenResolutionFilter configure(Collection dependencies) { + for (MavenResolutionFilter f : filters) { + f.configure(dependencies); + } + return this; + } - public boolean accept(MavenDependency element) - { - for (MavenResolutionFilter f : filters) - { - if (f.accept(element) == false) - { - return false; - } - } + public boolean accept(MavenDependency element) { + for (MavenResolutionFilter f : filters) { + if (f.accept(element) == false) { + return false; + } + } - return true; - } + return true; + } } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/ScopeFilter.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/ScopeFilter.java index dac0faa4..f864468e 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/ScopeFilter.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/ScopeFilter.java @@ -25,64 +25,51 @@ import org.jboss.shrinkwrap.resolver.api.maven.MavenResolutionFilter; /** - * A filter which limits scope of the artifacts. Only the artifacts within - * specified scopes are included in resolution. - * + * A filter which limits scope of the artifacts. Only the artifacts within specified scopes are included in resolution. + * * @author Karel Piwko - * + * */ -public class ScopeFilter implements MavenResolutionFilter -{ - private Set allowedScopes; +public class ScopeFilter implements MavenResolutionFilter { + private Set allowedScopes; - /** - * Creates a filter which accepts all artifacts with no scope defined, that - * is their scope is an empty string. - */ - public ScopeFilter() - { - this(""); - } + /** + * Creates a filter which accepts all artifacts with no scope defined, that is their scope is an empty string. + */ + public ScopeFilter() { + this(""); + } - /** - * Creates a filter which accepts all artifacts that their scope is one of - * the specified. - * - * @param scopes The enumeration of allowed scopes - */ - public ScopeFilter(String... scopes) - { - this.allowedScopes = new HashSet(); - if (scopes.length != 0) - { - allowedScopes.addAll(Arrays.asList(scopes)); - } - } + /** + * Creates a filter which accepts all artifacts that their scope is one of the specified. + * + * @param scopes The enumeration of allowed scopes + */ + public ScopeFilter(String... scopes) { + this.allowedScopes = new HashSet(); + if (scopes.length != 0) { + allowedScopes.addAll(Arrays.asList(scopes)); + } + } - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java - * .util.Collection) - */ - public MavenResolutionFilter configure(Collection dependencies) - { - return this; - } + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java .util.Collection) + */ + public MavenResolutionFilter configure(Collection dependencies) { + return this; + } - public boolean accept(MavenDependency dependency) - { - if (dependency == null) - { - return false; - } + public boolean accept(MavenDependency dependency) { + if (dependency == null) { + return false; + } - if (allowedScopes.contains(dependency.getScope())) - { - return true; - } + if (allowedScopes.contains(dependency.getScope())) { + return true; + } - return false; - } + return false; + } } diff --git a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/StrictFilter.java b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/StrictFilter.java index 2ca89ea8..c4fdb200 100644 --- a/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/StrictFilter.java +++ b/api-maven/src/main/java/org/jboss/shrinkwrap/resolver/api/maven/filter/StrictFilter.java @@ -22,41 +22,32 @@ import org.jboss.shrinkwrap.resolver.api.maven.MavenResolutionFilter; /** - * A filter which accepts only dependencies which are directly specified in the - * builder All transitive dependencies are omitted. - * + * A filter which accepts only dependencies which are directly specified in the builder All transitive dependencies are omitted. + * * @author Karel Piwko - * + * */ -public class StrictFilter implements MavenResolutionFilter -{ - private Collection allowedDependencies; - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java - * .util.Collection) - */ - public MavenResolutionFilter configure(Collection dependencies) - { - this.allowedDependencies = dependencies; - return this; - } - - public boolean accept(MavenDependency element) - { - - for (MavenDependency allowed : allowedDependencies) - { - if (allowed.getScope().equals(element.getScope()) && element.hasSameArtifactAs(allowed)) - { - return true; - } - } - return false; - } - +public class StrictFilter implements MavenResolutionFilter { + private Collection allowedDependencies; + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.maven.MavenResolutionFilter#configure(java .util.Collection) + */ + public MavenResolutionFilter configure(Collection dependencies) { + this.allowedDependencies = dependencies; + return this; + } + + public boolean accept(MavenDependency element) { + + for (MavenDependency allowed : allowedDependencies) { + if (allowed.getScope().equals(element.getScope()) && element.hasSameArtifactAs(allowed)) { + return true; + } + } + return false; + } } diff --git a/api/pom.xml b/api/pom.xml index e969c501..6e278635 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -1,36 +1,46 @@ - - - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-parent - 1.1.0-alpha-1-SNAPSHOT - ../pom.xml - - - - 4.0.0 - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api - ShrinkWrap Resolver API - ShrinkWrap Extension for Resolving Dependencies - - - - - - - - org.jboss.shrinkwrap - shrinkwrap-api - - - + + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-parent + 1.1.0-alpha-1-SNAPSHOT + ../pom.xml + + + + 4.0.0 + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api + ShrinkWrap Resolver API + ShrinkWrap Extension for Resolving Dependencies + + + + + + + + org.jboss.shrinkwrap + shrinkwrap-api + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilder.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilder.java index d54b0374..db20108b 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilder.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilder.java @@ -17,38 +17,31 @@ package org.jboss.shrinkwrap.resolver.api; /** - * Encapsulates access to a backing store or repository; Accepts - * coordinates intended to resolve to a set of dependencies. - * + * Encapsulates access to a backing store or repository; Accepts coordinates intended to resolve to a set of dependencies. + * * @author Karel Piwko * @author Andrew Lee Rubinger */ -public interface DependencyBuilder> -{ - /** - * Creates an artifact builder. You can define additional parameters for the - * artifact later. Additional parameters will be changed for all artifacts - * defined by this call. - * - * @param coordinates Coordinates specified to a created artifact, specified - * in an implementation-specific format. - * - * @return This {@link DependencyBuilder} - * @throws ResolutionException If artifact coordinates are wrong or if - * version cannot be determined. - */ - T artifact(String coordinates) throws ResolutionException; +public interface DependencyBuilder> { + /** + * Creates an artifact builder. You can define additional parameters for the artifact later. Additional parameters will be + * changed for all artifacts defined by this call. + * + * @param coordinates Coordinates specified to a created artifact, specified in an implementation-specific format. + * + * @return This {@link DependencyBuilder} + * @throws ResolutionException If artifact coordinates are wrong or if version cannot be determined. + */ + T artifact(String coordinates) throws ResolutionException; - /** - * Creates an artifact builder. You can define additional parameters for the - * artifacts later. Additional parameters will be changed for all artifacts - * defined by this call. - * - * @param coordinates A list of coordinates specified to the created - * artifacts, specified in an implementation-specific format. - * @return This {@link DependencyBuilder} - * @throws ResolutionException If artifact coordinates are wrong or if - * version cannot be determined. - */ - T artifacts(String... coordinates) throws ResolutionException; + /** + * Creates an artifact builder. You can define additional parameters for the artifacts later. Additional parameters will be + * changed for all artifacts defined by this call. + * + * @param coordinates A list of coordinates specified to the created artifacts, specified in an implementation-specific + * format. + * @return This {@link DependencyBuilder} + * @throws ResolutionException If artifact coordinates are wrong or if version cannot be determined. + */ + T artifacts(String... coordinates) throws ResolutionException; } diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilderInstantiator.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilderInstantiator.java index 2f0982fb..9e8620f3 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilderInstantiator.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyBuilderInstantiator.java @@ -22,173 +22,150 @@ import java.util.Properties; /** - * Utility capable of creating {@link DependencyBuilder} instances given - * a requested end-user view. - * + * Utility capable of creating {@link DependencyBuilder} instances given a requested end-user view. + * * @author ALR */ -final class DependencyBuilderInstantiator -{ - //-------------------------------------------------------------------------------------|| - // Class Members ----------------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Classpath location under which mapping configuration between - * ens-user view and implementation types is located - */ - private static final String MAPPING_LOCATION = "META-INF/services/"; - - /** - * Key of the property denoting the implementation class for a given end-user view type - */ - private static final String KEY_IMPL_CLASS_NAME = "implClass"; - - //-------------------------------------------------------------------------------------|| - // Constructor ------------------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Internal constructor; not to be called - */ - private DependencyBuilderInstantiator() - { - throw new UnsupportedOperationException("No instances permitted"); - } - - //-------------------------------------------------------------------------------------|| - // Functional Methods -----------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Creates a new {@link DependencyBuilder} instance of the specified user view type. - * Will consult a configuration file visible to the {@link Thread} Context {@link ClassLoader} - * named "META-INF/services/$fullyQualfiedClassName" which should contain a key=value - * format with the key {@link DependencyBuilderInstantiator#KEY_IMPL_CLASS_NAME}. - * The implementation class name must have a no-arg constructor. - * - * @param - * @param userViewClass - * @return - * @throws IllegalArgumentException If the user view class was not specified - */ - static > T createFromUserView(final Class userViewClass) - throws IllegalArgumentException - { - // Get the impl class for the specified user view - final Class implClass = getImplClassForUserView(userViewClass); - - // Get the constructor to use in making the new instance - final Constructor ctor; - try - { - ctor = SecurityActions.getConstructor(implClass, new Class[]{}); - } - catch (final NoSuchMethodException nsme) - { - throw new RuntimeException(implClass + " must contain a public no args contructor"); - } - - // Create a new instance using the backing model - final DependencyBuilder dependencyBuilder; - try - { - dependencyBuilder = ctor.newInstance(); - } - // Handle all construction errors equally - catch (final Exception e) - { - throw new RuntimeException("Could not create new descriptor instance", e); - } - - // Return - return userViewClass.cast(dependencyBuilder); - - } - - //-------------------------------------------------------------------------------------|| - // Internal Helper Members ------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Obtains the {@link DependencyBuilder} class for the giving end user view, using - * a configuration file loaded from the TCCL of name "META-INF/services.$fullyQualifiedClassName" - * having properties as described by {@link DependencyBuilderInstantiator#createFromUserView(Class)}. - * - * @param userViewClass - * @return The construction information needed to create new instances conforming to the user view - * @throws IllegalArgumentException If the user view was not specified - */ - private static > Class getImplClassForUserView(final Class userViewClass) - throws IllegalArgumentException - { - // Precondition checks - if (userViewClass == null) - { - throw new IllegalArgumentException("User view class must be specified"); - } - - // Get the configuration from which we'll create new instances - final String className = userViewClass.getName(); - final String resourceName = MAPPING_LOCATION + className; - final ClassLoader tccl = SecurityActions.getThreadContextClassLoader(); - final InputStream resourceStream = tccl.getResourceAsStream(resourceName); - if (resourceStream == null) - { - throw new IllegalArgumentException("No resource " + resourceName - + " was found configured for user view class " + userViewClass.getName()); - } - - // Load - final Properties props = new Properties(); - try - { - props.load(resourceStream); - } - catch (final IOException e) - { - throw new RuntimeException("I/O Problem in reading the properties for " + userViewClass.getName(), e); - } - final String implClassName = props.getProperty(KEY_IMPL_CLASS_NAME); - if (implClassName == null || implClassName.length() == 0) - { - throw new IllegalStateException("Resource " + resourceName + " for " + userViewClass - + " does not contain key " + KEY_IMPL_CLASS_NAME); - } - - // Load the Implementation class - final Class implClass; - try - { - implClass = getImplClassForName(tccl, implClassName); - } - catch (final ClassNotFoundException e) - { - // Rethrow with some context - throw new IllegalStateException("Could not load specified implementation class from " + tccl + ": " - + implClassName, e); - } - - // Return - return implClass; - } - - /** - * Uses the specified {@link ClassLoader} to create and return - * a {@link Class} instance for the specified class name. Externalized to suppress - * unchecked warnings. - * @param - * @param cl - * @param implClassName - * @return - */ - @SuppressWarnings("unchecked") - private static > Class getImplClassForName(final ClassLoader cl, - final String implClassName) throws ClassNotFoundException - { - assert cl != null : "CL is required"; - assert implClassName != null && implClassName.length() > 0 : "Impl Class name is required"; - return (Class) Class.forName(implClassName, false, cl); - } +final class DependencyBuilderInstantiator { + // -------------------------------------------------------------------------------------|| + // Class Members ----------------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Classpath location under which mapping configuration between ens-user view and implementation types is located + */ + private static final String MAPPING_LOCATION = "META-INF/services/"; + + /** + * Key of the property denoting the implementation class for a given end-user view type + */ + private static final String KEY_IMPL_CLASS_NAME = "implClass"; + + // -------------------------------------------------------------------------------------|| + // Constructor ------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Internal constructor; not to be called + */ + private DependencyBuilderInstantiator() { + throw new UnsupportedOperationException("No instances permitted"); + } + + // -------------------------------------------------------------------------------------|| + // Functional Methods -----------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Creates a new {@link DependencyBuilder} instance of the specified user view type. Will consult a configuration file + * visible to the {@link Thread} Context {@link ClassLoader} named "META-INF/services/$fullyQualfiedClassName" which should + * contain a key=value format with the key {@link DependencyBuilderInstantiator#KEY_IMPL_CLASS_NAME}. The implementation + * class name must have a no-arg constructor. + * + * @param + * @param userViewClass + * @return + * @throws IllegalArgumentException If the user view class was not specified + */ + static > T createFromUserView(final Class userViewClass) throws IllegalArgumentException { + // Get the impl class for the specified user view + final Class implClass = getImplClassForUserView(userViewClass); + + // Get the constructor to use in making the new instance + final Constructor ctor; + try { + ctor = SecurityActions.getConstructor(implClass, new Class[] {}); + } catch (final NoSuchMethodException nsme) { + throw new RuntimeException(implClass + " must contain a public no args contructor"); + } + + // Create a new instance using the backing model + final DependencyBuilder dependencyBuilder; + try { + dependencyBuilder = ctor.newInstance(); + } + // Handle all construction errors equally + catch (final Exception e) { + throw new RuntimeException("Could not create new descriptor instance", e); + } + + // Return + return userViewClass.cast(dependencyBuilder); + + } + + // -------------------------------------------------------------------------------------|| + // Internal Helper Members ------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Obtains the {@link DependencyBuilder} class for the giving end user view, using a configuration file loaded from the TCCL + * of name "META-INF/services.$fullyQualifiedClassName" having properties as described by + * {@link DependencyBuilderInstantiator#createFromUserView(Class)}. + * + * @param userViewClass + * @return The construction information needed to create new instances conforming to the user view + * @throws IllegalArgumentException If the user view was not specified + */ + private static > Class getImplClassForUserView(final Class userViewClass) + throws IllegalArgumentException { + // Precondition checks + if (userViewClass == null) { + throw new IllegalArgumentException("User view class must be specified"); + } + + // Get the configuration from which we'll create new instances + final String className = userViewClass.getName(); + final String resourceName = MAPPING_LOCATION + className; + final ClassLoader tccl = SecurityActions.getThreadContextClassLoader(); + final InputStream resourceStream = tccl.getResourceAsStream(resourceName); + if (resourceStream == null) { + throw new IllegalArgumentException("No resource " + resourceName + " was found configured for user view class " + + userViewClass.getName()); + } + + // Load + final Properties props = new Properties(); + try { + props.load(resourceStream); + } catch (final IOException e) { + throw new RuntimeException("I/O Problem in reading the properties for " + userViewClass.getName(), e); + } + final String implClassName = props.getProperty(KEY_IMPL_CLASS_NAME); + if (implClassName == null || implClassName.length() == 0) { + throw new IllegalStateException("Resource " + resourceName + " for " + userViewClass + " does not contain key " + + KEY_IMPL_CLASS_NAME); + } + + // Load the Implementation class + final Class implClass; + try { + implClass = getImplClassForName(tccl, implClassName); + } catch (final ClassNotFoundException e) { + // Rethrow with some context + throw new IllegalStateException( + "Could not load specified implementation class from " + tccl + ": " + implClassName, e); + } + + // Return + return implClass; + } + + /** + * Uses the specified {@link ClassLoader} to create and return a {@link Class} instance for the specified class name. + * Externalized to suppress unchecked warnings. + * + * @param + * @param cl + * @param implClassName + * @return + */ + @SuppressWarnings("unchecked") + private static > Class getImplClassForName(final ClassLoader cl, + final String implClassName) throws ClassNotFoundException { + assert cl != null : "CL is required"; + assert implClassName != null && implClassName.length() > 0 : "Impl Class name is required"; + return (Class) Class.forName(implClassName, false, cl); + } } diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolutionFilter.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolutionFilter.java index 43809689..7a19185d 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolutionFilter.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolutionFilter.java @@ -1,13 +1,33 @@ -/** - * +/* + * JBoss, Home of Professional Open Source + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.jboss.shrinkwrap.resolver.api; /** + * Filtering encapsulation applied after elements are resolved + * * @author Andrew Lee Rubinger */ -public interface DependencyResolver, E extends ResolutionElement> -{ +public interface DependencyResolver, E extends ResolutionElement> { - /** - * Resolves dependencies for dependency builder - * - * @param archiveView End-user view of the archive requested (ie. - * {@link GenericArchive} or {@link JavaArchive}) - * @return An array of archives which contains resolved artifacts. - * @throws ResolutionException If artifacts could not be resolved - * @throws {@link IllegalArgumentException} If target archive view is not supplied - */ - Collection resolveAs(Class archiveView) - throws ResolutionException; + /** + * Resolves dependencies for dependency builder + * + * @param archiveView End-user view of the archive requested (ie. {@link GenericArchive} or {@link JavaArchive}) + * @return An array of archives which contains resolved artifacts. + * @throws ResolutionException If artifacts could not be resolved + * @throws {@link IllegalArgumentException} If target archive view is not supplied + */ + Collection resolveAs(Class archiveView) + throws ResolutionException; - /** - * Resolves dependencies for dependency builder. Uses a filter to limit - * dependency tree - * - * @param archiveView End-user view of the archive requested (ie. - * {@link GenericArchive} or {@link JavaArchive}) - * @param filter The filter to limit the dependencies during resolution - * @return An array of archive which contains resolved artifacts - * @throws ResolutionException - * @throws {@link IllegalArgumentException} If either argument is not supplied - */ - Collection resolveAs(Class archiveView, F filter) - throws ResolutionException; + /** + * Resolves dependencies for dependency builder. Uses a filter to limit dependency tree + * + * @param archiveView End-user view of the archive requested (ie. {@link GenericArchive} or {@link JavaArchive}) + * @param filter The filter to limit the dependencies during resolution + * @return An array of archive which contains resolved artifacts + * @throws ResolutionException + * @throws {@link IllegalArgumentException} If either argument is not supplied + */ + Collection resolveAs(Class archiveView, F filter) + throws ResolutionException; - /** - * Resolves dependencies for dependency builder - * - * @return An array of Files which contains resolved artifacts. - * @throws ResolutionException If artifacts could not be resolved - */ - File[] resolveAsFiles() throws ResolutionException; + /** + * Resolves dependencies for dependency builder + * + * @return An array of Files which contains resolved artifacts. + * @throws ResolutionException If artifacts could not be resolved + */ + File[] resolveAsFiles() throws ResolutionException; - /** - * Resolves dependencies for dependency builder. Uses a filter to limit - * dependency tree - * - * @param filter The filter to limit the dependencies during resolution - * @return An array of Files which contains resolved artifacts - * @throws ResolutionException - */ - File[] resolveAsFiles(F filter) throws ResolutionException; + /** + * Resolves dependencies for dependency builder. Uses a filter to limit dependency tree + * + * @param filter The filter to limit the dependencies during resolution + * @return An array of Files which contains resolved artifacts + * @throws ResolutionException + */ + File[] resolveAsFiles(F filter) throws ResolutionException; } diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolvers.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolvers.java index f079df87..cada5a96 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolvers.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/DependencyResolvers.java @@ -19,23 +19,21 @@ import org.jboss.shrinkwrap.api.Archive; /** - * Client entry point to resolve {@link Archive}s - * from a specified {@link DependencyBuilder} - * + * Client entry point to resolve {@link Archive}s from a specified {@link DependencyBuilder} + * * @author Karel Piwko * @author Andrew Lee Rubinger */ -public class DependencyResolvers -{ - /** - * Creates a new implementation of a dependency builder based on passed class. - * This allows to switch builder in the test suite dynamically - * @param The type of class which extends {@link DependencyBuilder} - * @param clazz the class - * @return The new instance of dependency builder backed by passed implementation - */ - public static > T use(final Class clazz) - { - return DependencyBuilderInstantiator.createFromUserView(clazz); - } +public class DependencyResolvers { + /** + * Creates a new implementation of a dependency builder based on passed class. This allows to switch builder in the test + * suite dynamically + * + * @param The type of class which extends {@link DependencyBuilder} + * @param clazz the class + * @return The new instance of dependency builder backed by passed implementation + */ + public static > T use(final Class clazz) { + return DependencyBuilderInstantiator.createFromUserView(clazz); + } } diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolutionElement.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolutionElement.java index 1946da2b..c635d749 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolutionElement.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolutionElement.java @@ -1,15 +1,27 @@ -/** - * +/* + * JBoss, Home of Professional Open Source + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.jboss.shrinkwrap.resolver.api; /** * A marker interface for resolution elements - * + * * @author Karel Piwko - * + * */ -public class ResolutionException extends RuntimeException -{ +public class ResolutionException extends RuntimeException { - /** - * + /** + * */ - private static final long serialVersionUID = -5494130553315008915L; + private static final long serialVersionUID = -5494130553315008915L; - /** - * @param message - */ - public ResolutionException(String message) - { - super(message); - } + /** + * @param message + */ + public ResolutionException(String message) { + super(message); + } - /** - * @param cause - */ - public ResolutionException(Throwable cause) - { - super(cause); - } + /** + * @param cause + */ + public ResolutionException(Throwable cause) { + super(cause); + } - /** - * @param message - * @param cause - */ - public ResolutionException(String message, Throwable cause) - { - super(message, cause); - } + /** + * @param message + * @param cause + */ + public ResolutionException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/SecurityActions.java b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/SecurityActions.java index 51d85fdd..65674f44 100644 --- a/api/src/main/java/org/jboss/shrinkwrap/resolver/api/SecurityActions.java +++ b/api/src/main/java/org/jboss/shrinkwrap/resolver/api/SecurityActions.java @@ -24,101 +24,87 @@ /** * A set of privileged actions that are not to leak out of this package - * + * * @author ALR * @author Karel Piwko - * + * * @version $Revision: $ */ -final class SecurityActions -{ +final class SecurityActions { - // -------------------------------------------------------------------------------|| - // Constructor -------------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Constructor -------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * No instantiation - */ - private SecurityActions() - { - throw new UnsupportedOperationException("No instantiation"); - } + /** + * No instantiation + */ + private SecurityActions() { + throw new UnsupportedOperationException("No instantiation"); + } - // -------------------------------------------------------------------------------|| - // Utility Methods ---------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Utility Methods ---------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * Obtains the Thread Context ClassLoader - */ - static ClassLoader getThreadContextClassLoader() - { - return AccessController.doPrivileged(GetTcclAction.INSTANCE); - } + /** + * Obtains the Thread Context ClassLoader + */ + static ClassLoader getThreadContextClassLoader() { + return AccessController.doPrivileged(GetTcclAction.INSTANCE); + } - /** - * Obtains the Constructor specified from the given Class and argument types - * - * @param clazz - * @param argumentTypes - * @return - * @throws NoSuchMethodException - */ - static Constructor getConstructor(final Class clazz, final Class... argumentTypes) - throws NoSuchMethodException - { - try - { - return AccessController.doPrivileged(new PrivilegedExceptionAction>() - { - public Constructor run() throws NoSuchMethodException - { - return clazz.getConstructor(argumentTypes); - } - }); - } - // Unwrap - catch (final PrivilegedActionException pae) - { - final Throwable t = pae.getCause(); - // Rethrow - if (t instanceof NoSuchMethodException) - { - throw (NoSuchMethodException) t; - } - else - { - // No other checked Exception thrown by Class.getConstructor - try - { - throw (RuntimeException) t; - } - // Just in case we've really messed up - catch (final ClassCastException cce) - { - throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + /** + * Obtains the Constructor specified from the given Class and argument types + * + * @param clazz + * @param argumentTypes + * @return + * @throws NoSuchMethodException + */ + static Constructor getConstructor(final Class clazz, final Class... argumentTypes) + throws NoSuchMethodException { + try { + return AccessController.doPrivileged(new PrivilegedExceptionAction>() { + public Constructor run() throws NoSuchMethodException { + return clazz.getConstructor(argumentTypes); + } + }); + } + // Unwrap + catch (final PrivilegedActionException pae) { + final Throwable t = pae.getCause(); + // Rethrow + if (t instanceof NoSuchMethodException) { + throw (NoSuchMethodException) t; + } else { + // No other checked Exception thrown by Class.getConstructor + try { + throw (RuntimeException) t; + } + // Just in case we've really messed up + catch (final ClassCastException cce) { + throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + } } - } - } - } + } + } - // -------------------------------------------------------------------------------|| - // Inner Classes - // ----------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Inner Classes + // ----------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * Single instance to get the TCCL - */ - private enum GetTcclAction implements PrivilegedAction { - INSTANCE; + /** + * Single instance to get the TCCL + */ + private enum GetTcclAction implements PrivilegedAction { + INSTANCE; - public ClassLoader run() - { - return Thread.currentThread().getContextClassLoader(); - } + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } - } + } } diff --git a/build-resources/pom.xml b/build-resources/pom.xml new file mode 100644 index 00000000..0362f365 --- /dev/null +++ b/build-resources/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-parent + 1.1.0-alpha-1-SNAPSHOT + ../pom.xml + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-build-resources + Shrinkwrap Resolver Build Resources + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + diff --git a/build-resources/src/main/resources/code-style/checkstyle.xml b/build-resources/src/main/resources/code-style/checkstyle.xml new file mode 100644 index 00000000..89eb4f4a --- /dev/null +++ b/build-resources/src/main/resources/code-style/checkstyle.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build-resources/src/main/resources/code-style/eclipse-cleanup-rules.xml b/build-resources/src/main/resources/code-style/eclipse-cleanup-rules.xml new file mode 100644 index 00000000..073992e9 --- /dev/null +++ b/build-resources/src/main/resources/code-style/eclipse-cleanup-rules.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build-resources/src/main/resources/code-style/eclipse-formatting-rules.xml b/build-resources/src/main/resources/code-style/eclipse-formatting-rules.xml new file mode 100644 index 00000000..7f65b3c6 --- /dev/null +++ b/build-resources/src/main/resources/code-style/eclipse-formatting-rules.xml @@ -0,0 +1,269 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build-resources/src/main/resources/code-style/eclipse-java-templates.xml b/build-resources/src/main/resources/code-style/eclipse-java-templates.xml new file mode 100644 index 00000000..b2090db6 --- /dev/null +++ b/build-resources/src/main/resources/code-style/eclipse-java-templates.xml @@ -0,0 +1,21 @@ + diff --git a/impl-maven/pom.xml b/impl-maven/pom.xml index 4145c259..2efae7a8 100644 --- a/impl-maven/pom.xml +++ b/impl-maven/pom.xml @@ -1,262 +1,267 @@ - + - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-parent - 1.1.0-alpha-1-SNAPSHOT - ../pom.xml - + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-parent + 1.1.0-alpha-1-SNAPSHOT + ../pom.xml + - - 4.0.0 + + 4.0.0 - - shrinkwrap-resolver-impl-maven - ShrinkWrap Resolver Maven Implementation - ShrinkWrap Extension for Resolving Dependencies from a Maven backend + + shrinkwrap-resolver-impl-maven + ShrinkWrap Resolver Maven Implementation + ShrinkWrap Extension for Resolving Dependencies from a Maven backend - - + + - - 1.8 - 3.0.1 - 1.0-beta-7 - ${basedir}/src/test/resources/artifacts/test-pom-in.jar + + 1.8 + 3.0.1 + 1.0-beta-7 + ${basedir}/src/test/resources/artifacts/test-pom-in.jar - + - - + + - - - org.jboss.shrinkwrap - shrinkwrap-api - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api - ${project.version} - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-api-maven - ${project.version} - - - org.jboss.shrinkwrap - shrinkwrap-impl-base - test - + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api + ${project.version} + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api-maven + ${project.version} + + + org.jboss.shrinkwrap + shrinkwrap-impl-base + test + - - - junit - junit - test - - - org.mortbay.jetty - jetty - 6.1.16 - test - + + + junit + junit + test + + + org.mortbay.jetty + jetty + 6.1.16 + test + - - - org.sonatype.aether - aether-api - ${version.org.sonatype.aether} - - - org.sonatype.aether - aether-util - ${version.org.sonatype.aether} - - - org.sonatype.aether - aether-connector-wagon - ${version.org.sonatype.aether} - - - junit - junit - - - - - org.sonatype.aether - aether-impl - ${version.org.sonatype.aether} - test - + + + org.sonatype.aether + aether-api + ${version.org.sonatype.aether} + + + org.sonatype.aether + aether-util + ${version.org.sonatype.aether} + + + org.sonatype.aether + aether-connector-wagon + ${version.org.sonatype.aether} + + + junit + junit + + + + + org.sonatype.aether + aether-impl + ${version.org.sonatype.aether} + test + - - - org.apache.maven - maven-aether-provider - ${version.org.apache.maven} - + + + org.apache.maven + maven-aether-provider + ${version.org.apache.maven} + - - org.apache.maven - maven-settings-builder - ${version.org.apache.maven} - + + org.apache.maven + maven-settings-builder + ${version.org.apache.maven} + - - - org.apache.maven.wagon - wagon-provider-api - ${version.org.apache.maven.wagon} - - - org.apache.maven.wagon - wagon-file - ${version.org.apache.maven.wagon} - - - org.apache.maven.wagon - wagon-http-lightweight - ${version.org.apache.maven.wagon} - - - nekohtml - nekohtml - - - nekohtml - xercesMinimal - - - + + + org.apache.maven.wagon + wagon-provider-api + ${version.org.apache.maven.wagon} + + + org.apache.maven.wagon + wagon-file + ${version.org.apache.maven.wagon} + + + org.apache.maven.wagon + wagon-http-lightweight + ${version.org.apache.maven.wagon} + + + nekohtml + nekohtml + + + nekohtml + xercesMinimal + + + - + - - + + - - - org.apache.maven.plugins - maven-surefire-plugin - - - ${appended.jar.for.test} - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-files-exist - - enforce - - - - - - ${appended.jar.for.test} - - - - true - - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.4.3 - - - copy-repository - process-test-resources - - copy-resources - - - ${basedir}/target/repository - - - ${basedir}/src/test/resources/repository - false - - - - - - copy-settings - process-test-resources - - copy-resources - - - ${basedir}/target/settings/profiles - - - ${basedir}/src/test/resources/profiles - true - - - - - - copy-poms - process-test-resources - - copy-resources - - - ${basedir}/target/poms - - - ${basedir}/src/test/resources/poms - true - - - - - - - + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${appended.jar.for.test} + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-files-exist + + enforce + + + + + + ${appended.jar.for.test} + + + + true + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.4.3 + + + copy-repository + process-test-resources + + copy-resources + + + ${basedir}/target/repository + + + ${basedir}/src/test/resources/repository + false + + + + + + copy-settings + process-test-resources + + copy-resources + + + ${basedir}/target/settings/profiles + + + ${basedir}/src/test/resources/profiles + true + + + + + + copy-poms + process-test-resources + + copy-resources + + + ${basedir}/target/poms + + + ${basedir}/src/test/resources/poms + true + + + + + + + - - - - - verbose - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.8.1 - - - logging.properties - - - - - - - - + + + + + verbose + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.8.1 + + + logging.properties + + + + + + + + diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactAsKey.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactAsKey.java index 5baea30a..8171d222 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactAsKey.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactAsKey.java @@ -20,124 +20,107 @@ import org.sonatype.aether.util.artifact.DefaultArtifact; /** - * A mapping for artifact resolved from POM file to a Map key. It is used to - * retrieve a version + * A mapping for artifact resolved from POM file to a Map key. It is used to retrieve a version * * @author Karel Piwko * */ -class ArtifactAsKey -{ - private final String groupId; - private final String artifactId; - private final String type; - private final String classifier; +class ArtifactAsKey { - /** - * Creates an artifact key - * - * @param groupId Group id - * @param artifactId Artifact id - * @param type Type, if empty or {@code null}, it is set to an empty string - * {@code jar} - * @param classifier Classifier, if {@code null}, it is set to an empty - * string - */ - public ArtifactAsKey(String groupId, String artifactId, String type, String classifier) - { - this.groupId = groupId; - this.artifactId = artifactId; - this.type = (type == null || type.length() == 0) ? "jar" : type; - this.classifier = (classifier == null || classifier.length() == 0) ? "" : classifier; - } + private final String groupId; + private final String artifactId; + private final String type; + private final String classifier; - public ArtifactAsKey(String coordinates) - { - this(new DefaultArtifact(coordinates)); - } + /** + * Creates an artifact key + * + * @param groupId Group id + * @param artifactId Artifact id + * @param type Type, if empty or {@code null}, it is set to an empty string {@code jar} + * @param classifier Classifier, if {@code null}, it is set to an empty string + */ + public ArtifactAsKey(String groupId, String artifactId, String type, String classifier) { + this.groupId = groupId; + this.artifactId = artifactId; + this.type = (type == null || type.length() == 0) ? "jar" : type; + this.classifier = (classifier == null || classifier.length() == 0) ? "" : classifier; + } - public ArtifactAsKey(org.apache.maven.model.Dependency d) - { - this(d.getGroupId(), d.getArtifactId(), d.getType(), d.getClassifier()); - } + public ArtifactAsKey(String coordinates) { + this(new DefaultArtifact(coordinates)); + } - public ArtifactAsKey(Artifact a) - { - this(a.getGroupId(), a.getArtifactId(), a.getExtension(), a.getClassifier()); - } + public ArtifactAsKey(org.apache.maven.model.Dependency d) { + this(d.getGroupId(), d.getArtifactId(), d.getType(), d.getClassifier()); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - return "ArtifactAsKey [artifactId=" + artifactId + ", classifier=" + classifier + ", groupId=" + groupId + ", type=" + type + "]"; - } + public ArtifactAsKey(Artifact a) { + this(a.getGroupId(), a.getArtifactId(), a.getExtension(), a.getClassifier()); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((classifier == null) ? 0 : classifier.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "ArtifactAsKey [artifactId=" + artifactId + ", classifier=" + classifier + ", groupId=" + groupId + ", type=" + + type + "]"; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ArtifactAsKey other = (ArtifactAsKey) obj; - if (artifactId == null) - { - if (other.artifactId != null) + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); + result = prime * result + ((classifier == null) ? 0 : classifier.hashCode()); + result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ArtifactAsKey other = (ArtifactAsKey) obj; + if (artifactId == null) { + if (other.artifactId != null) + return false; + } else if (!artifactId.equals(other.artifactId)) return false; - } - else if (!artifactId.equals(other.artifactId)) - return false; - if (classifier == null) - { - if (other.classifier != null) + if (classifier == null) { + if (other.classifier != null) + return false; + } else if (!classifier.equals(other.classifier)) return false; - } - else if (!classifier.equals(other.classifier)) - return false; - if (groupId == null) - { - if (other.groupId != null) + if (groupId == null) { + if (other.groupId != null) + return false; + } else if (!groupId.equals(other.groupId)) return false; - } - else if (!groupId.equals(other.groupId)) - return false; - if (type == null) - { - if (other.type != null) + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) return false; - } - else if (!type.equals(other.type)) - return false; - return true; - } + return true; + } } \ No newline at end of file diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogRepositoryListener.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogRepositoryListener.java index e3918704..747d2773 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogRepositoryListener.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogRepositoryListener.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright (c) 2010 Sonatype, Inc. All rights reserved. - * + * * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a @@ -27,204 +27,166 @@ /** * A listener which reports Maven repository event to a logger. - * + * * The logger is shared with {@link LogTransferListerer} - * + * * @author Karel Piwko - * + * */ -public class LogRepositoryListener extends AbstractRepositoryListener -{ - private static final Logger log = Logger.getLogger(LogRepositoryListener.class.getName()); - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactDeployed - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactDeployed(RepositoryEvent event) - { - log.fine("Deployed " + event.getArtifact() + " to " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactDeploying - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactDeploying(RepositoryEvent event) - { - log.finer("Deploying " + event.getArtifact() + " to " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# - * artifactDescriptorInvalid(org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactDescriptorInvalid(RepositoryEvent event) - { - log.warning("Invalid artifact descriptor for " + event.getArtifact() + ": " + event.getException().getMessage()); - } - - /* - * (non-Javadoc) - * - * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# - * artifactDescriptorMissing(org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactDescriptorMissing(RepositoryEvent event) - { - log.warning("Missing artifact descriptor for " + event.getArtifact()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactInstalled - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactInstalled(RepositoryEvent event) - { - log.fine("Installed " + event.getArtifact() + " to " + event.getFile()); - } - - /* - * (non-Javadoc) - * - * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# - * artifactInstalling(org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactInstalling(RepositoryEvent event) - { - log.finer("Installing " + event.getArtifact() + " to " + event.getFile()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactResolved - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactResolved(RepositoryEvent event) - { - log.fine("Resolved artifact " + event.getArtifact() + " from " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactResolving - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void artifactResolving(RepositoryEvent event) - { - log.finer("Resolving artifact " + event.getArtifact()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataDeployed - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataDeployed(RepositoryEvent event) - { - log.fine("Deployed " + event.getMetadata() + " to " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataDeploying - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataDeploying(RepositoryEvent event) - { - log.finer("Deploying " + event.getMetadata() + " to " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataInstalled - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataInstalled(RepositoryEvent event) - { - log.fine("Installed " + event.getMetadata() + " to " + event.getFile()); - } - - /* - * (non-Javadoc) - * - * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# - * metadataInstalling(org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataInstalling(RepositoryEvent event) - { - log.finer("Installing " + event.getMetadata() + " to " + event.getFile()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataInvalid - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataInvalid(RepositoryEvent event) - { - log.warning("Invalid metadata " + event.getMetadata()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataResolved - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataResolved(RepositoryEvent event) - { - log.fine("Resolved metadata " + event.getMetadata() + " from " + event.getRepository()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataResolving - * (org.sonatype.aether.RepositoryEvent) - */ - @Override - public void metadataResolving(RepositoryEvent event) - { - log.finer("Resolving metadata " + event.getMetadata() + " from " + event.getRepository()); - } +public class LogRepositoryListener extends AbstractRepositoryListener { + private static final Logger log = Logger.getLogger(LogRepositoryListener.class.getName()); + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactDeployed (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactDeployed(RepositoryEvent event) { + log.fine("Deployed " + event.getArtifact() + " to " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactDeploying (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactDeploying(RepositoryEvent event) { + log.finer("Deploying " + event.getArtifact() + " to " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# + * artifactDescriptorInvalid(org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactDescriptorInvalid(RepositoryEvent event) { + log.warning("Invalid artifact descriptor for " + event.getArtifact() + ": " + event.getException().getMessage()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# + * artifactDescriptorMissing(org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactDescriptorMissing(RepositoryEvent event) { + log.warning("Missing artifact descriptor for " + event.getArtifact()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactInstalled (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactInstalled(RepositoryEvent event) { + log.fine("Installed " + event.getArtifact() + " to " + event.getFile()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# + * artifactInstalling(org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactInstalling(RepositoryEvent event) { + log.finer("Installing " + event.getArtifact() + " to " + event.getFile()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactResolved (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactResolved(RepositoryEvent event) { + log.fine("Resolved artifact " + event.getArtifact() + " from " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#artifactResolving (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void artifactResolving(RepositoryEvent event) { + log.finer("Resolving artifact " + event.getArtifact()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataDeployed (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataDeployed(RepositoryEvent event) { + log.fine("Deployed " + event.getMetadata() + " to " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataDeploying (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataDeploying(RepositoryEvent event) { + log.finer("Deploying " + event.getMetadata() + " to " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataInstalled (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataInstalled(RepositoryEvent event) { + log.fine("Installed " + event.getMetadata() + " to " + event.getFile()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener# + * metadataInstalling(org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataInstalling(RepositoryEvent event) { + log.finer("Installing " + event.getMetadata() + " to " + event.getFile()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataInvalid (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataInvalid(RepositoryEvent event) { + log.warning("Invalid metadata " + event.getMetadata()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataResolved (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataResolved(RepositoryEvent event) { + log.fine("Resolved metadata " + event.getMetadata() + " from " + event.getRepository()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractRepositoryListener#metadataResolving (org.sonatype.aether.RepositoryEvent) + */ + @Override + public void metadataResolving(RepositoryEvent event) { + log.finer("Resolving metadata " + event.getMetadata() + " from " + event.getRepository()); + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogTransferListerer.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogTransferListerer.java index 6169ead2..d20f31f0 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogTransferListerer.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/LogTransferListerer.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright (c) 2010 Sonatype, Inc. All rights reserved. - * + * * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a @@ -33,154 +33,149 @@ /** * A listener which reports Maven transfer events to a logger. - * + * * The logger is shared with {@link LogRepositoryListener}. - * + * * @author Karel Piwko - * + * */ -public class LogTransferListerer extends AbstractTransferListener -{ - // set up new logger with output directed to standard out - private static final Logger log = Logger.getLogger(LogTransferListerer.class.getName()); - - // a map of transferred data sizes for the last notification - private Map downloads = new ConcurrentHashMap(); - - // a minimal amount of data transferred for an artifact required to inform - // the user - private static final long TRANSFER_THRESHOLD = 1024 * 50; - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractTransferListener#transferInitiated - * (org.sonatype.aether.transfer.TransferEvent) - */ - @Override - public void transferInitiated(TransferEvent event) - { - TransferResource resource = event.getResource(); - - StringBuilder sb = new StringBuilder().append(event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading").append(":").append(resource.getRepositoryUrl()).append(resource.getResourceName()); - - downloads.put(resource, new Long(0)); - log.fine(sb.toString()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractTransferListener#transferProgressed - * (org.sonatype.aether.transfer.TransferEvent) - */ - @Override - public void transferProgressed(TransferEvent event) - { - TransferResource resource = event.getResource(); - - long lastTransferred = downloads.get(resource); - long transferred = event.getTransferredBytes(); - - if (transferred - lastTransferred >= TRANSFER_THRESHOLD) - { - downloads.put(resource, Long.valueOf(transferred)); - long total = resource.getContentLength(); - log.finer(getStatus(transferred, total) + ", "); - } - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractTransferListener#transferSucceeded - * (org.sonatype.aether.transfer.TransferEvent) - */ - @Override - public void transferSucceeded(TransferEvent event) - { - TransferResource resource = event.getResource(); - - downloads.remove(resource); - - long contentLength = event.getTransferredBytes(); - if (contentLength >= 0) - { - long duration = System.currentTimeMillis() - resource.getTransferStartTime(); - double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0); - - StringBuilder sb = new StringBuilder().append("Completed").append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ").append(resource.getResourceName()).append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ").append(resource.getRepositoryUrl()).append(", transferred ").append(contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B").append(" at ").append(new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH)).format(kbPerSec)).append("KB/sec"); - - log.fine(sb.toString()); - } - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractTransferListener#transferFailed - * (org.sonatype.aether.transfer.TransferEvent) - */ - @Override - public void transferFailed(TransferEvent event) - { - TransferResource resource = event.getResource(); - - downloads.remove(resource); - - StringBuilder sb = new StringBuilder().append("Failed").append(event.getRequestType() == TransferEvent.RequestType.PUT ? " uploading " : " downloading ").append(resource.getResourceName()).append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ").append(resource.getRepositoryUrl()).append(", reason: ").append(event.getException().toString()); - - log.warning(sb.toString()); - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.util.listener.AbstractTransferListener#transferCorrupted - * (org.sonatype.aether.transfer.TransferEvent) - */ - @Override - public void transferCorrupted(TransferEvent event) - { - TransferResource resource = event.getResource(); - - downloads.remove(resource); - - StringBuilder sb = new StringBuilder().append("Corrupted").append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ").append(resource.getResourceName()).append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ").append(resource.getRepositoryUrl()).append(", reason: ").append(event.getException().toString()); - - log.warning(sb.toString()); - - } - - // converts into status message - private String getStatus(long complete, long total) - { - if (total >= 1024) - { - return toKB(complete) + "/" + toKB(total) + " KB"; - } - else if (total >= 0) - { - return complete + "/" + total + " B"; - } - else if (complete >= 1024) - { - return toKB(complete) + " KB"; - } - else - { - return complete + " B"; - } - } - - // converts bytes to kilobytes - private long toKB(long bytes) - { - return (bytes + 1023) / 1024; - } +public class LogTransferListerer extends AbstractTransferListener { + // set up new logger with output directed to standard out + private static final Logger log = Logger.getLogger(LogTransferListerer.class.getName()); + + // a map of transferred data sizes for the last notification + private Map downloads = new ConcurrentHashMap(); + + // a minimal amount of data transferred for an artifact required to inform + // the user + private static final long TRANSFER_THRESHOLD = 1024 * 50; + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractTransferListener#transferInitiated + * (org.sonatype.aether.transfer.TransferEvent) + */ + @Override + public void transferInitiated(TransferEvent event) { + TransferResource resource = event.getResource(); + + StringBuilder sb = new StringBuilder() + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading").append(":") + .append(resource.getRepositoryUrl()).append(resource.getResourceName()); + + downloads.put(resource, new Long(0)); + log.fine(sb.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractTransferListener#transferProgressed + * (org.sonatype.aether.transfer.TransferEvent) + */ + @Override + public void transferProgressed(TransferEvent event) { + TransferResource resource = event.getResource(); + + long lastTransferred = downloads.get(resource); + long transferred = event.getTransferredBytes(); + + if (transferred - lastTransferred >= TRANSFER_THRESHOLD) { + downloads.put(resource, Long.valueOf(transferred)); + long total = resource.getContentLength(); + log.finer(getStatus(transferred, total) + ", "); + } + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractTransferListener#transferSucceeded + * (org.sonatype.aether.transfer.TransferEvent) + */ + @Override + public void transferSucceeded(TransferEvent event) { + TransferResource resource = event.getResource(); + + downloads.remove(resource); + + long contentLength = event.getTransferredBytes(); + if (contentLength >= 0) { + long duration = System.currentTimeMillis() - resource.getTransferStartTime(); + double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0); + + StringBuilder sb = new StringBuilder().append("Completed") + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ") + .append(resource.getResourceName()) + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") + .append(resource.getRepositoryUrl()).append(", transferred ") + .append(contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B").append(" at ") + .append(new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH)).format(kbPerSec)) + .append("KB/sec"); + + log.fine(sb.toString()); + } + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractTransferListener#transferFailed + * (org.sonatype.aether.transfer.TransferEvent) + */ + @Override + public void transferFailed(TransferEvent event) { + TransferResource resource = event.getResource(); + + downloads.remove(resource); + + StringBuilder sb = new StringBuilder().append("Failed") + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " uploading " : " downloading ") + .append(resource.getResourceName()) + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") + .append(resource.getRepositoryUrl()).append(", reason: ").append(event.getException().toString()); + + log.warning(sb.toString()); + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.util.listener.AbstractTransferListener#transferCorrupted + * (org.sonatype.aether.transfer.TransferEvent) + */ + @Override + public void transferCorrupted(TransferEvent event) { + TransferResource resource = event.getResource(); + + downloads.remove(resource); + + StringBuilder sb = new StringBuilder().append("Corrupted") + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ") + .append(resource.getResourceName()) + .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") + .append(resource.getRepositoryUrl()).append(", reason: ").append(event.getException().toString()); + + log.warning(sb.toString()); + + } + + // converts into status message + private String getStatus(long complete, long total) { + if (total >= 1024) { + return toKB(complete) + "/" + toKB(total) + " KB"; + } else if (total >= 0) { + return complete + "/" + total + " B"; + } else if (complete >= 1024) { + return toKB(complete) + " KB"; + } else { + return complete + " B"; + } + } + + // converts bytes to kilobytes + private long toKB(long bytes) { + return (bytes + 1023) / 1024; + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenBuilderImpl.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenBuilderImpl.java index d3541bbd..f97eb960 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenBuilderImpl.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenBuilderImpl.java @@ -3,7 +3,7 @@ * Copyright 2010, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. - * + * * Licensed 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 @@ -52,934 +52,798 @@ /** * A default implementation of dependency builder based on Maven. - * - * Apart from contract, it allows to load Maven settings from an XML file, - * configure remote repositories from an POM file and retrieve dependencies - * defined in a POM file, including ones in POM parents. - * + * + * Apart from contract, it allows to load Maven settings from an XML file, configure remote repositories from an POM file and + * retrieve dependencies defined in a POM file, including ones in POM parents. + * * Maven can be configured externally, using following properties: - * + * *
    *
  • {@see MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION} - a path to local settings.xml file
  • *
  • {@see MavenSettingsBuilder.ALT_GLOBAL_SETTINGS_XML_LOCATION} - a path to global settings.xml file
  • *
  • {@see MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION} - a path to local repository
  • *
  • {@see MavenSettingsBuilder.ALT_MAVEN_OFFLINE} - a flag to go offline
  • *
- * + * * @author Karel Piwko * @author Jose Rodolfo freitas * @see MavenSettingsBuilder */ -public class MavenBuilderImpl implements MavenDependencyResolverInternal -{ - - private static final Logger log = Logger.getLogger(MavenArtifactBuilderImpl.class.getName()); - - private static final String CLASSPATH_QUALIFIER = "classpath:"; - private static final String FILE_QUALIFIER = "file:"; - - private static final File[] FILE_CAST = new File[0]; - - private final MavenRepositorySystem system; - private final MavenDependencyResolverSettings settings; - - private RepositorySystemSession session; - - // private final RepositorySystemSession session; - - // these are package visible, so they can be wrapped and make visible for - // filters - Stack dependencies; - - Map pomInternalDependencyManagement; - - @Override - public Stack getDependencies() - { - return dependencies; - } - - @Override - public Map getPomInternalDependencyManagement() - { - return pomInternalDependencyManagement; - } - - /** - * Constructs new instance of MavenDependencies - */ - public MavenBuilderImpl() - { - this.system = new MavenRepositorySystem(); - this.settings = new MavenDependencyResolverSettings(); - this.dependencies = new Stack(); - this.pomInternalDependencyManagement = new HashMap(); - // get session to spare time - this.session = system.getSession(settings); - } - - /** - * Configures Maven from a settings.xml file - * - * @param path A path to a settings.xml configuration file - * @return A dependency builder with a configuration from given file - */ - @Override - public MavenDependencyResolver configureFrom(final String path) - { - String resolvedPath = resolvePathByQualifier(path); - Validate.isReadable(resolvedPath, "Path to the settings.xml ('" + path + "') must be defined and accessible"); - - system.loadSettings(new File(resolvedPath), settings); - // regenerate session - this.session = system.getSession(settings); - return this; - } - - - - /** - * Loads remote repositories for a POM file. If repositories are defined in - * the parent of the POM file and there are accessible via local file system, - * they are set as well. - * - * These remote repositories are used to resolve the artifacts during - * dependency resolution. - * - * Additionally, it loads dependencies defined in the POM file model in an - * internal cache, which can be later used to resolve an artifact without - * explicitly specifying its version. - * - * @param path A path to the POM file, must not be {@code null} or empty - * @return A dependency builder with remote repositories set according to the - * content of POM file. - * @throws Exception - */ - - @Override - public MavenDependencyResolver loadMetadataFromPom(final String path) throws ResolutionException - { - String resolvedPath = resolvePathByQualifier(path); - Validate.isReadable(resolvedPath, "Path to the pom.xml ('" + path + "')file must be defined and accessible"); - - File pom = new File(resolvedPath); - Model model = system.loadPom(pom, settings, session); - - ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); - - // store all dependency information to be able to retrieve versions later - for (org.apache.maven.model.Dependency dependency : model.getDependencies()) - { - MavenDependency d = MavenConverter.fromDependency(dependency, stereotypes); - pomInternalDependencyManagement.put(new ArtifactAsKey(d.getCoordinates()), d); - } - - return this; - } - - /** - * @deprecated please use {@link #loadMetadataFromPom(String)} instead - */ - @Override - @Deprecated - public MavenDependencyResolver loadReposFromPom(final String path) throws ResolutionException - { - return loadMetadataFromPom(path); - } - - /** - * Loads dependencies from the specified path and applies the specified MavenResolutionFilter. - * Adds the Maven central repository by default. - * - * @param path path to file which contains the desired dependencies - * @param filter the filter to apply - * @return a corresponding MavenDependencyResolver - * @throws ResolutionException if any resolution related exceptions occur - */ - - @Override - public MavenDependencyResolver includeDependenciesFromPom(final String path) throws ResolutionException - { - String resolvedPath = resolvePathByQualifier(path); - Validate.isReadable(resolvedPath, "Path to the pom.xml file must be defined and accessible"); - - File pom = new File(resolvedPath); - Model model = system.loadPom(pom, settings, session); - - ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); - - for (org.apache.maven.model.Dependency dependency : model.getDependencies()) - { - dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); - } - return this; - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - - @Override - @Deprecated - public MavenDependencyResolver loadDependenciesFromPom(final String path) throws ResolutionException - { - return includeDependenciesFromPom(path); - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - @Override - @Deprecated - public MavenDependencyResolver loadDependenciesFromPom(final String path, final MavenResolutionFilter filter) - throws ResolutionException - { - return includeDependenciesFromPom(path); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang - * .String) - */ - @Override - public MavenDependencyResolver artifact(String coordinates) throws ResolutionException - { - Validate.notNullOrEmpty(coordinates, "Artifact coordinates must not be null or empty"); - - return new MavenArtifactBuilderImpl(this, coordinates); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang - * .String) - */ - @Override - public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException - { - Validate.notNullAndNoNullValues(coordinates, "Artifacts coordinates must not be null or empty"); - - return new MavenArtifactsBuilderImpl(this, coordinates); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #exclusion(org.sonatype.aether.graph.Exclusion) - */ - @Override - public MavenDependencyResolver exclusion(String coordinates) - { - MavenDependency dependency = dependencies.peek(); - dependency.addExclusions(coordinates); - - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #exclusions(org.sonatype.aether.graph.Exclusion[]) - */ - @Override - public MavenDependencyResolver exclusions(String... coordinates) - { - MavenDependency dependency = dependencies.peek(); - dependency.addExclusions(coordinates); - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #exclusions(java.util.Collection) - */ - @Override - public MavenDependencyResolver exclusions(Collection coordinates) - { - MavenDependency dependency = dependencies.peek(); - dependency.addExclusions(coordinates.toArray(new String[0])); - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #optional(boolean) - */ - @Override - public MavenDependencyResolver optional(boolean optional) - { - MavenDependency dependency = dependencies.peek(); - dependency.setOptional(optional); - - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #scope(java.lang.String) - */ - @Override - public MavenDependencyResolver scope(String scope) - { - MavenDependency dependency = dependencies.peek(); - dependency.setScope(scope); - - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #resolveAsFiles() - */ - @Override - public File[] resolveAsFiles() throws ResolutionException - { - return resolveAsFiles(AcceptAllFilter.INSTANCE); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #resolveAsFiles() - */ - @Override - public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException - { - Validate.notEmpty(dependencies, "No dependencies were set for resolution"); - - CollectRequest request = new CollectRequest(MavenConverter.asDependencies(dependencies), null, - settings.getRemoteRepositories()); - - // configure filter - filter.configure(Collections.unmodifiableList(dependencies)); - - // wrap artifact files to archives - Collection artifacts; - try - { - artifacts = system.resolveDependencies(session, request, filter); - } - catch (DependencyCollectionException e) - { - throw new ResolutionException("Unable to collect dependeny tree for a resolution", e); - } - catch (ArtifactResolutionException e) - { - throw new ResolutionException("Unable to resolve an artifact", e); - } - - Collection files = new ArrayList(artifacts.size()); - for (ArtifactResult artifact : artifacts) - { - Artifact a = artifact.getArtifact(); - // skip all pom artifacts - if ("pom".equals(a.getExtension())) - { - log.info("Removed POM artifact " + a.toString() + " from archive, it's dependencies were fetched."); - continue; - } - - files.add(a.getFile()); - } - - return files.toArray(FILE_CAST); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #resolve() - */ - @Override - public Collection resolveAs(final Class archiveView) - throws ResolutionException - { - return resolveAs(archiveView, AcceptAllFilter.INSTANCE); - } - - /** - * {@inheritDoc} - * - * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#useCentralRepo(boolean) - */ - @Override - public MavenDependencyResolver useCentralRepo(final boolean useCentral) - { - settings.setUseMavenCentral(useCentral); - return this; - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder - * #resolve(org.sonatype.aether.graph.DependencyFilter) - */ - @Override - public Collection resolveAs(final Class archiveView, - MavenResolutionFilter filter) throws ResolutionException - { - // Precondition checks - if (archiveView == null) - { - throw new IllegalArgumentException("Archive view must be specified"); - } - if (filter == null) - { - throw new IllegalArgumentException("Filter must be specified"); - } - - final File[] files = resolveAsFiles(filter); - final Collection archives = new ArrayList(files.length); - for (final File file : files) - { - final ARCHIVEVIEW archive = ShrinkWrap.create(ZipImporter.class, file.getName()).importFrom(convert(file)) - .as(archiveView); - archives.add(archive); - } - - return archives; - } - - // converts a file to a ZIP file - private ZipFile convert(File file) throws ResolutionException - { - try - { - return new ZipFile(file); - } - catch (ZipException e) - { - throw new ResolutionException("Unable to treat dependency artifact \"" + file.getAbsolutePath() - + "\" as a ZIP file", e); - } - catch (IOException e) - { - throw new ResolutionException("Unable to access artifact file at \"" + file.getAbsolutePath() + "\".", e); - } - } - - class MavenArtifactBuilderImpl implements MavenDependencyResolverInternal - { - private final MavenDependencyResolverInternal delegate; - - MavenArtifactBuilderImpl(final MavenDependencyResolverInternal delegate, String coordinates) - throws ResolutionException - { - assert delegate != null : "Delegate must be specified"; - this.delegate = delegate; - coordinates = MavenConverter.resolveArtifactVersion(pomInternalDependencyManagement, coordinates); - MavenDependency dependency = new MavenDependencyImpl(coordinates); - delegate.getDependencies().push(dependency); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang - * .String) - */ - - @Override - public MavenDependencyResolver artifact(String coordinates) - { - Validate.notNullOrEmpty(coordinates, "Artifact coordinates must not be null or empty"); - return new MavenArtifactsBuilderImpl(this, coordinates); - } - - /* - * (non-Javadoc) - * - * @see - * org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifacts(java. - * lang.String[]) - */ - - @Override - public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException - { - Validate.notNullAndNoNullValues(coordinates, "Artifacts coordinates must not be null or empty"); - return new MavenArtifactsBuilderImpl(this, coordinates); - } - - @Override - public Collection resolveAs(Class archiveView) - throws ResolutionException - { - return delegate.resolveAs(archiveView); - } - - @Override - public Collection resolveAs(Class archiveView, - MavenResolutionFilter filter) throws ResolutionException - { - return delegate.resolveAs(archiveView, filter); - } - - @Override - public File[] resolveAsFiles() throws ResolutionException - { - return delegate.resolveAsFiles(); - } - - @Override - public MavenDependencyResolver configureFrom(String path) - { - return delegate.configureFrom(path); - } - - @Override - public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException - { - return delegate.resolveAsFiles(filter); - } - - @Override - public MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException - { - return delegate.loadMetadataFromPom(path); - } - - /** - * @deprecated please use {@link #loadMetadataFromPom(String)} instead - */ - - @Override - public MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException - { - return delegate.loadReposFromPom(path); - } - - @Override - public MavenDependencyResolver scope(String scope) - { - return delegate.scope(scope); - } - - @Override - public MavenDependencyResolver optional(boolean optional) - { - return delegate.optional(optional); - } - - @Override - public MavenDependencyResolver exclusion(String exclusion) - { - return delegate.exclusion(exclusion); - } - - @Override - public MavenDependencyResolver exclusions(String... exclusions) - { - return delegate.exclusions(exclusions); - } - - @Override - public MavenDependencyResolver exclusions(Collection exclusions) - { - return delegate.exclusions(exclusions); - } - - @Override - public Stack getDependencies() - { - return delegate.getDependencies(); - } - - @Override - public Map getPomInternalDependencyManagement() - { - return delegate.getPomInternalDependencyManagement(); - } - - @Override - public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException - { - return delegate.includeDependenciesFromPom(path); - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - - @Override - public MavenDependencyResolver loadDependenciesFromPom(String path) throws ResolutionException - { - return delegate.loadDependenciesFromPom(path); - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - - @Override - public MavenDependencyResolver loadDependenciesFromPom(String path, MavenResolutionFilter filter) - throws ResolutionException - { - return delegate.loadDependenciesFromPom(path, filter); - } - - @Override - public MavenDependencyResolver useCentralRepo(final boolean useCentral) - { - return delegate.useCentralRepo(useCentral); - } - - @Override - public MavenDependencyResolver goOffline() - { - return delegate.goOffline(); - } - - } - - static class MavenArtifactsBuilderImpl implements MavenDependencyResolverInternal - { - private final MavenDependencyResolverInternal delegate; - - private int size; - - MavenArtifactsBuilderImpl(final MavenDependencyResolverInternal delegate, final String... coordinates) - { - assert delegate != null : "Delegate must be specified"; - this.delegate = delegate; - - this.size = coordinates.length; - - for (String coords : coordinates) - { - coords = MavenConverter.resolveArtifactVersion(delegate.getPomInternalDependencyManagement(), coords); - MavenDependency dependency = new MavenDependencyImpl(coords); +public class MavenBuilderImpl implements MavenDependencyResolverInternal { + + private static final Logger log = Logger.getLogger(MavenArtifactBuilderImpl.class.getName()); + + private static final String CLASSPATH_QUALIFIER = "classpath:"; + private static final String FILE_QUALIFIER = "file:"; + + private static final File[] FILE_CAST = new File[0]; + + private final MavenRepositorySystem system; + private final MavenDependencyResolverSettings settings; + + private RepositorySystemSession session; + + // private final RepositorySystemSession session; + + // these are package visible, so they can be wrapped and make visible for + // filters + Stack dependencies; + + Map pomInternalDependencyManagement; + + @Override + public Stack getDependencies() { + return dependencies; + } + + @Override + public Map getPomInternalDependencyManagement() { + return pomInternalDependencyManagement; + } + + /** + * Constructs new instance of MavenDependencies + */ + public MavenBuilderImpl() { + this.system = new MavenRepositorySystem(); + this.settings = new MavenDependencyResolverSettings(); + this.dependencies = new Stack(); + this.pomInternalDependencyManagement = new HashMap(); + // get session to spare time + this.session = system.getSession(settings); + } + + /** + * Configures Maven from a settings.xml file + * + * @param path A path to a settings.xml configuration file + * @return A dependency builder with a configuration from given file + */ + @Override + public MavenDependencyResolver configureFrom(final String path) { + String resolvedPath = resolvePathByQualifier(path); + Validate.isReadable(resolvedPath, "Path to the settings.xml ('" + path + "') must be defined and accessible"); + + system.loadSettings(new File(resolvedPath), settings); + // regenerate session + this.session = system.getSession(settings); + return this; + } + + /** + * Loads remote repositories for a POM file. If repositories are defined in the parent of the POM file and there are + * accessible via local file system, they are set as well. + * + * These remote repositories are used to resolve the artifacts during dependency resolution. + * + * Additionally, it loads dependencies defined in the POM file model in an internal cache, which can be later used to + * resolve an artifact without explicitly specifying its version. + * + * @param path A path to the POM file, must not be {@code null} or empty + * @return A dependency builder with remote repositories set according to the content of POM file. + * @throws Exception + */ + + @Override + public MavenDependencyResolver loadMetadataFromPom(final String path) throws ResolutionException { + String resolvedPath = resolvePathByQualifier(path); + Validate.isReadable(resolvedPath, "Path to the pom.xml ('" + path + "')file must be defined and accessible"); + + File pom = new File(resolvedPath); + Model model = system.loadPom(pom, settings, session); + + ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); + + // store all dependency information to be able to retrieve versions later + for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { + MavenDependency d = MavenConverter.fromDependency(dependency, stereotypes); + pomInternalDependencyManagement.put(new ArtifactAsKey(d.getCoordinates()), d); + } + + return this; + } + + /** + * @deprecated please use {@link #loadMetadataFromPom(String)} instead + */ + @Override + @Deprecated + public MavenDependencyResolver loadReposFromPom(final String path) throws ResolutionException { + return loadMetadataFromPom(path); + } + + /** + * Loads dependencies from the specified path and applies the specified MavenResolutionFilter. Adds the Maven + * central repository by default. + * + * @param path path to file which contains the desired dependencies + * @param filter the filter to apply + * @return a corresponding MavenDependencyResolver + * @throws ResolutionException if any resolution related exceptions occur + */ + + @Override + public MavenDependencyResolver includeDependenciesFromPom(final String path) throws ResolutionException { + String resolvedPath = resolvePathByQualifier(path); + Validate.isReadable(resolvedPath, "Path to the pom.xml file must be defined and accessible"); + + File pom = new File(resolvedPath); + Model model = system.loadPom(pom, settings, session); + + ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); + + for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { + dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); + } + return this; + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + + @Override + @Deprecated + public MavenDependencyResolver loadDependenciesFromPom(final String path) throws ResolutionException { + return includeDependenciesFromPom(path); + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + @Override + @Deprecated + public MavenDependencyResolver loadDependenciesFromPom(final String path, final MavenResolutionFilter filter) + throws ResolutionException { + return includeDependenciesFromPom(path); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang .String) + */ + @Override + public MavenDependencyResolver artifact(String coordinates) throws ResolutionException { + Validate.notNullOrEmpty(coordinates, "Artifact coordinates must not be null or empty"); + + return new MavenArtifactBuilderImpl(this, coordinates); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang .String) + */ + @Override + public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException { + Validate.notNullAndNoNullValues(coordinates, "Artifacts coordinates must not be null or empty"); + + return new MavenArtifactsBuilderImpl(this, coordinates); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #exclusion(org.sonatype.aether.graph.Exclusion) + */ + @Override + public MavenDependencyResolver exclusion(String coordinates) { + MavenDependency dependency = dependencies.peek(); + dependency.addExclusions(coordinates); + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder + * #exclusions(org.sonatype.aether.graph.Exclusion[]) + */ + @Override + public MavenDependencyResolver exclusions(String... coordinates) { + MavenDependency dependency = dependencies.peek(); + dependency.addExclusions(coordinates); + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #exclusions(java.util.Collection) + */ + @Override + public MavenDependencyResolver exclusions(Collection coordinates) { + MavenDependency dependency = dependencies.peek(); + dependency.addExclusions(coordinates.toArray(new String[0])); + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #optional(boolean) + */ + @Override + public MavenDependencyResolver optional(boolean optional) { + MavenDependency dependency = dependencies.peek(); + dependency.setOptional(optional); + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #scope(java.lang.String) + */ + @Override + public MavenDependencyResolver scope(String scope) { + MavenDependency dependency = dependencies.peek(); + dependency.setScope(scope); + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #resolveAsFiles() + */ + @Override + public File[] resolveAsFiles() throws ResolutionException { + return resolveAsFiles(AcceptAllFilter.INSTANCE); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #resolveAsFiles() + */ + @Override + public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException { + Validate.notEmpty(dependencies, "No dependencies were set for resolution"); + + CollectRequest request = new CollectRequest(MavenConverter.asDependencies(dependencies), null, + settings.getRemoteRepositories()); + + // configure filter + filter.configure(Collections.unmodifiableList(dependencies)); + + // wrap artifact files to archives + Collection artifacts; + try { + artifacts = system.resolveDependencies(session, request, filter); + } catch (DependencyCollectionException e) { + throw new ResolutionException("Unable to collect dependeny tree for a resolution", e); + } catch (ArtifactResolutionException e) { + throw new ResolutionException("Unable to resolve an artifact", e); + } + + Collection files = new ArrayList(artifacts.size()); + for (ArtifactResult artifact : artifacts) { + Artifact a = artifact.getArtifact(); + // skip all pom artifacts + if ("pom".equals(a.getExtension())) { + log.info("Removed POM artifact " + a.toString() + " from archive, it's dependencies were fetched."); + continue; + } + + files.add(a.getFile()); + } + + return files.toArray(FILE_CAST); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder #resolve() + */ + @Override + public Collection resolveAs(final Class archiveView) + throws ResolutionException { + return resolveAs(archiveView, AcceptAllFilter.INSTANCE); + } + + /** + * {@inheritDoc} + * + * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#useCentralRepo(boolean) + */ + @Override + public MavenDependencyResolver useCentralRepo(final boolean useCentral) { + settings.setUseMavenCentral(useCentral); + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder.ArtifactBuilder + * #resolve(org.sonatype.aether.graph.DependencyFilter) + */ + @Override + public Collection resolveAs(final Class archiveView, + MavenResolutionFilter filter) throws ResolutionException { + // Precondition checks + if (archiveView == null) { + throw new IllegalArgumentException("Archive view must be specified"); + } + if (filter == null) { + throw new IllegalArgumentException("Filter must be specified"); + } + + final File[] files = resolveAsFiles(filter); + final Collection archives = new ArrayList(files.length); + for (final File file : files) { + final ARCHIVEVIEW archive = ShrinkWrap.create(ZipImporter.class, file.getName()).importFrom(convert(file)) + .as(archiveView); + archives.add(archive); + } + + return archives; + } + + // converts a file to a ZIP file + private ZipFile convert(File file) throws ResolutionException { + try { + return new ZipFile(file); + } catch (ZipException e) { + throw new ResolutionException("Unable to treat dependency artifact \"" + file.getAbsolutePath() + + "\" as a ZIP file", e); + } catch (IOException e) { + throw new ResolutionException("Unable to access artifact file at \"" + file.getAbsolutePath() + "\".", e); + } + } + + class MavenArtifactBuilderImpl implements MavenDependencyResolverInternal { + private final MavenDependencyResolverInternal delegate; + + MavenArtifactBuilderImpl(final MavenDependencyResolverInternal delegate, String coordinates) throws ResolutionException { + assert delegate != null : "Delegate must be specified"; + this.delegate = delegate; + coordinates = MavenConverter.resolveArtifactVersion(pomInternalDependencyManagement, coordinates); + MavenDependency dependency = new MavenDependencyImpl(coordinates); delegate.getDependencies().push(dependency); - } - } - - /** - * {@inheritDoc} - * - * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#optional(boolean) - */ - - @Override - public MavenDependencyResolver optional(boolean optional) - { - List workplace = new ArrayList(); - - int i; - for (i = 0; i < size; i++) - { - MavenDependency dependency = delegate.getDependencies().pop(); - workplace.add(dependency.setOptional(optional)); - } - - for (; i > 0; i--) - { - delegate.getDependencies().push(workplace.get(i - 1)); - } - - return this; - } - - /** - * {@inheritDoc} - * - * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#scope(java.lang.String) - */ - - @Override - public MavenDependencyResolver scope(String scope) - { - List workplace = new ArrayList(); - - int i; - for (i = 0; i < size; i++) - { - MavenDependency dependency = delegate.getDependencies().pop(); - workplace.add(dependency.setScope(scope)); - } - - for (; i > 0; i--) - { - delegate.getDependencies().push(workplace.get(i - 1)); - } - - return this; - } - - /** - * {@inheritDoc} - * - * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#exclusions(java.lang.String[]) - */ - - @Override - public MavenDependencyResolver exclusions(String... coordinates) - { - List workplace = new ArrayList(); - - int i; - for (i = 0; i < size; i++) - { - MavenDependency dependency = delegate.getDependencies().pop(); - workplace.add(dependency.addExclusions(coordinates)); - } - - for (; i > 0; i--) - { - delegate.getDependencies().push(workplace.get(i - 1)); - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see org.jboss.shrinkwrap.dependencies.impl.MavenDependencies. - * MavenArtifactBuilder#exclusions(java.util.Collection) - */ - - @Override - public MavenDependencyResolver exclusions(Collection coordinates) - { - List workplace = new ArrayList(); - - int i; - for (i = 0; i < size; i++) - { - MavenDependency dependency = delegate.getDependencies().pop(); - workplace.add(dependency.addExclusions(coordinates.toArray(new String[0]))); - } - - for (; i > 0; i--) - { - delegate.getDependencies().push(workplace.get(i - 1)); - } - - return this; - } - - /* - * (non-Javadoc) - * - * @see org.jboss.shrinkwrap.dependencies.impl.MavenDependencies. - * MavenArtifactBuilder#exclusion(org.sonatype.aether.graph.Exclusion) - */ - - @Override - public MavenDependencyResolver exclusion(String exclusion) - { - List workplace = new ArrayList(); - - int i; - for (i = 0; i < size; i++) - { - MavenDependency dependency = delegate.getDependencies().pop(); - workplace.add(dependency.addExclusions(exclusion)); - } - - for (; i > 0; i--) - { - delegate.getDependencies().push(workplace.get(i - 1)); - } - - return this; - } - - @Override - public int hashCode() - { - return delegate.hashCode(); - } - - @Override - public boolean equals(Object obj) - { - return delegate.equals(obj); - } - - @Override - public MavenDependencyResolver configureFrom(String path) - { - return delegate.configureFrom(path); - } - - @Override - public MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException - { - return delegate.loadMetadataFromPom(path); - } - - /** - * @deprecated please use {@link #loadMetadataFromPom(String)} instead - */ - - @Override - public MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException - { - return delegate.loadReposFromPom(path); - } - - @Override - public MavenDependencyResolver artifact(String coordinates) throws ResolutionException - { - return delegate.artifact(coordinates); - } - - @Override - public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException - { - return delegate.artifacts(coordinates); - } - - @Override - public File[] resolveAsFiles() throws ResolutionException - { - return delegate.resolveAsFiles(); - } - - @Override - public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException - { - return delegate.resolveAsFiles(filter); - } - - @Override - public String toString() - { - return delegate.toString(); - } - - @Override - public Collection resolveAs(Class archiveView) - throws ResolutionException - { - return delegate.resolveAs(archiveView); - } - - @Override - public Collection resolveAs(Class archiveView, - MavenResolutionFilter filter) throws ResolutionException - { - return delegate.resolveAs(archiveView, filter); - } - - @Override - public Stack getDependencies() - { - return delegate.getDependencies(); - } - - @Override - public Map getPomInternalDependencyManagement() - { - return delegate.getPomInternalDependencyManagement(); - } - - @Override - public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException - { - return delegate.includeDependenciesFromPom(path); - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - @Override - public MavenDependencyResolver loadDependenciesFromPom(String path) throws ResolutionException - { - return delegate.loadDependenciesFromPom(path); - } - - /** - * @deprecated please use {@link #includeDependenciesFromPom(String)} instead - */ - @Override - public MavenDependencyResolver loadDependenciesFromPom(String path, MavenResolutionFilter filter) - throws ResolutionException - { - return delegate.loadDependenciesFromPom(path, filter); - } - - @Override - public MavenDependencyResolver useCentralRepo(final boolean useCentral) - { - return delegate.useCentralRepo(useCentral); - } - - @Override - public MavenDependencyResolver goOffline() - { - return delegate.goOffline(); - } - - } - - @Override - public MavenDependencyResolver goOffline() - { - settings.setOffline(true); - // regenerate session - this.session = system.getSession(settings); - return this; - } - - /** - * Gets a resource from the TCCL and returns its name As resource in classpath. - * - * @param resourceName is the name of the resource in the classpath - * @return the file path for resourceName @see {@link java.net.URL#getFile()} - * @throws IllegalArgumentException if resourceName doesn't exist in the classpath or privileges are not granted - */ - private String getLocalResourcePathFromResourceName(final String resourceName) - { - final URL resourceUrl = SecurityActions.getResource(resourceName); - Validate.notNull(resourceUrl, resourceName + " doesn't exist or can't be accessed on classpath"); - - try { - File localResource = File.createTempFile("sw_resource", "xml"); - localResource.deleteOnExit(); - IOUtil.copyWithClose(resourceUrl.openStream(), new FileOutputStream(localResource)); - return localResource.getAbsolutePath(); - } - catch(IOException e) { - throw new IllegalArgumentException("Unable to open resource name specified by " + resourceName, e); - } - } - - private String resolvePathByQualifier(String path) { - if (path.startsWith(CLASSPATH_QUALIFIER)) { - path = getLocalResourcePathFromResourceName(path.replace(CLASSPATH_QUALIFIER, "")); - } else if (path.startsWith(FILE_QUALIFIER)) { - path = path.replace(FILE_QUALIFIER, ""); - } - return path; - } + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifact(java.lang .String) + */ + + @Override + public MavenDependencyResolver artifact(String coordinates) { + Validate.notNullOrEmpty(coordinates, "Artifact coordinates must not be null or empty"); + return new MavenArtifactsBuilderImpl(this, coordinates); + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.DependencyBuilder#artifacts(java. lang.String[]) + */ + + @Override + public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException { + Validate.notNullAndNoNullValues(coordinates, "Artifacts coordinates must not be null or empty"); + return new MavenArtifactsBuilderImpl(this, coordinates); + } + + @Override + public Collection resolveAs(Class archiveView) + throws ResolutionException { + return delegate.resolveAs(archiveView); + } + + @Override + public Collection resolveAs(Class archiveView, + MavenResolutionFilter filter) throws ResolutionException { + return delegate.resolveAs(archiveView, filter); + } + + @Override + public File[] resolveAsFiles() throws ResolutionException { + return delegate.resolveAsFiles(); + } + + @Override + public MavenDependencyResolver configureFrom(String path) { + return delegate.configureFrom(path); + } + + @Override + public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException { + return delegate.resolveAsFiles(filter); + } + + @Override + public MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException { + return delegate.loadMetadataFromPom(path); + } + + /** + * @deprecated please use {@link #loadMetadataFromPom(String)} instead + */ + + @Override + public MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException { + return delegate.loadReposFromPom(path); + } + + @Override + public MavenDependencyResolver scope(String scope) { + return delegate.scope(scope); + } + + @Override + public MavenDependencyResolver optional(boolean optional) { + return delegate.optional(optional); + } + + @Override + public MavenDependencyResolver exclusion(String exclusion) { + return delegate.exclusion(exclusion); + } + + @Override + public MavenDependencyResolver exclusions(String... exclusions) { + return delegate.exclusions(exclusions); + } + + @Override + public MavenDependencyResolver exclusions(Collection exclusions) { + return delegate.exclusions(exclusions); + } + + @Override + public Stack getDependencies() { + return delegate.getDependencies(); + } + + @Override + public Map getPomInternalDependencyManagement() { + return delegate.getPomInternalDependencyManagement(); + } + + @Override + public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { + return delegate.includeDependenciesFromPom(path); + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + + @Override + public MavenDependencyResolver loadDependenciesFromPom(String path) throws ResolutionException { + return delegate.loadDependenciesFromPom(path); + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + + @Override + public MavenDependencyResolver loadDependenciesFromPom(String path, MavenResolutionFilter filter) + throws ResolutionException { + return delegate.loadDependenciesFromPom(path, filter); + } + + @Override + public MavenDependencyResolver useCentralRepo(final boolean useCentral) { + return delegate.useCentralRepo(useCentral); + } + + @Override + public MavenDependencyResolver goOffline() { + return delegate.goOffline(); + } + + } + + static class MavenArtifactsBuilderImpl implements MavenDependencyResolverInternal { + private final MavenDependencyResolverInternal delegate; + + private int size; + + MavenArtifactsBuilderImpl(final MavenDependencyResolverInternal delegate, final String... coordinates) { + assert delegate != null : "Delegate must be specified"; + this.delegate = delegate; + + this.size = coordinates.length; + + for (String coords : coordinates) { + coords = MavenConverter.resolveArtifactVersion(delegate.getPomInternalDependencyManagement(), coords); + MavenDependency dependency = new MavenDependencyImpl(coords); + delegate.getDependencies().push(dependency); + } + } + + /** + * {@inheritDoc} + * + * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#optional(boolean) + */ + + @Override + public MavenDependencyResolver optional(boolean optional) { + List workplace = new ArrayList(); + + int i; + for (i = 0; i < size; i++) { + MavenDependency dependency = delegate.getDependencies().pop(); + workplace.add(dependency.setOptional(optional)); + } + + for (; i > 0; i--) { + delegate.getDependencies().push(workplace.get(i - 1)); + } + + return this; + } + + /** + * {@inheritDoc} + * + * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#scope(java.lang.String) + */ + + @Override + public MavenDependencyResolver scope(String scope) { + List workplace = new ArrayList(); + + int i; + for (i = 0; i < size; i++) { + MavenDependency dependency = delegate.getDependencies().pop(); + workplace.add(dependency.setScope(scope)); + } + + for (; i > 0; i--) { + delegate.getDependencies().push(workplace.get(i - 1)); + } + + return this; + } + + /** + * {@inheritDoc} + * + * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver#exclusions(java.lang.String[]) + */ + + @Override + public MavenDependencyResolver exclusions(String... coordinates) { + List workplace = new ArrayList(); + + int i; + for (i = 0; i < size; i++) { + MavenDependency dependency = delegate.getDependencies().pop(); + workplace.add(dependency.addExclusions(coordinates)); + } + + for (; i > 0; i--) { + delegate.getDependencies().push(workplace.get(i - 1)); + } + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.impl.MavenDependencies. MavenArtifactBuilder#exclusions(java.util.Collection) + */ + + @Override + public MavenDependencyResolver exclusions(Collection coordinates) { + List workplace = new ArrayList(); + + int i; + for (i = 0; i < size; i++) { + MavenDependency dependency = delegate.getDependencies().pop(); + workplace.add(dependency.addExclusions(coordinates.toArray(new String[0]))); + } + + for (; i > 0; i--) { + delegate.getDependencies().push(workplace.get(i - 1)); + } + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.dependencies.impl.MavenDependencies. + * MavenArtifactBuilder#exclusion(org.sonatype.aether.graph.Exclusion) + */ + + @Override + public MavenDependencyResolver exclusion(String exclusion) { + List workplace = new ArrayList(); + + int i; + for (i = 0; i < size; i++) { + MavenDependency dependency = delegate.getDependencies().pop(); + workplace.add(dependency.addExclusions(exclusion)); + } + + for (; i > 0; i--) { + delegate.getDependencies().push(workplace.get(i - 1)); + } + + return this; + } + + @Override + public int hashCode() { + return delegate.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return delegate.equals(obj); + } + + @Override + public MavenDependencyResolver configureFrom(String path) { + return delegate.configureFrom(path); + } + + @Override + public MavenDependencyResolver loadMetadataFromPom(String path) throws ResolutionException { + return delegate.loadMetadataFromPom(path); + } + + /** + * @deprecated please use {@link #loadMetadataFromPom(String)} instead + */ + + @Override + public MavenDependencyResolver loadReposFromPom(String path) throws ResolutionException { + return delegate.loadReposFromPom(path); + } + + @Override + public MavenDependencyResolver artifact(String coordinates) throws ResolutionException { + return delegate.artifact(coordinates); + } + + @Override + public MavenDependencyResolver artifacts(String... coordinates) throws ResolutionException { + return delegate.artifacts(coordinates); + } + + @Override + public File[] resolveAsFiles() throws ResolutionException { + return delegate.resolveAsFiles(); + } + + @Override + public File[] resolveAsFiles(MavenResolutionFilter filter) throws ResolutionException { + return delegate.resolveAsFiles(filter); + } + + @Override + public String toString() { + return delegate.toString(); + } + + @Override + public Collection resolveAs(Class archiveView) + throws ResolutionException { + return delegate.resolveAs(archiveView); + } + + @Override + public Collection resolveAs(Class archiveView, + MavenResolutionFilter filter) throws ResolutionException { + return delegate.resolveAs(archiveView, filter); + } + + @Override + public Stack getDependencies() { + return delegate.getDependencies(); + } + + @Override + public Map getPomInternalDependencyManagement() { + return delegate.getPomInternalDependencyManagement(); + } + + @Override + public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { + return delegate.includeDependenciesFromPom(path); + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + @Override + public MavenDependencyResolver loadDependenciesFromPom(String path) throws ResolutionException { + return delegate.loadDependenciesFromPom(path); + } + + /** + * @deprecated please use {@link #includeDependenciesFromPom(String)} instead + */ + @Override + public MavenDependencyResolver loadDependenciesFromPom(String path, MavenResolutionFilter filter) + throws ResolutionException { + return delegate.loadDependenciesFromPom(path, filter); + } + + @Override + public MavenDependencyResolver useCentralRepo(final boolean useCentral) { + return delegate.useCentralRepo(useCentral); + } + + @Override + public MavenDependencyResolver goOffline() { + return delegate.goOffline(); + } + + } + + @Override + public MavenDependencyResolver goOffline() { + settings.setOffline(true); + // regenerate session + this.session = system.getSession(settings); + return this; + } + + /** + * Gets a resource from the TCCL and returns its name As resource in classpath. + * + * @param resourceName is the name of the resource in the classpath + * @return the file path for resourceName @see {@link java.net.URL#getFile()} + * @throws IllegalArgumentException if resourceName doesn't exist in the classpath or privileges are not granted + */ + private String getLocalResourcePathFromResourceName(final String resourceName) { + final URL resourceUrl = SecurityActions.getResource(resourceName); + Validate.notNull(resourceUrl, resourceName + " doesn't exist or can't be accessed on classpath"); + + try { + File localResource = File.createTempFile("sw_resource", "xml"); + localResource.deleteOnExit(); + IOUtil.copyWithClose(resourceUrl.openStream(), new FileOutputStream(localResource)); + return localResource.getAbsolutePath(); + } catch (IOException e) { + throw new IllegalArgumentException("Unable to open resource name specified by " + resourceName, e); + } + } + + private String resolvePathByQualifier(String path) { + if (path.startsWith(CLASSPATH_QUALIFIER)) { + path = getLocalResourcePathFromResourceName(path.replace(CLASSPATH_QUALIFIER, "")); + } else if (path.startsWith(FILE_QUALIFIER)) { + path = path.replace(FILE_QUALIFIER, ""); + } + return path; + } } \ No newline at end of file diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenConverter.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenConverter.java index 42567ad1..23cb2762 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenConverter.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenConverter.java @@ -46,362 +46,310 @@ import org.sonatype.aether.util.artifact.DefaultArtifactType; /** - * An utility class which provides conversion between Maven and Aether objects. - * It allows creation of Aether object from different objects than Maven objects - * as well. + * An utility class which provides conversion between Maven and Aether objects. It allows creation of Aether object from + * different objects than Maven objects as well. * * @author Benjamin Bentmann * @author Karel Piwko * */ -public class MavenConverter -{ - private static final Logger log = Logger.getLogger(MavenConverter.class.getName()); - - private static final Pattern DEPENDENCY_PATTERN = Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?(:([^: ]+))?"); - - private static final int DEPENDENCY_GROUP_ID = 1; - private static final int DEPENDENCY_ARTIFACT_ID = 2; - private static final int DEPENDENCY_TYPE_ID = 4; - private static final int DEPENDENCY_CLASSIFIER_ID = 6; - private static final int DEPENDENCY_VERSION_ID = 8; - - private static final Pattern EXCLUSION_PATTERN = Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?"); - - private static final int EXCLUSION_GROUP_ID = 1; - private static final int EXCLUSION_ARTIFACT_ID = 2; - private static final int EXCLUSION_TYPE_ID = 4; - private static final int EXCLUSION_CLASSIFIER_ID = 6; - - // disable instantiation - private MavenConverter() - { - throw new AssertionError("Utility class MavenConverter cannot be instantiated."); - } - - /** - * Tries to resolve artifact version from internal dependencies from a - * fetched POM file. If no version is found, it simply returns original - * coordinates - * - * @param dependencyManagement The map including dependency information - * retrieved from the POM file - * @param coordinates The coordinates excluding the {@code version} part - * @return Either coordinates with appended {@code version} or original - * coordinates - */ - public static String resolveArtifactVersion(Map dependencyManagement, String coordinates) - { - Matcher m = DEPENDENCY_PATTERN.matcher(coordinates); - if (!m.matches()) - { - throw new ResolutionException("Bad artifact coordinates" - + ", expected format is :[:[:]][:]"); - } - - ArtifactAsKey key = new ArtifactAsKey(m.group(DEPENDENCY_GROUP_ID), m.group(DEPENDENCY_ARTIFACT_ID), - m.group(DEPENDENCY_TYPE_ID), m.group(DEPENDENCY_CLASSIFIER_ID)); - - if (m.group(DEPENDENCY_VERSION_ID) == null && dependencyManagement.containsKey(key)) - { - String version = asArtifact(dependencyManagement.get(key).getCoordinates()).getVersion(); - log.fine("Resolved version " + version + " from the POM file for the artifact: " + coordinates); - coordinates = coordinates + ":" + version; - } - - return coordinates; - } - - public static Dependency asDependency(MavenDependency dependency) - { - return new Dependency(asArtifact(dependency.getCoordinates()), dependency.getScope(), dependency.isOptional(), - asExclusions(Arrays.asList(dependency.getExclusions()))); - } - - public static List asDependencies(List dependencies) - { - List list = new ArrayList(dependencies.size()); - for (MavenDependency d : dependencies) - { - list.add(asDependency(d)); - } - - return list; - } - - public static Artifact asArtifact(String coordinates) throws ResolutionException - { - try - { - return new DefaultArtifact(coordinates); - } - catch (IllegalArgumentException e) - { - throw new ResolutionException( - "Unable to create artifact from coordinates " - + coordinates - + ", " - + "they are either invalid or version information was not specified in loaded POM file (maybe the POM file wasn't load at all)", - e); - } - } - - /** - * Converts string coordinates to Aether exclusion object - * - * @param coordinates Coordinates specified in the format specified in the - * format {@code :[:[:]]}, an - * empty string or {@code *} will match all exclusions, you can - * pass an {@code *} instead of any part of the coordinates to - * match all possible values - * @return Exclusion object based on the coordinates - * @throws ResolutionException If coordinates cannot be converted - */ - public static Exclusion asExclusion(String coordinates) - { - Validate.notNull(coordinates, "Exclusion string must not be null"); - - if (coordinates.length() == 0 || coordinates.equals("*")) - { - return new Exclusion("*", "*", "*", "*"); - } - - Matcher m = EXCLUSION_PATTERN.matcher(coordinates); - if (!m.matches()) - { - throw new ResolutionException("Bad exclusion coordinates" - + ", expected format is :[:[:]]"); - } - - String group = m.group(EXCLUSION_GROUP_ID); - String artifact = m.group(EXCLUSION_ARTIFACT_ID); - String type = m.group(EXCLUSION_TYPE_ID); - String classifier = m.group(EXCLUSION_CLASSIFIER_ID); - - group = (group == null || group.length() == 0) ? "*" : group; - artifact = (artifact == null || artifact.length() == 0) ? "*" : artifact; - type = (type == null || type.length() == 0) ? "*" : type; - classifier = (classifier == null || classifier.length() == 0) ? "*" : classifier; - - return new Exclusion(group, artifact, classifier, type); - } - - /** - * Converts a collection of string coordinates to Aether exclusions objects - * - * @param coordinates A collection of coordinates specified in the format - * specified in the format {@code :[:[:]]} - * @return List of Exclusion objects based on the coordinates - * @throws ResolutionException If coordinates cannot be converted - */ - public static List asExclusions(Collection coordinates) - { - List list = new ArrayList(coordinates.size()); - for (String coords : coordinates) - { - list.add(asExclusion(coords)); - } - return list; - } - - public static String fromExclusion(org.apache.maven.model.Exclusion exclusion) - { - StringBuilder sb = new StringBuilder(); - sb.append(exclusion.getGroupId()).append(":"); - sb.append(exclusion.getArtifactId()); - - return sb.toString(); - } - - public static String fromExclusion(Exclusion exclusion) - { - StringBuilder sb = new StringBuilder(); - sb.append(exclusion.getGroupId()).append(":"); - sb.append(exclusion.getArtifactId()); - - String type = exclusion.getExtension(); - if (type != null && type.length() != 0) - { - sb.append(":").append(type); - } - - String classifier = exclusion.getClassifier(); - if (classifier != null && classifier.length() != 0) - { - sb.append(":").append(classifier); - } - - return sb.toString(); - } - - public static Collection fromExclusions(Collection exclusions) - { - List list = new ArrayList(exclusions.size()); - for (Exclusion e : exclusions) - { - list.add(fromExclusion(e)); - } - return list; - } - - public static String fromArtifact(Artifact artifact) - { - StringBuilder sb = new StringBuilder(); - sb.append(artifact.getGroupId()).append(":"); - sb.append(artifact.getArtifactId()).append(":"); - - String extension = artifact.getExtension(); - sb.append(extension.length() == 0 ? "jar" : extension).append(":"); - String classifier = artifact.getClassifier(); - if (classifier.length() != 0) - { - sb.append(classifier).append(":"); - } - sb.append(artifact.getVersion()); - - return sb.toString(); - } - - public static MavenDependency fromDependency(Dependency dependency) - { - MavenDependency result = new MavenDependencyImpl(fromArtifact(dependency.getArtifact())); - result.setOptional(dependency.isOptional()); - result.setScope(dependency.getScope()); - result.addExclusions(fromExclusions(dependency.getExclusions()).toArray(new String[0])); - return result; - } - - /** - * Converts Maven {@link org.apache.maven.model.Dependency} to Aether {@link org.sonatype.aether.graph.Dependency} - * - * @param dependency the Maven dependency to be converted - * @param registry the Artifact type catalog to determine common artifact - * properties - * @return Equivalent Aether dependency - */ - public static MavenDependency fromDependency(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry registry) - { - ArtifactType stereotype = registry.get(dependency.getType()); - if (stereotype == null) - { - stereotype = new DefaultArtifactType(dependency.getType()); - } - - boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0; - - Map props = null; - if (system) - { - props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath()); - } - - Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), - null, dependency.getVersion(), props, stereotype); - - List exclusions = new ArrayList(); - for (org.apache.maven.model.Exclusion e : dependency.getExclusions()) - { - exclusions.add(fromExclusion(e)); - } - - MavenDependency result = new MavenDependencyImpl(fromArtifact(artifact)); - result.setOptional(dependency.isOptional()); - result.setScope(dependency.getScope()); - result.addExclusions(exclusions.toArray(new String[0])); - return result; - } - - /** - * Converts Maven {@link Repository} to Aether {@link RemoteRepository} - * - * @param repository the Maven repository to be converted - * @return Equivalent remote repository - */ - public static RemoteRepository asRemoteRepository(org.apache.maven.model.Repository repository) - { - - return new RemoteRepository().setId(repository.getId()) - .setContentType(repository.getLayout()) - .setUrl(repository.getUrl()) - .setPolicy(true, asRepositoryPolicy(repository.getSnapshots())) - .setPolicy(false, asRepositoryPolicy(repository.getReleases())); - } - - /** - * Converts Maven {@link Repository} to Aether {@link RemoteRepository} - * - * @param repository the Maven repository to be converted - * @return Equivalent remote repository - */ - public static RemoteRepository asRemoteRepository(org.apache.maven.settings.Repository repository) - { - return new RemoteRepository().setId(repository.getId()) - .setContentType(repository.getLayout()) - .setUrl(repository.getUrl()) - .setPolicy(true, asRepositoryPolicy(repository.getSnapshots())) - .setPolicy(false, asRepositoryPolicy(repository.getReleases())); - } - - /** - * Converts Maven Proxy to Aether Proxy - * - * @param proxy the Maven proxy to be converted - * @return Aether proxy equivalent - */ - public static Proxy asProxy(org.apache.maven.settings.Proxy proxy) - { - Proxy aetherProxy = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), null); - if (proxy.getUsername() != null || proxy.getPassword() != null) - { - aetherProxy.setAuthentication(new Authentication(proxy.getUsername(), proxy.getPassword())); - } - return aetherProxy; - } - - // converts repository policy - private static RepositoryPolicy asRepositoryPolicy(org.apache.maven.model.RepositoryPolicy policy) - { - boolean enabled = true; - String checksums = RepositoryPolicy.CHECKSUM_POLICY_WARN; - String updates = RepositoryPolicy.UPDATE_POLICY_DAILY; - - if (policy != null) - { - enabled = policy.isEnabled(); - if (policy.getUpdatePolicy() != null) - { - updates = policy.getUpdatePolicy(); - } - if (policy.getChecksumPolicy() != null) - { - checksums = policy.getChecksumPolicy(); - } - } - - return new RepositoryPolicy(enabled, updates, checksums); - } - - // converts repository policy - private static RepositoryPolicy asRepositoryPolicy(org.apache.maven.settings.RepositoryPolicy policy) - { - boolean enabled = true; - String checksums = RepositoryPolicy.CHECKSUM_POLICY_WARN; - String updates = RepositoryPolicy.UPDATE_POLICY_DAILY; - - if (policy != null) - { - enabled = policy.isEnabled(); - if (policy.getUpdatePolicy() != null) - { - updates = policy.getUpdatePolicy(); - } - if (policy.getChecksumPolicy() != null) - { - checksums = policy.getChecksumPolicy(); - } - } - - return new RepositoryPolicy(enabled, updates, checksums); - } +public class MavenConverter { + + private static final Logger log = Logger.getLogger(MavenConverter.class.getName()); + + private static final Pattern DEPENDENCY_PATTERN = Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?(:([^: ]+))?"); + + private static final int DEPENDENCY_GROUP_ID = 1; + private static final int DEPENDENCY_ARTIFACT_ID = 2; + private static final int DEPENDENCY_TYPE_ID = 4; + private static final int DEPENDENCY_CLASSIFIER_ID = 6; + private static final int DEPENDENCY_VERSION_ID = 8; + + private static final Pattern EXCLUSION_PATTERN = Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?"); + + private static final int EXCLUSION_GROUP_ID = 1; + private static final int EXCLUSION_ARTIFACT_ID = 2; + private static final int EXCLUSION_TYPE_ID = 4; + private static final int EXCLUSION_CLASSIFIER_ID = 6; + + // disable instantiation + private MavenConverter() { + throw new AssertionError("Utility class MavenConverter cannot be instantiated."); + } + + /** + * Tries to resolve artifact version from internal dependencies from a fetched POM file. If no version is found, it simply + * returns original coordinates + * + * @param dependencyManagement The map including dependency information retrieved from the POM file + * @param coordinates The coordinates excluding the {@code version} part + * @return Either coordinates with appended {@code version} or original coordinates + */ + public static String resolveArtifactVersion(Map dependencyManagement, String coordinates) { + Matcher m = DEPENDENCY_PATTERN.matcher(coordinates); + if (!m.matches()) { + throw new ResolutionException("Bad artifact coordinates" + + ", expected format is :[:[:]][:]"); + } + + ArtifactAsKey key = new ArtifactAsKey(m.group(DEPENDENCY_GROUP_ID), m.group(DEPENDENCY_ARTIFACT_ID), + m.group(DEPENDENCY_TYPE_ID), m.group(DEPENDENCY_CLASSIFIER_ID)); + + if (m.group(DEPENDENCY_VERSION_ID) == null && dependencyManagement.containsKey(key)) { + String version = asArtifact(dependencyManagement.get(key).getCoordinates()).getVersion(); + log.fine("Resolved version " + version + " from the POM file for the artifact: " + coordinates); + coordinates = coordinates + ":" + version; + } + + return coordinates; + } + + public static Dependency asDependency(MavenDependency dependency) { + return new Dependency(asArtifact(dependency.getCoordinates()), dependency.getScope(), dependency.isOptional(), + asExclusions(Arrays.asList(dependency.getExclusions()))); + } + + public static List asDependencies(List dependencies) { + List list = new ArrayList(dependencies.size()); + for (MavenDependency d : dependencies) { + list.add(asDependency(d)); + } + + return list; + } + + public static Artifact asArtifact(String coordinates) throws ResolutionException { + try { + return new DefaultArtifact(coordinates); + } catch (IllegalArgumentException e) { + throw new ResolutionException( + "Unable to create artifact from coordinates " + + coordinates + + ", " + + "they are either invalid or version information was not specified in loaded POM file (maybe the POM file wasn't load at all)", + e); + } + } + + /** + * Converts string coordinates to Aether exclusion object + * + * @param coordinates Coordinates specified in the format specified in the format + * {@code :[:[:]]}, an empty string or {@code *} will match all + * exclusions, you can pass an {@code *} instead of any part of the coordinates to match all possible values + * @return Exclusion object based on the coordinates + * @throws ResolutionException If coordinates cannot be converted + */ + public static Exclusion asExclusion(String coordinates) { + Validate.notNull(coordinates, "Exclusion string must not be null"); + + if (coordinates.length() == 0 || coordinates.equals("*")) { + return new Exclusion("*", "*", "*", "*"); + } + + Matcher m = EXCLUSION_PATTERN.matcher(coordinates); + if (!m.matches()) { + throw new ResolutionException("Bad exclusion coordinates" + + ", expected format is :[:[:]]"); + } + + String group = m.group(EXCLUSION_GROUP_ID); + String artifact = m.group(EXCLUSION_ARTIFACT_ID); + String type = m.group(EXCLUSION_TYPE_ID); + String classifier = m.group(EXCLUSION_CLASSIFIER_ID); + + group = (group == null || group.length() == 0) ? "*" : group; + artifact = (artifact == null || artifact.length() == 0) ? "*" : artifact; + type = (type == null || type.length() == 0) ? "*" : type; + classifier = (classifier == null || classifier.length() == 0) ? "*" : classifier; + + return new Exclusion(group, artifact, classifier, type); + } + + /** + * Converts a collection of string coordinates to Aether exclusions objects + * + * @param coordinates A collection of coordinates specified in the format specified in the format + * {@code :[:[:]]} + * @return List of Exclusion objects based on the coordinates + * @throws ResolutionException If coordinates cannot be converted + */ + public static List asExclusions(Collection coordinates) { + List list = new ArrayList(coordinates.size()); + for (String coords : coordinates) { + list.add(asExclusion(coords)); + } + return list; + } + + public static String fromExclusion(org.apache.maven.model.Exclusion exclusion) { + StringBuilder sb = new StringBuilder(); + sb.append(exclusion.getGroupId()).append(":"); + sb.append(exclusion.getArtifactId()); + + return sb.toString(); + } + + public static String fromExclusion(Exclusion exclusion) { + StringBuilder sb = new StringBuilder(); + sb.append(exclusion.getGroupId()).append(":"); + sb.append(exclusion.getArtifactId()); + + String type = exclusion.getExtension(); + if (type != null && type.length() != 0) { + sb.append(":").append(type); + } + + String classifier = exclusion.getClassifier(); + if (classifier != null && classifier.length() != 0) { + sb.append(":").append(classifier); + } + + return sb.toString(); + } + + public static Collection fromExclusions(Collection exclusions) { + List list = new ArrayList(exclusions.size()); + for (Exclusion e : exclusions) { + list.add(fromExclusion(e)); + } + return list; + } + + public static String fromArtifact(Artifact artifact) { + StringBuilder sb = new StringBuilder(); + sb.append(artifact.getGroupId()).append(":"); + sb.append(artifact.getArtifactId()).append(":"); + + String extension = artifact.getExtension(); + sb.append(extension.length() == 0 ? "jar" : extension).append(":"); + String classifier = artifact.getClassifier(); + if (classifier.length() != 0) { + sb.append(classifier).append(":"); + } + sb.append(artifact.getVersion()); + + return sb.toString(); + } + + public static MavenDependency fromDependency(Dependency dependency) { + MavenDependency result = new MavenDependencyImpl(fromArtifact(dependency.getArtifact())); + result.setOptional(dependency.isOptional()); + result.setScope(dependency.getScope()); + result.addExclusions(fromExclusions(dependency.getExclusions()).toArray(new String[0])); + return result; + } + + /** + * Converts Maven {@link org.apache.maven.model.Dependency} to Aether {@link org.sonatype.aether.graph.Dependency} + * + * @param dependency the Maven dependency to be converted + * @param registry the Artifact type catalog to determine common artifact properties + * @return Equivalent Aether dependency + */ + public static MavenDependency fromDependency(org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry registry) { + ArtifactType stereotype = registry.get(dependency.getType()); + if (stereotype == null) { + stereotype = new DefaultArtifactType(dependency.getType()); + } + + boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0; + + Map props = null; + if (system) { + props = Collections.singletonMap(ArtifactProperties.LOCAL_PATH, dependency.getSystemPath()); + } + + Artifact artifact = new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), + dependency.getClassifier(), null, dependency.getVersion(), props, stereotype); + + List exclusions = new ArrayList(); + for (org.apache.maven.model.Exclusion e : dependency.getExclusions()) { + exclusions.add(fromExclusion(e)); + } + + MavenDependency result = new MavenDependencyImpl(fromArtifact(artifact)); + result.setOptional(dependency.isOptional()); + result.setScope(dependency.getScope()); + result.addExclusions(exclusions.toArray(new String[0])); + return result; + } + + /** + * Converts Maven {@link Repository} to Aether {@link RemoteRepository} + * + * @param repository the Maven repository to be converted + * @return Equivalent remote repository + */ + public static RemoteRepository asRemoteRepository(org.apache.maven.model.Repository repository) { + + return new RemoteRepository().setId(repository.getId()).setContentType(repository.getLayout()) + .setUrl(repository.getUrl()).setPolicy(true, asRepositoryPolicy(repository.getSnapshots())) + .setPolicy(false, asRepositoryPolicy(repository.getReleases())); + } + + /** + * Converts Maven {@link Repository} to Aether {@link RemoteRepository} + * + * @param repository the Maven repository to be converted + * @return Equivalent remote repository + */ + public static RemoteRepository asRemoteRepository(org.apache.maven.settings.Repository repository) { + return new RemoteRepository().setId(repository.getId()).setContentType(repository.getLayout()) + .setUrl(repository.getUrl()).setPolicy(true, asRepositoryPolicy(repository.getSnapshots())) + .setPolicy(false, asRepositoryPolicy(repository.getReleases())); + } + + /** + * Converts Maven Proxy to Aether Proxy + * + * @param proxy the Maven proxy to be converted + * @return Aether proxy equivalent + */ + public static Proxy asProxy(org.apache.maven.settings.Proxy proxy) { + Proxy aetherProxy = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), null); + if (proxy.getUsername() != null || proxy.getPassword() != null) { + aetherProxy.setAuthentication(new Authentication(proxy.getUsername(), proxy.getPassword())); + } + return aetherProxy; + } + + // converts repository policy + private static RepositoryPolicy asRepositoryPolicy(org.apache.maven.model.RepositoryPolicy policy) { + boolean enabled = true; + String checksums = RepositoryPolicy.CHECKSUM_POLICY_WARN; + String updates = RepositoryPolicy.UPDATE_POLICY_DAILY; + + if (policy != null) { + enabled = policy.isEnabled(); + if (policy.getUpdatePolicy() != null) { + updates = policy.getUpdatePolicy(); + } + if (policy.getChecksumPolicy() != null) { + checksums = policy.getChecksumPolicy(); + } + } + + return new RepositoryPolicy(enabled, updates, checksums); + } + + // converts repository policy + private static RepositoryPolicy asRepositoryPolicy(org.apache.maven.settings.RepositoryPolicy policy) { + boolean enabled = true; + String checksums = RepositoryPolicy.CHECKSUM_POLICY_WARN; + String updates = RepositoryPolicy.UPDATE_POLICY_DAILY; + + if (policy != null) { + enabled = policy.isEnabled(); + if (policy.getUpdatePolicy() != null) { + updates = policy.getUpdatePolicy(); + } + if (policy.getChecksumPolicy() != null) { + checksums = policy.getChecksumPolicy(); + } + } + + return new RepositoryPolicy(enabled, updates, checksums); + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyImpl.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyImpl.java index 82b412e8..cfd03d85 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyImpl.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyImpl.java @@ -26,90 +26,78 @@ * @author (); - } - - @Override - public MavenDependency setCoordinates(String coordinates) - { - this.coordinates = coordinates; - return this; - } - - @Override - public String getScope() - { - return scope; - } - - @Override - public MavenDependency setScope(String scope) - { - this.scope = scope; - return this; - } - - @Override - public boolean isOptional() - { - return optional; - } - - @Override - public MavenDependency setOptional(boolean optional) - { - this.optional = optional; - return this; - } - - @Override - public String[] getExclusions() - { - return exclusions.toArray(new String[0]); - } - - @Override - public String getCoordinates() - { - return coordinates; - } - - @Override - public MavenDependency addExclusions(String... exclusions) - { - if (exclusions.length == 0) - { - return this; - } - - this.exclusions.addAll(Arrays.asList(exclusions)); - return this; - } - - /* - * (non-Javadoc) - * - * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependency#hasSameArtifactAs(org.jboss.shrinkwrap.resolver.api.maven. - * MavenDependency) - */ - @Override - public boolean hasSameArtifactAs(MavenDependency other) - { - return MavenConverter.asArtifact(getCoordinates()).equals(MavenConverter.asArtifact(other.getCoordinates())); - } +public class MavenDependencyImpl implements MavenDependency { + + private String coordinates; + private String scope; + private boolean optional; + + private List exclusions; + + public MavenDependencyImpl(String coordinates) { + this.coordinates = coordinates; + this.scope = ""; + this.optional = false; + this.exclusions = new ArrayList(); + } + + @Override + public MavenDependency setCoordinates(String coordinates) { + this.coordinates = coordinates; + return this; + } + + @Override + public String getScope() { + return scope; + } + + @Override + public MavenDependency setScope(String scope) { + this.scope = scope; + return this; + } + + @Override + public boolean isOptional() { + return optional; + } + + @Override + public MavenDependency setOptional(boolean optional) { + this.optional = optional; + return this; + } + + @Override + public String[] getExclusions() { + return exclusions.toArray(new String[0]); + } + + @Override + public String getCoordinates() { + return coordinates; + } + + @Override + public MavenDependency addExclusions(String... exclusions) { + if (exclusions.length == 0) { + return this; + } + + this.exclusions.addAll(Arrays.asList(exclusions)); + return this; + } + + /* + * (non-Javadoc) + * + * @see org.jboss.shrinkwrap.resolver.api.maven.MavenDependency#hasSameArtifactAs(org.jboss.shrinkwrap.resolver.api.maven. + * MavenDependency) + */ + @Override + public boolean hasSameArtifactAs(MavenDependency other) { + return MavenConverter.asArtifact(getCoordinates()).equals(MavenConverter.asArtifact(other.getCoordinates())); + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverInternal.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverInternal.java index d819c688..2d3e276a 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverInternal.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverInternal.java @@ -23,14 +23,12 @@ import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver; /** - * Internal SPI to expose out required elements of the {@link MavenBuilderImpl} - * to inner classes for use as delegate methods - * + * Internal SPI to expose out required elements of the {@link MavenBuilderImpl} to inner classes for use as delegate methods + * * @author Andrew Lee Rubinger */ -interface MavenDependencyResolverInternal extends MavenDependencyResolver -{ - Stack getDependencies(); +interface MavenDependencyResolverInternal extends MavenDependencyResolver { + Stack getDependencies(); - Map getPomInternalDependencyManagement(); + Map getPomInternalDependencyManagement(); } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverSettings.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverSettings.java index 72615d03..0c3d21cb 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverSettings.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenDependencyResolverSettings.java @@ -3,7 +3,7 @@ * Copyright 2011, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. - * + * * Licensed 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 @@ -37,183 +37,157 @@ /** * Representation of Maven and resolver settings - * + * * @author Karel Piwko - * + * */ -public class MavenDependencyResolverSettings -{ - private static final Logger log = Logger.getLogger(MavenDependencyResolverSettings.class.getName()); - - // creates a link to Maven Central Repository - private static final RemoteRepository MAVEN_CENTRAL = new RemoteRepository("central", "default", - "http://repo1.maven.org/maven2"); - - // Maven native settings object - private Settings settings; - - // enable usage of central - private boolean useMavenCentral = true; - - private Collection modelRemoteRepositories = Collections.emptyList(); - - /** - * Creates settings with default values - */ - public MavenDependencyResolverSettings() - { - this.settings = new MavenSettingsBuilder().buildDefaultSettings(); - } - - /** - * Gets remote repositories. Collects ones activated via pom.xml, settings.xml and - * then mirrors are applied - * - * @return the effective list of repositories - */ - @SuppressWarnings("unchecked") - public List getRemoteRepositories() - { - // disable repositories if working offline - if (isOffline()) - { - return Collections.emptyList(); - } - - List actives = settings.getActiveProfiles(); - Set enhancedRepos = new LinkedHashSet(); - - for (Map.Entry profile : (Set>) settings.getProfilesAsMap().entrySet()) - { - Activation activation = profile.getValue().getActivation(); - if (actives.contains(profile.getKey()) || (activation != null && activation.isActiveByDefault())) - { - for (org.apache.maven.settings.Repository repo : profile.getValue().getRepositories()) - { - enhancedRepos.add(MavenConverter.asRemoteRepository(repo)); +public class MavenDependencyResolverSettings { + private static final Logger log = Logger.getLogger(MavenDependencyResolverSettings.class.getName()); + + // creates a link to Maven Central Repository + private static final RemoteRepository MAVEN_CENTRAL = new RemoteRepository("central", "default", + "http://repo1.maven.org/maven2"); + + // Maven native settings object + private Settings settings; + + // enable usage of central + private boolean useMavenCentral = true; + + private Collection modelRemoteRepositories = Collections.emptyList(); + + /** + * Creates settings with default values + */ + public MavenDependencyResolverSettings() { + this.settings = new MavenSettingsBuilder().buildDefaultSettings(); + } + + /** + * Gets remote repositories. Collects ones activated via pom.xml, settings.xml and then mirrors are applied + * + * @return the effective list of repositories + */ + @SuppressWarnings("unchecked") + public List getRemoteRepositories() { + // disable repositories if working offline + if (isOffline()) { + return Collections.emptyList(); + } + + List actives = settings.getActiveProfiles(); + Set enhancedRepos = new LinkedHashSet(); + + for (Map.Entry profile : (Set>) settings.getProfilesAsMap().entrySet()) { + Activation activation = profile.getValue().getActivation(); + if (actives.contains(profile.getKey()) || (activation != null && activation.isActiveByDefault())) { + for (org.apache.maven.settings.Repository repo : profile.getValue().getRepositories()) { + enhancedRepos.add(MavenConverter.asRemoteRepository(repo)); + } } - } - } - - // add repositories from model - enhancedRepos.addAll(modelRemoteRepositories); - - // add maven central if selected - if (useMavenCentral) - { - enhancedRepos.add(MAVEN_CENTRAL); - } - - if (settings.getMirrors().size() == 0) - { - return new ArrayList(enhancedRepos); - } - - // use mirrors if any to do the mirroring stuff - DefaultMirrorSelector dms = new DefaultMirrorSelector(); - // fill in mirrors - for (Mirror mirror : settings.getMirrors()) - { - // Repository manager flag is set to false - // Maven does not support specifying it in the settings.xml - dms.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); - } - - Set mirroredRepos = new LinkedHashSet(); - for (RemoteRepository repository : enhancedRepos) - { - RemoteRepository mirror = dms.getMirror(repository); - if (mirror != null) - { - mirroredRepos.add(mirror); - } - else - { - mirroredRepos.add(repository); - } - } - - return new ArrayList(mirroredRepos); - } - - /** - * Sets a list of remote repositories using a POM model - * - * @param model the POM model - */ - public void setModelRemoteRepositories(Model model) - { - List repositories = new ArrayList(); - for (Repository repository : model.getRepositories()) - { - repositories.add(MavenConverter.asRemoteRepository(repository)); - } - - this.modelRemoteRepositories = repositories; - } - - // getters and setters - - /** - * @return the settings - */ - public Settings getSettings() - { - return settings; - } - - /** - * @param settings the settings to set - */ - public void setSettings(Settings settings) - { - this.settings = settings; - } - - /** - * @return the useMavenCentral - */ - public boolean isUseMavenCentral() - { - return useMavenCentral; - } - - /** - * @param useMavenCentral the useMavenCentral to set - */ - public void setUseMavenCentral(boolean useMavenCentral) - { - this.useMavenCentral = useMavenCentral; - } - - /** - * @return the offline - */ - public boolean isOffline() - { - return settings.isOffline(); - } - - /** - * @param offline the offline to set - */ - public void setOffline(boolean offline) - { - String goOffline = SecurityActions.getProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE); - if (goOffline != null) - { - this.settings.setOffline(Boolean.valueOf(goOffline)); - if (log.isLoggable(Level.FINER)) - { - log.finer("Offline settings is set via a system property. The new offline flag value is: " - + settings.isOffline()); - } - - } - else - { - this.settings.setOffline(offline); - } - } + } + + // add repositories from model + enhancedRepos.addAll(modelRemoteRepositories); + + // add maven central if selected + if (useMavenCentral) { + enhancedRepos.add(MAVEN_CENTRAL); + } + + if (settings.getMirrors().size() == 0) { + return new ArrayList(enhancedRepos); + } + + // use mirrors if any to do the mirroring stuff + DefaultMirrorSelector dms = new DefaultMirrorSelector(); + // fill in mirrors + for (Mirror mirror : settings.getMirrors()) { + // Repository manager flag is set to false + // Maven does not support specifying it in the settings.xml + dms.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), + mirror.getMirrorOfLayouts()); + } + + Set mirroredRepos = new LinkedHashSet(); + for (RemoteRepository repository : enhancedRepos) { + RemoteRepository mirror = dms.getMirror(repository); + if (mirror != null) { + mirroredRepos.add(mirror); + } else { + mirroredRepos.add(repository); + } + } + + return new ArrayList(mirroredRepos); + } + + /** + * Sets a list of remote repositories using a POM model + * + * @param model the POM model + */ + public void setModelRemoteRepositories(Model model) { + List repositories = new ArrayList(); + for (Repository repository : model.getRepositories()) { + repositories.add(MavenConverter.asRemoteRepository(repository)); + } + + this.modelRemoteRepositories = repositories; + } + + // getters and setters + + /** + * @return the settings + */ + public Settings getSettings() { + return settings; + } + + /** + * @param settings the settings to set + */ + public void setSettings(Settings settings) { + this.settings = settings; + } + + /** + * @return the useMavenCentral + */ + public boolean isUseMavenCentral() { + return useMavenCentral; + } + + /** + * @param useMavenCentral the useMavenCentral to set + */ + public void setUseMavenCentral(boolean useMavenCentral) { + this.useMavenCentral = useMavenCentral; + } + + /** + * @return the offline + */ + public boolean isOffline() { + return settings.isOffline(); + } + + /** + * @param offline the offline to set + */ + public void setOffline(boolean offline) { + String goOffline = SecurityActions.getProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE); + if (goOffline != null) { + this.settings.setOffline(Boolean.valueOf(goOffline)); + if (log.isLoggable(Level.FINER)) { + log.finer("Offline settings is set via a system property. The new offline flag value is: " + + settings.isOffline()); + } + + } else { + this.settings.setOffline(offline); + } + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenManagerBuilder.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenManagerBuilder.java index 463270d0..8acab88b 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenManagerBuilder.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenManagerBuilder.java @@ -37,112 +37,105 @@ * @author Karel Piwko * */ -public class MavenManagerBuilder -{ - private MavenDependencyResolverSettings settings; - private RepositorySystem system; - - private static enum LocalRepositoryType - { - SIMPLE("simple"), - ENHANCED("enhanced"); - - private final String type; - - private LocalRepositoryType(String type) - { - this.type = type; - } - - public String contentType() - { - return type; - } - } - - /** - * Creates a builder which has access to Maven system and current settings - * - * @param system the Maven system - * @param settings Maven and resolver settings - */ - public MavenManagerBuilder(RepositorySystem system, MavenDependencyResolverSettings settings) - { - this.system = system; - this.settings = settings; - } - - /** - * Gets the transfer listener - * - * @return the listener - */ - public TransferListener transferListerer() - { - return new LogTransferListerer(); - } - - /** - * Get the repository listener - * - * @return the listener - */ - public RepositoryListener repositoryListener() - { - return new LogRepositoryListener(); - } - - /** - * Gets manager for local repository - * - * @return the manager - */ - public LocalRepositoryManager localRepositoryManager() - { - - String localRepositoryPath = settings.getSettings().getLocalRepository(); - Validate.notNullOrEmpty(localRepositoryPath, "Path to a local repository must be defined"); - - LocalRepositoryType repositoryType = settings.isOffline() ? LocalRepositoryType.SIMPLE : LocalRepositoryType.ENHANCED; - return system.newLocalRepositoryManager(new LocalRepository(new File(localRepositoryPath), repositoryType.contentType())); - } - - /** - * Gets mirror selector - * - * @return the selector - */ - public MirrorSelector mirrorSelector() - { - - DefaultMirrorSelector dms = new DefaultMirrorSelector(); - - // fill in mirrors - for (Mirror mirror : settings.getSettings().getMirrors()) - { - // Repository manager flag is set to false - // Maven does not support specifying it in the settings.xml - dms.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); - } - - return dms; - } - - /** - * Gets proxy selector - * - * @return the selector - */ - public ProxySelector proxySelector() - { - DefaultProxySelector dps = new DefaultProxySelector(); - - for (Proxy proxy : settings.getSettings().getProxies()) - { - dps.add(MavenConverter.asProxy(proxy), proxy.getNonProxyHosts()); - } - - return dps; - } +public class MavenManagerBuilder { + private MavenDependencyResolverSettings settings; + private RepositorySystem system; + + private static enum LocalRepositoryType { + // does not allow connection to a remote repository + SIMPLE("simple"), + + // connects to a remote repository if required + ENHANCED("enhanced"); + + private final String type; + + private LocalRepositoryType(String type) { + this.type = type; + } + + public String contentType() { + return type; + } + } + + /** + * Creates a builder which has access to Maven system and current settings + * + * @param system the Maven system + * @param settings Maven and resolver settings + */ + public MavenManagerBuilder(RepositorySystem system, MavenDependencyResolverSettings settings) { + this.system = system; + this.settings = settings; + } + + /** + * Gets the transfer listener + * + * @return the listener + */ + public TransferListener transferListerer() { + return new LogTransferListerer(); + } + + /** + * Get the repository listener + * + * @return the listener + */ + public RepositoryListener repositoryListener() { + return new LogRepositoryListener(); + } + + /** + * Gets manager for local repository + * + * @return the manager + */ + public LocalRepositoryManager localRepositoryManager() { + + String localRepositoryPath = settings.getSettings().getLocalRepository(); + Validate.notNullOrEmpty(localRepositoryPath, "Path to a local repository must be defined"); + + LocalRepositoryType repositoryType = settings.isOffline() ? LocalRepositoryType.SIMPLE : LocalRepositoryType.ENHANCED; + return system + .newLocalRepositoryManager(new LocalRepository(new File(localRepositoryPath), repositoryType.contentType())); + } + + /** + * Gets mirror selector + * + * @return the selector + */ + public MirrorSelector mirrorSelector() { + + DefaultMirrorSelector dms = new DefaultMirrorSelector(); + + // fill in mirrors + for (Mirror mirror : settings.getSettings().getMirrors()) { + // Repository manager flag is set to false + // Maven does not support specifying it in the settings.xml + dms.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), + mirror.getMirrorOfLayouts()); + } + + return dms; + } + + /** + * Gets proxy selector + * + * @return the selector + */ + public ProxySelector proxySelector() { + DefaultProxySelector dps = new DefaultProxySelector(); + + for (Proxy proxy : settings.getSettings().getProxies()) { + dps.add(MavenConverter.asProxy(proxy), proxy.getNonProxyHosts()); + } + + return dps; + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenModelResolver.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenModelResolver.java index ae33c080..ed92f44f 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenModelResolver.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenModelResolver.java @@ -39,116 +39,104 @@ /** * Resolves an artifact even from remote repository during resolution of the model. * - * The repositories are added to the resolution chain as found during processing - * of the POM file. Repository is added only if there is no other repository with - * same id already defined. + * The repositories are added to the resolution chain as found during processing of the POM file. Repository is added only if + * there is no other repository with same id already defined. * * @author Karel Piwko */ -public class MavenModelResolver implements ModelResolver -{ - private List repositories; - private Set repositoryIds; - - private MavenRepositorySystem system; - private RepositorySystemSession session; - - /** - * Creates a new Maven repository resolver. This resolver uses service available to Maven - * to create an artifact resolution chain - * - * @param system the Maven based implementation of the {@link RepositorySystem} - * @param settings Maven and resolver settings - */ - public MavenModelResolver(MavenRepositorySystem system, MavenDependencyResolverSettings settings) - { - this(system, settings, system.getSession(settings)); - } - - /** - * Creates a new Maven repository resolver. This resolver uses service available to Maven - * to create an artifact resolution chain - * - * @param system the Maven based implementation of the {@link RepositorySystem} - * @param settings Maven and resolver settings - * @param session the current Maven execution session - */ - public MavenModelResolver(MavenRepositorySystem system, MavenDependencyResolverSettings settings, - RepositorySystemSession session) - { - this.system = system; - this.session = session; - this.repositories = new ArrayList(settings.getRemoteRepositories()); - this.repositoryIds = new HashSet(); - - for (RemoteRepository repository : repositories) - { - repositoryIds.add(repository.getId()); - } - - } - - // a cloning constructor - private MavenModelResolver(MavenModelResolver clone) - { - this.system = clone.system; - this.session = clone.session; - this.repositories = new ArrayList(clone.repositories); - this.repositoryIds = new HashSet(clone.repositoryIds); - } - - /* - * (non-Javadoc) - * - * @see org.apache.maven.model.resolution.ModelResolver#addRepository(org.apache.maven.model.Repository) - */ - @Override - public void addRepository(Repository repository) throws InvalidRepositoryException - { - if (repositoryIds.contains(repository.getId())) - { - return; - } - - repositoryIds.add(repository.getId()); - repositories.add(MavenConverter.asRemoteRepository(repository)); - } - - /* - * (non-Javadoc) - * - * @see org.apache.maven.model.resolution.ModelResolver#newCopy() - */ - @Override - public ModelResolver newCopy() - { - return new MavenModelResolver(this); - } - - /* - * (non-Javadoc) - * - * @see org.apache.maven.model.resolution.ModelResolver#resolveModel(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public ModelSource resolveModel(String groupId, String artifactId, String version) throws UnresolvableModelException - { - Artifact pomArtifact = new DefaultArtifact(groupId, artifactId, "", "pom", version); - try - { - ArtifactRequest request = new ArtifactRequest(pomArtifact, repositories, null); - pomArtifact = system.resolveArtifact(session, request).getArtifact(); - - } - catch (ArtifactResolutionException e) - { - throw new UnresolvableModelException("Failed to resolve POM for " + groupId + ":" + artifactId + ":" - + version + " due to " + e.getMessage(), groupId, artifactId, version, e); - } - - File pomFile = pomArtifact.getFile(); - - return new FileModelSource(pomFile); - - } +public class MavenModelResolver implements ModelResolver { + + private List repositories; + private Set repositoryIds; + + private MavenRepositorySystem system; + private RepositorySystemSession session; + + /** + * Creates a new Maven repository resolver. This resolver uses service available to Maven to create an artifact resolution + * chain + * + * @param system the Maven based implementation of the {@link RepositorySystem} + * @param settings Maven and resolver settings + */ + public MavenModelResolver(MavenRepositorySystem system, MavenDependencyResolverSettings settings) { + this(system, settings, system.getSession(settings)); + } + + /** + * Creates a new Maven repository resolver. This resolver uses service available to Maven to create an artifact resolution + * chain + * + * @param system the Maven based implementation of the {@link RepositorySystem} + * @param settings Maven and resolver settings + * @param session the current Maven execution session + */ + public MavenModelResolver(MavenRepositorySystem system, MavenDependencyResolverSettings settings, + RepositorySystemSession session) { + this.system = system; + this.session = session; + this.repositories = new ArrayList(settings.getRemoteRepositories()); + this.repositoryIds = new HashSet(); + + for (RemoteRepository repository : repositories) { + repositoryIds.add(repository.getId()); + } + + } + + // a cloning constructor + private MavenModelResolver(MavenModelResolver clone) { + this.system = clone.system; + this.session = clone.session; + this.repositories = new ArrayList(clone.repositories); + this.repositoryIds = new HashSet(clone.repositoryIds); + } + + /* + * (non-Javadoc) + * + * @see org.apache.maven.model.resolution.ModelResolver#addRepository(org.apache.maven.model.Repository) + */ + @Override + public void addRepository(Repository repository) throws InvalidRepositoryException { + if (repositoryIds.contains(repository.getId())) { + return; + } + + repositoryIds.add(repository.getId()); + repositories.add(MavenConverter.asRemoteRepository(repository)); + } + + /* + * (non-Javadoc) + * + * @see org.apache.maven.model.resolution.ModelResolver#newCopy() + */ + @Override + public ModelResolver newCopy() { + return new MavenModelResolver(this); + } + + /* + * (non-Javadoc) + * + * @see org.apache.maven.model.resolution.ModelResolver#resolveModel(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public ModelSource resolveModel(String groupId, String artifactId, String version) throws UnresolvableModelException { + Artifact pomArtifact = new DefaultArtifact(groupId, artifactId, "", "pom", version); + try { + ArtifactRequest request = new ArtifactRequest(pomArtifact, repositories, null); + pomArtifact = system.resolveArtifact(session, request).getArtifact(); + + } catch (ArtifactResolutionException e) { + throw new UnresolvableModelException("Failed to resolve POM for " + groupId + ":" + artifactId + ":" + version + + " due to " + e.getMessage(), groupId, artifactId, version, e); + } + + File pomFile = pomArtifact.getFile(); + + return new FileModelSource(pomFile); + + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenRepositorySystem.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenRepositorySystem.java index 0fdce836..abfa1537 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenRepositorySystem.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenRepositorySystem.java @@ -46,218 +46,188 @@ import org.sonatype.aether.resolution.ArtifactResult; /** - * Abstraction of the repository system for purposes of dependency resolution - * used by Maven + * Abstraction of the repository system for purposes of dependency resolution used by Maven * * @author Karel Piwko * */ -public class MavenRepositorySystem -{ - private final RepositorySystem system; - - /** - * Creates a Maven repository system - */ - public MavenRepositorySystem() - { - this.system = getRepositorySystem(); - } - - /** - * Spawns a working session from the repository system. This is used to - * as environment for execution of Maven commands - * - * @param settings A configuration of current session - */ - public RepositorySystemSession getSession(MavenDependencyResolverSettings settings) - { - MavenRepositorySystemSession session = new MavenRepositorySystemSession(); - - MavenManagerBuilder builder = new MavenManagerBuilder(system, settings); - - session.setLocalRepositoryManager(builder.localRepositoryManager()); - session.setTransferListener(builder.transferListerer()); - session.setRepositoryListener(builder.repositoryListener()); - session.setOffline(settings.isOffline()); - session.setMirrorSelector(builder.mirrorSelector()); - session.setProxySelector(builder.proxySelector()); - - return session; - } - - /** - * Gets registry of the known artifact types - * - * @param session Session which contains requested information - * @return the registry - */ - public ArtifactTypeRegistry getArtifactTypeRegistry(RepositorySystemSession session) - { - return session.getArtifactTypeRegistry(); - } - - /** - * Gets registry of the known artifact types - * - * @param settings Settings which will be used to spawn the session - * @return the registry - */ - public ArtifactTypeRegistry getArtifactTypeRegistry(MavenDependencyResolverSettings settings) - { - return getArtifactTypeRegistry((MavenRepositorySystemSession) getSession(settings)); - } - - /** - * Loads a POM file and updates settings both in current system and the - * session. Namely remote repositories are updated using the settings found - * in the POM file. - * - * @param pom The POM file which contains either settings or a reference to a - * parent POM - * @param session The session to be used to fetch possible parents - * @return The model generated from the POM file - * @throws ResolutionException If dependency resolution, such as retrieving - * an artifact parent fails - */ - public Model loadPom(File pom, MavenDependencyResolverSettings settings, RepositorySystemSession session) - throws ResolutionException - { - return loadPom(pom, settings, new MavenModelResolver(this, settings, session)); - } - - public Model loadPom(File pom, MavenDependencyResolverSettings settings, MavenModelResolver modelResolver) - throws ResolutionException - { - ModelBuildingRequest request = new DefaultModelBuildingRequest(); - request.setPomFile(pom); - request.setModelResolver(modelResolver); - - ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); - ModelBuildingResult result; - try - { - result = builder.build(request); - } - // wrap exception message - catch (ModelBuildingException e) - { - StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size()) - .append(" problems while building POM model from ").append(pom.getAbsolutePath()); - - int counter = 1; - for (ModelProblem problem : e.getProblems()) - { - sb.append(counter++).append("/ ").append(problem).append("\n"); - } - - throw new ResolutionException(sb.toString(), e); - } - - Model model = result.getEffectiveModel(); - settings.setModelRemoteRepositories(model); - return model; - - } - - /** - * Loads Maven settings from a file. Original settings are discarded. - * - * @param file The file which contains Maven settings - * @param settings Settings object to be updated - */ - public void loadSettings(File file, MavenDependencyResolverSettings settings) - { - MavenSettingsBuilder builder = new MavenSettingsBuilder(); - settings.setSettings(builder.buildSettings(file)); - // propagate offline settings - settings.setOffline(settings.getSettings().isOffline()); - } - - /** - * Resolves artifact dependencies. - * - * The {@see ArtifactResult} contains a reference to a file in Maven local - * repository. - * - * @param session The current Maven session - * @param request The request to be computed - * @param filter The filter of dependency results - * @return A collection of artifacts which have built dependency tree from {@link request} - * @throws DependencyCollectionException If a dependency could not be - * computed or collected - * @throws ArtifactResolutionException If an artifact could not be fetched - */ - public Collection resolveDependencies(RepositorySystemSession session, CollectRequest request, - MavenResolutionFilter filter) throws DependencyCollectionException, ArtifactResolutionException - { - return system.resolveDependencies(session, request, new MavenResolutionFilterWrap(filter)); - } - - /** - * Resolves an artifact - * - * @param session The current Maven session - * @param request The request to be computed - * @return The artifact - * @throws ArtifactResolutionException If the artifact could not be fetched - */ - public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) - throws ArtifactResolutionException - { - return system.resolveArtifact(session, request); - } - - /** - * Finds a current implementation of repository system. A {@link RepositorySystem} is an entry point to dependency resolution - * - * @return A repository system - */ - private RepositorySystem getRepositorySystem() - { - try - { - return new DefaultPlexusContainer().lookup(RepositorySystem.class); - } - catch (ComponentLookupException e) - { - throw new RuntimeException( - "Unable to lookup component RepositorySystem, cannot establish Aether dependency resolver.", e); - } - catch (PlexusContainerException e) - { - throw new RuntimeException( - "Unable to load RepositorySystem component by Plexus, cannot establish Aether dependency resolver.", e); - } - } +public class MavenRepositorySystem { + + private final RepositorySystem system; + + /** + * Creates a Maven repository system + */ + public MavenRepositorySystem() { + this.system = getRepositorySystem(); + } + + /** + * Spawns a working session from the repository system. This is used to as environment for execution of Maven commands + * + * @param settings A configuration of current session + */ + public RepositorySystemSession getSession(MavenDependencyResolverSettings settings) { + MavenRepositorySystemSession session = new MavenRepositorySystemSession(); + + MavenManagerBuilder builder = new MavenManagerBuilder(system, settings); + + session.setLocalRepositoryManager(builder.localRepositoryManager()); + session.setTransferListener(builder.transferListerer()); + session.setRepositoryListener(builder.repositoryListener()); + session.setOffline(settings.isOffline()); + session.setMirrorSelector(builder.mirrorSelector()); + session.setProxySelector(builder.proxySelector()); + + return session; + } + + /** + * Gets registry of the known artifact types + * + * @param session Session which contains requested information + * @return the registry + */ + public ArtifactTypeRegistry getArtifactTypeRegistry(RepositorySystemSession session) { + return session.getArtifactTypeRegistry(); + } + + /** + * Gets registry of the known artifact types + * + * @param settings Settings which will be used to spawn the session + * @return the registry + */ + public ArtifactTypeRegistry getArtifactTypeRegistry(MavenDependencyResolverSettings settings) { + return getArtifactTypeRegistry((MavenRepositorySystemSession) getSession(settings)); + } + + /** + * Loads a POM file and updates settings both in current system and the session. Namely remote repositories are updated + * using the settings found in the POM file. + * + * @param pom The POM file which contains either settings or a reference to a parent POM + * @param session The session to be used to fetch possible parents + * @return The model generated from the POM file + * @throws ResolutionException If dependency resolution, such as retrieving an artifact parent fails + */ + public Model loadPom(File pom, MavenDependencyResolverSettings settings, RepositorySystemSession session) + throws ResolutionException { + return loadPom(pom, settings, new MavenModelResolver(this, settings, session)); + } + + public Model loadPom(File pom, MavenDependencyResolverSettings settings, MavenModelResolver modelResolver) + throws ResolutionException { + ModelBuildingRequest request = new DefaultModelBuildingRequest(); + request.setPomFile(pom); + request.setModelResolver(modelResolver); + + ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); + ModelBuildingResult result; + try { + result = builder.build(request); + } + // wrap exception message + catch (ModelBuildingException e) { + StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size()) + .append(" problems while building POM model from ").append(pom.getAbsolutePath()); + + int counter = 1; + for (ModelProblem problem : e.getProblems()) { + sb.append(counter++).append("/ ").append(problem).append("\n"); + } + + throw new ResolutionException(sb.toString(), e); + } + + Model model = result.getEffectiveModel(); + settings.setModelRemoteRepositories(model); + return model; + + } + + /** + * Loads Maven settings from a file. Original settings are discarded. + * + * @param file The file which contains Maven settings + * @param settings Settings object to be updated + */ + public void loadSettings(File file, MavenDependencyResolverSettings settings) { + MavenSettingsBuilder builder = new MavenSettingsBuilder(); + settings.setSettings(builder.buildSettings(file)); + // propagate offline settings + settings.setOffline(settings.getSettings().isOffline()); + } + + /** + * Resolves artifact dependencies. + * + * The {@see ArtifactResult} contains a reference to a file in Maven local repository. + * + * @param session The current Maven session + * @param request The request to be computed + * @param filter The filter of dependency results + * @return A collection of artifacts which have built dependency tree from {@link request} + * @throws DependencyCollectionException If a dependency could not be computed or collected + * @throws ArtifactResolutionException If an artifact could not be fetched + */ + public Collection resolveDependencies(RepositorySystemSession session, CollectRequest request, + MavenResolutionFilter filter) throws DependencyCollectionException, ArtifactResolutionException { + return system.resolveDependencies(session, request, new MavenResolutionFilterWrap(filter)); + } + + /** + * Resolves an artifact + * + * @param session The current Maven session + * @param request The request to be computed + * @return The artifact + * @throws ArtifactResolutionException If the artifact could not be fetched + */ + public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) + throws ArtifactResolutionException { + return system.resolveArtifact(session, request); + } + + /** + * Finds a current implementation of repository system. A {@link RepositorySystem} is an entry point to dependency + * resolution + * + * @return A repository system + */ + private RepositorySystem getRepositorySystem() { + try { + return new DefaultPlexusContainer().lookup(RepositorySystem.class); + } catch (ComponentLookupException e) { + throw new RuntimeException( + "Unable to lookup component RepositorySystem, cannot establish Aether dependency resolver.", e); + } catch (PlexusContainerException e) { + throw new RuntimeException( + "Unable to load RepositorySystem component by Plexus, cannot establish Aether dependency resolver.", e); + } + } } -class MavenResolutionFilterWrap implements org.sonatype.aether.graph.DependencyFilter -{ - private MavenResolutionFilter delegate; - - public MavenResolutionFilterWrap(MavenResolutionFilter filter) - { - delegate = filter; - } - - /* - * (non-Javadoc) - * - * @see - * org.sonatype.aether.graph.DependencyFilter#accept(org.sonatype.aether. - * graph.DependencyNode, java.util.List) - */ - public boolean accept(DependencyNode node, List parents) - { - Dependency dependency = node.getDependency(); - if (dependency == null) - { - return false; - } - - return delegate.accept(MavenConverter.fromDependency(dependency)); - } +class MavenResolutionFilterWrap implements org.sonatype.aether.graph.DependencyFilter { + private MavenResolutionFilter delegate; + + public MavenResolutionFilterWrap(MavenResolutionFilter filter) { + delegate = filter; + } + + /* + * (non-Javadoc) + * + * @see org.sonatype.aether.graph.DependencyFilter#accept(org.sonatype.aether. graph.DependencyNode, java.util.List) + */ + public boolean accept(DependencyNode node, List parents) { + Dependency dependency = node.getDependency(); + if (dependency == null) { + return false; + } + + return delegate.accept(MavenConverter.fromDependency(dependency)); + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenSettingsBuilder.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenSettingsBuilder.java index 87310686..c2601e04 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenSettingsBuilder.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenSettingsBuilder.java @@ -33,131 +33,117 @@ * @author Karel Piwko * */ -public class MavenSettingsBuilder -{ - /** - * Sets an alternate location to Maven user settings.xml configuration - */ - public static final String ALT_USER_SETTINGS_XML_LOCATION = "org.apache.maven.user-settings"; - - /** - * Sets an alternate location of Maven global settings.xml configuration - */ - public static final String ALT_GLOBAL_SETTINGS_XML_LOCATION = "org.apache.maven.global-settings"; - - /** - * Sets Maven resolution either online or offline - */ - public static final String ALT_MAVEN_OFFLINE = "org.apache.maven.offline"; - - /** - * Sets an alternate location of Maven local repository - */ - public static final String ALT_LOCAL_REPOSITORY_LOCATION = "maven.repo.local"; - - // path to the user settings.xml - private static final String DEFAULT_USER_SETTINGS_PATH = SecurityActions.getProperty("user.home") - .concat("/.m2/settings.xml"); - - // path to the default local repository - private static final String DEFAULT_REPOSITORY_PATH = SecurityActions.getProperty("user.home").concat("/.m2/repository"); - - /** - * Loads default Maven settings from standard location or from a location specified by a property - * - * @return - */ - public Settings buildDefaultSettings() - { - SettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); - - String altUserSettings = SecurityActions.getProperty(ALT_USER_SETTINGS_XML_LOCATION); - String altGlobalSettings = SecurityActions.getProperty(ALT_GLOBAL_SETTINGS_XML_LOCATION); - - request.setUserSettingsFile(new File(DEFAULT_USER_SETTINGS_PATH)); - // set alternate files - if (altUserSettings != null && altUserSettings.length() > 0) - { - request.setUserSettingsFile(new File(altUserSettings)); - } - - if (altGlobalSettings != null && altGlobalSettings.length() > 0) - { - request.setUserSettingsFile(new File(altGlobalSettings)); - } - - return buildSettings(request); - } - - /** - * Loads Maven settings and updates session settings - * - * @param file The file which contains Maven settings - */ - public Settings buildSettings(File file) - { - Validate.notNull(file, "Settings file should not be null"); - Validate.isReadable(file.getAbsolutePath(), "Settings file '" + file.getAbsolutePath() + "' could not be read"); - SettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); - request.setUserSettingsFile(file); - - return buildSettings(request); - } - - /** - * Builds Maven settings from request. - * - * @param request The request for new settings - */ - private Settings buildSettings(SettingsBuildingRequest request) - { - SettingsBuildingResult result; - try - { - SettingsBuilder builder = new DefaultSettingsBuilderFactory().newInstance(); - result = builder.build(request); - } - catch (SettingsBuildingException e) - { - e.printStackTrace(); - throw new RuntimeException("Unable to parse Maven configuration", e); - } - - Settings settings = result.getEffectiveSettings(); - - // enrich with local repository - if (settings.getLocalRepository() == null) - { - settings = enrichWithLocalRepository(settings); - } - - return enrichWithOfflineMode(settings); - } - - // adds local repository - private Settings enrichWithLocalRepository(Settings settings) - { - String altLocalRepository = SecurityActions.getProperty(ALT_LOCAL_REPOSITORY_LOCATION); - settings.setLocalRepository(DEFAULT_REPOSITORY_PATH); - - if (altLocalRepository != null && altLocalRepository.length() > 0) - { - settings.setLocalRepository(altLocalRepository); - } - return settings; - } - - // adds offline mode from system property - private Settings enrichWithOfflineMode(Settings settings) - { - - String goOffline = SecurityActions.getProperty(ALT_MAVEN_OFFLINE); - if (goOffline != null) - { - settings.setOffline(Boolean.valueOf(goOffline)); - } - - return settings; - } +public class MavenSettingsBuilder { + /** + * Sets an alternate location to Maven user settings.xml configuration + */ + public static final String ALT_USER_SETTINGS_XML_LOCATION = "org.apache.maven.user-settings"; + + /** + * Sets an alternate location of Maven global settings.xml configuration + */ + public static final String ALT_GLOBAL_SETTINGS_XML_LOCATION = "org.apache.maven.global-settings"; + + /** + * Sets Maven resolution either online or offline + */ + public static final String ALT_MAVEN_OFFLINE = "org.apache.maven.offline"; + + /** + * Sets an alternate location of Maven local repository + */ + public static final String ALT_LOCAL_REPOSITORY_LOCATION = "maven.repo.local"; + + // path to the user settings.xml + private static final String DEFAULT_USER_SETTINGS_PATH = SecurityActions.getProperty("user.home").concat( + "/.m2/settings.xml"); + + // path to the default local repository + private static final String DEFAULT_REPOSITORY_PATH = SecurityActions.getProperty("user.home").concat("/.m2/repository"); + + /** + * Loads default Maven settings from standard location or from a location specified by a property + * + * @return + */ + public Settings buildDefaultSettings() { + SettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); + + String altUserSettings = SecurityActions.getProperty(ALT_USER_SETTINGS_XML_LOCATION); + String altGlobalSettings = SecurityActions.getProperty(ALT_GLOBAL_SETTINGS_XML_LOCATION); + + request.setUserSettingsFile(new File(DEFAULT_USER_SETTINGS_PATH)); + // set alternate files + if (altUserSettings != null && altUserSettings.length() > 0) { + request.setUserSettingsFile(new File(altUserSettings)); + } + + if (altGlobalSettings != null && altGlobalSettings.length() > 0) { + request.setUserSettingsFile(new File(altGlobalSettings)); + } + + return buildSettings(request); + } + + /** + * Loads Maven settings and updates session settings + * + * @param file The file which contains Maven settings + */ + public Settings buildSettings(File file) { + Validate.notNull(file, "Settings file should not be null"); + Validate.isReadable(file.getAbsolutePath(), "Settings file '" + file.getAbsolutePath() + "' could not be read"); + SettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); + request.setUserSettingsFile(file); + + return buildSettings(request); + } + + /** + * Builds Maven settings from request. + * + * @param request The request for new settings + */ + private Settings buildSettings(SettingsBuildingRequest request) { + SettingsBuildingResult result; + try { + SettingsBuilder builder = new DefaultSettingsBuilderFactory().newInstance(); + result = builder.build(request); + } catch (SettingsBuildingException e) { + e.printStackTrace(); + throw new RuntimeException("Unable to parse Maven configuration", e); + } + + Settings settings = result.getEffectiveSettings(); + + // enrich with local repository + if (settings.getLocalRepository() == null) { + settings = enrichWithLocalRepository(settings); + } + + return enrichWithOfflineMode(settings); + } + + // adds local repository + private Settings enrichWithLocalRepository(Settings settings) { + String altLocalRepository = SecurityActions.getProperty(ALT_LOCAL_REPOSITORY_LOCATION); + settings.setLocalRepository(DEFAULT_REPOSITORY_PATH); + + if (altLocalRepository != null && altLocalRepository.length() > 0) { + settings.setLocalRepository(altLocalRepository); + } + return settings; + } + + // adds offline mode from system property + private Settings enrichWithOfflineMode(Settings settings) { + + String goOffline = SecurityActions.getProperty(ALT_MAVEN_OFFLINE); + if (goOffline != null) { + settings.setOffline(Boolean.valueOf(goOffline)); + } + + return settings; + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/SecurityActions.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/SecurityActions.java index d22577ed..6693a03e 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/SecurityActions.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/SecurityActions.java @@ -24,155 +24,123 @@ /** * SecurityActions - * + * * A set of privileged actions that are not to leak out of this package - * - * + * + * * @author ALR * @author Karel Piwko - * + * * @version $Revision: $ */ -final class SecurityActions -{ +final class SecurityActions { - // -------------------------------------------------------------------------------|| - // Constructor - // ------------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Constructor + // ------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * No instantiation - */ - private SecurityActions() - { - throw new UnsupportedOperationException("No instantiation"); - } + /** + * No instantiation + */ + private SecurityActions() { + throw new UnsupportedOperationException("No instantiation"); + } - // -------------------------------------------------------------------------------|| - // Utility Methods - // --------------------------------------------------------------|| - // -------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| + // Utility Methods + // --------------------------------------------------------------|| + // -------------------------------------------------------------------------------|| - /** - * Obtains the Thread Context ClassLoader - */ - static ClassLoader getThreadContextClassLoader() - { - return AccessController.doPrivileged(GetTcclAction.INSTANCE); - } - - static URL getResource(final String resource) { - //AccessController.doPrivileged(SecurityActions.GetTcclAction.INSTANCE).getResource(resourceName); - - try - { - URL value = AccessController.doPrivileged(new PrivilegedExceptionAction() - { - @Override - public URL run() throws Exception - { - return getThreadContextClassLoader().getResource(resource); - } - - }); - - return value; - } - // Unwrap - catch (final PrivilegedActionException pae) - { - final Throwable t = pae.getCause(); - // Rethrow - if (t instanceof SecurityException) - { - throw (SecurityException) t; - } - if (t instanceof NullPointerException) - { - throw (NullPointerException) t; - } - else if (t instanceof IllegalArgumentException) - { - throw (IllegalArgumentException) t; - } - else - { - // No other checked Exception thrown by System.getProperty - try - { - throw (RuntimeException) t; - } - // Just in case we've really messed up - catch (final ClassCastException cce) - { - throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + /** + * Obtains the Thread Context ClassLoader + */ + static ClassLoader getThreadContextClassLoader() { + return AccessController.doPrivileged(GetTcclAction.INSTANCE); + } + + static URL getResource(final String resource) { + // AccessController.doPrivileged(SecurityActions.GetTcclAction.INSTANCE).getResource(resourceName); + + try { + URL value = AccessController.doPrivileged(new PrivilegedExceptionAction() { + @Override + public URL run() throws Exception { + return getThreadContextClassLoader().getResource(resource); + } + + }); + + return value; + } + // Unwrap + catch (final PrivilegedActionException pae) { + final Throwable t = pae.getCause(); + // Rethrow + if (t instanceof SecurityException) { + throw (SecurityException) t; } - } - } - } - - - static String getProperty(final String key) - { - try - { - String value = AccessController.doPrivileged(new PrivilegedExceptionAction() - { - public String run() - { - return System.getProperty(key); + if (t instanceof NullPointerException) { + throw (NullPointerException) t; + } else if (t instanceof IllegalArgumentException) { + throw (IllegalArgumentException) t; + } else { + // No other checked Exception thrown by System.getProperty + try { + throw (RuntimeException) t; + } + // Just in case we've really messed up + catch (final ClassCastException cce) { + throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + } } - }); - return value; - } - // Unwrap - catch (final PrivilegedActionException pae) - { - final Throwable t = pae.getCause(); - // Rethrow - if (t instanceof SecurityException) - { - throw (SecurityException) t; - } - if (t instanceof NullPointerException) - { - throw (NullPointerException) t; - } - else if (t instanceof IllegalArgumentException) - { - throw (IllegalArgumentException) t; - } - else - { - // No other checked Exception thrown by System.getProperty - try - { - throw (RuntimeException) t; + } + } + + static String getProperty(final String key) { + try { + String value = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public String run() { + return System.getProperty(key); + } + }); + return value; + } + // Unwrap + catch (final PrivilegedActionException pae) { + final Throwable t = pae.getCause(); + // Rethrow + if (t instanceof SecurityException) { + throw (SecurityException) t; } - // Just in case we've really messed up - catch (final ClassCastException cce) - { - throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + if (t instanceof NullPointerException) { + throw (NullPointerException) t; + } else if (t instanceof IllegalArgumentException) { + throw (IllegalArgumentException) t; + } else { + // No other checked Exception thrown by System.getProperty + try { + throw (RuntimeException) t; + } + // Just in case we've really messed up + catch (final ClassCastException cce) { + throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t); + } } - } - } - } - - + } + } + + /** + * Obtains the {@link Thread} Context {@link ClassLoader} + * + * @author Andrew Lee Rubinger + */ + static enum GetTcclAction implements PrivilegedAction { + INSTANCE; - /** - * Obtains the {@link Thread} Context {@link ClassLoader} - * - * @author Andrew Lee Rubinger - */ - static enum GetTcclAction implements PrivilegedAction - { - INSTANCE; - - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - } + @Override + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } + } } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/IOUtil.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/IOUtil.java index 830af5ef..aa8864f8 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/IOUtil.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/IOUtil.java @@ -30,165 +30,134 @@ * @author ALR * @version $Revision: $ */ -public final class IOUtil -{ - - //-------------------------------------------------------------------------------------|| - // Class Members ----------------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Logger - */ - private static final Logger log = Logger.getLogger(IOUtil.class.getName()); - - /** - * Name of UTF-8 Charset - */ - private static final String CHARSET_UTF8 = "UTF-8"; - - //-------------------------------------------------------------------------------------|| - // Constructor ------------------------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Internal constructor; should not be called - */ - private IOUtil() - { - throw new UnsupportedOperationException("No instances should be created; stateless class"); - } - - //-------------------------------------------------------------------------------------|| - // Required Implementations -----------------------------------------------------------|| - //-------------------------------------------------------------------------------------|| - - /** - * Obtains the contents of the specified stream - * as a String in UTF-8 charset. - * - * @param in - * @throws IllegalArgumentException If the stream was not specified - */ - public static String asUTF8String(InputStream in) - { - // Precondition check - Validate.notNull(in, "Stream must be specified"); - - StringBuilder buffer = new StringBuilder(); - String line; - - try - { - BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8)); - while ((line = reader.readLine()) != null) - { - buffer.append(line).append(Character.LINE_SEPARATOR); - } - } - catch (IOException ioe) - { - throw new RuntimeException("Error in obtaining string from " + in, ioe); - } - finally - { - try - { - in.close(); - } - catch (IOException ignore) - { - if (log.isLoggable(Level.FINER)) - { - log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); +public final class IOUtil { + + // -------------------------------------------------------------------------------------|| + // Class Members ----------------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Logger + */ + private static final Logger log = Logger.getLogger(IOUtil.class.getName()); + + /** + * Name of UTF-8 Charset + */ + private static final String CHARSET_UTF8 = "UTF-8"; + + // -------------------------------------------------------------------------------------|| + // Constructor ------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Internal constructor; should not be called + */ + private IOUtil() { + throw new UnsupportedOperationException("No instances should be created; stateless class"); + } + + // -------------------------------------------------------------------------------------|| + // Required Implementations -----------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Obtains the contents of the specified stream as a String in UTF-8 charset. + * + * @param in + * @throws IllegalArgumentException If the stream was not specified + */ + public static String asUTF8String(InputStream in) { + // Precondition check + Validate.notNull(in, "Stream must be specified"); + + StringBuilder buffer = new StringBuilder(); + String line; + + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET_UTF8)); + while ((line = reader.readLine()) != null) { + buffer.append(line).append(Character.LINE_SEPARATOR); } - } - } - - return buffer.toString(); - } - - /** - * Copies the contents from an InputStream to an OutputStream. It is the - * responsibility of the caller to close the streams passed in when done, - * though the {@link OutputStream} will be fully flushed. - * - * @param input - * @param output - * @throws IOException If a problem occurred during any I/O operations - */ - public static void copy(InputStream input, OutputStream output) throws IOException - { - final byte[] buffer = new byte[4096]; - int read = 0; - while ((read = input.read(buffer)) != -1) - { - output.write(buffer, 0, read); - } - - output.flush(); - } - - /** - * Writing the specified contents to the specified OutputStream using - * an internal buffer. Flushing the stream when completed. Caller is - * responsible for opening and closing the specified stream. - * - * @param output The OutputStream - * @param content The content to write to the specified stream - * @throws IOException If a problem occured during any I/O operations - */ - public static void bufferedWriteWithFlush(final OutputStream output, final byte[] content) throws IOException - { - final int size = 4096; - int offset = 0; - while(content.length-(offset+size) > size){ - output.write(content, offset, offset + size); - offset += size; - } - output.write(content, offset, content.length); - output.flush(); - } - - /** - * Copies the contents from an InputStream to an OutputStream and closes both streams. - * - * @param input - * @param output - * @throws IOException If a problem occurred during any I/O operations during the copy, but - * on closing the streams these will be ignored and logged at {@link Level#FINER} - */ - public static void copyWithClose(InputStream input, OutputStream output) throws IOException - { - try - { - copy(input, output); - } - finally - { - try - { - input.close(); - } - catch (final IOException ignore) - { - if (log.isLoggable(Level.FINER)) - { - log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); + } catch (IOException ioe) { + throw new RuntimeException("Error in obtaining string from " + in, ioe); + } finally { + try { + in.close(); + } catch (IOException ignore) { + if (log.isLoggable(Level.FINER)) { + log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); + } } - } - try - { - output.close(); - } - catch (final IOException ignore) - { - if (log.isLoggable(Level.FINER)) - { - log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); + } + + return buffer.toString(); + } + + /** + * Copies the contents from an InputStream to an OutputStream. It is the responsibility of the caller to close the streams + * passed in when done, though the {@link OutputStream} will be fully flushed. + * + * @param input + * @param output + * @throws IOException If a problem occurred during any I/O operations + */ + public static void copy(InputStream input, OutputStream output) throws IOException { + final byte[] buffer = new byte[4096]; + int read = 0; + while ((read = input.read(buffer)) != -1) { + output.write(buffer, 0, read); + } + + output.flush(); + } + + /** + * Writing the specified contents to the specified OutputStream using an internal buffer. Flushing the stream when + * completed. Caller is responsible for opening and closing the specified stream. + * + * @param output The OutputStream + * @param content The content to write to the specified stream + * @throws IOException If a problem occured during any I/O operations + */ + public static void bufferedWriteWithFlush(final OutputStream output, final byte[] content) throws IOException { + final int size = 4096; + int offset = 0; + while (content.length - (offset + size) > size) { + output.write(content, offset, offset + size); + offset += size; + } + output.write(content, offset, content.length); + output.flush(); + } + + /** + * Copies the contents from an InputStream to an OutputStream and closes both streams. + * + * @param input + * @param output + * @throws IOException If a problem occurred during any I/O operations during the copy, but on closing the streams these + * will be ignored and logged at {@link Level#FINER} + */ + public static void copyWithClose(InputStream input, OutputStream output) throws IOException { + try { + copy(input, output); + } finally { + try { + input.close(); + } catch (final IOException ignore) { + if (log.isLoggable(Level.FINER)) { + log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); + } } - } - } - } - + try { + output.close(); + } catch (final IOException ignore) { + if (log.isLoggable(Level.FINER)) { + log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring"); + } + } + } + } + } diff --git a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/Validate.java b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/Validate.java index e5719716..f1c3fc14 100644 --- a/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/Validate.java +++ b/impl-maven/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/util/Validate.java @@ -21,95 +21,83 @@ /** * Validate - * + * * Validation utility - * + * * @author Aslak Knutsen * @auther Karel Piwko * @version $Revision: $ */ -public final class Validate -{ - private Validate() - { - } +public final class Validate { + private Validate() { + } - /** - * Checks that object is not null, throws exception if it is. - * - * @param obj The object to check - * @param message The exception message - * @throws IllegalArgumentException Thrown if obj is null - */ - public static void notNull(final Object obj, final String message) throws IllegalArgumentException - { - if (obj == null) - { - throw new IllegalArgumentException(message); - } - } + /** + * Checks that object is not null, throws exception if it is. + * + * @param obj The object to check + * @param message The exception message + * @throws IllegalArgumentException Thrown if obj is null + */ + public static void notNull(final Object obj, final String message) throws IllegalArgumentException { + if (obj == null) { + throw new IllegalArgumentException(message); + } + } - /** - * Checks that collection is not {@code null} or empty, throws exception if it is. - * @param collection The collection to be checked - * @param message The exception message - * @throws IllegalArgumentException Thrown if {@code collection} is {@code null} or empty - */ - public static void notEmpty(final Collection collection, final String message) throws IllegalArgumentException - { - if (collection == null || collection.size() == 0) - { - throw new IllegalArgumentException(message); - } - } + /** + * Checks that collection is not {@code null} or empty, throws exception if it is. + * + * @param collection The collection to be checked + * @param message The exception message + * @throws IllegalArgumentException Thrown if {@code collection} is {@code null} or empty + */ + public static void notEmpty(final Collection collection, final String message) throws IllegalArgumentException { + if (collection == null || collection.size() == 0) { + throw new IllegalArgumentException(message); + } + } - /** - * Checks that the specified String is not null or empty, - * throws exception if it is. - * - * @param string The object to check - * @param message The exception message - * @throws IllegalArgumentException Thrown if string is null - */ - public static void notNullOrEmpty(final String string, final String message) throws IllegalArgumentException - { - if (string == null || string.length() == 0) - { - throw new IllegalArgumentException(message); - } - } + /** + * Checks that the specified String is not null or empty, throws exception if it is. + * + * @param string The object to check + * @param message The exception message + * @throws IllegalArgumentException Thrown if string is null + */ + public static void notNullOrEmpty(final String string, final String message) throws IllegalArgumentException { + if (string == null || string.length() == 0) { + throw new IllegalArgumentException(message); + } + } - /** - * Checks that the specified String is not null or empty and represents - * a readable file, throws exception if it is empty or null and does not represent a path - * to a file. - * @param path The path to check - * @param message The exception message - * @throws IllegalArgumentException Thrown if path is empty, null or invalid - */ - public static void isReadable(final String path, String message) throws IllegalArgumentException - { - notNullOrEmpty(path, message); - File file = new File(path); - if (!file.exists() || !file.canRead()) - { - throw new IllegalArgumentException(message); - } + /** + * Checks that the specified String is not null or empty and represents a readable file, throws exception if it is empty or + * null and does not represent a path to a file. + * + * @param path The path to check + * @param message The exception message + * @throws IllegalArgumentException Thrown if path is empty, null or invalid + */ + public static void isReadable(final String path, String message) throws IllegalArgumentException { + notNullOrEmpty(path, message); + File file = new File(path); + if (!file.exists() || !file.canRead()) { + throw new IllegalArgumentException(message); + } - } + } - /** - * Checks that the specified array is not null or contain any null values. - * - * @param objects The object to check - * @param message The exception message - */ - public static void notNullAndNoNullValues(final Object[] objects, final String message) - { - notNull(objects, message); - for (Object object : objects) - { - notNull(object, message); - } - } + /** + * Checks that the specified array is not null or contain any null values. + * + * @param objects The object to check + * @param message The exception message + */ + public static void notNullAndNoNullValues(final Object[] objects, final String message) { + notNull(objects, message); + for (Object object : objects) { + notNull(object, message); + } + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactDependenciesUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactDependenciesUnitTestCase.java index f5acba7c..4e0d86ca 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactDependenciesUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ArtifactDependenciesUnitTestCase.java @@ -29,81 +29,80 @@ /** * @author Karel Piwko - * + * */ -public class ArtifactDependenciesUnitTestCase -{ - /** - * Tests a resolution of an artifact from central with custom settings - * - * @throws ResolutionException - */ - @Test - public void testPomBasedArtifact() throws ResolutionException - { - String name = "pomBasedArtifact"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings.xml") - .artifact("org.jboss.shrinkwrap.test:test-parent:pom:1.0.0") - .resolveAs(GenericArchive.class)); - - // only default and compile scoped artifacts are resolved - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/test-parent.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - @Test - public void testPomBasedArtifactWithFileQualifier() throws ResolutionException { - String name = "testPomBasedArtifactWithFileQualifier"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("file:target/settings/profiles/settings.xml") - .artifact("org.jboss.shrinkwrap.test:test-parent:pom:1.0.0").resolveAs(GenericArchive.class)); - - // only default and compile scoped artifacts are resolved - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-parent.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - @Test - public void testPomBasedArtifactLocatedInClassPath() throws ResolutionException { - String name = "pomBasedArtifactLocatedInClassPath"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") - .addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("classpath:profiles/settings3.xml") - .includeDependenciesFromPom("classpath:poms/test-parent.xml").resolveAs(GenericArchive.class)); - - // only default and compile scoped artifacts are resolved - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/test-parent.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - // this test won't run on IDE since it uses a surefire configuration - @Test - public void testPomBasedArtifactLocatedInsideJar() throws ResolutionException { - String name = "pomBasedArtifactLocatedInsideJar"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("classpath:org/jboss/shrinkwrap/profiles/settings3.xml") - .includeDependenciesFromPom("classpath:org/jboss/shrinkwrap/poms/test-parent.xml") - .resolveAs(GenericArchive.class)); - - // only default and compile scoped artifacts are resolved - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/test-parent.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } +public class ArtifactDependenciesUnitTestCase { + /** + * Tests a resolution of an artifact from central with custom settings + * + * @throws ResolutionException + */ + @Test + public void testPomBasedArtifact() throws ResolutionException { + String name = "pomBasedArtifact"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") + .artifact("org.jboss.shrinkwrap.test:test-parent:pom:1.0.0").resolveAs(GenericArchive.class)); + + // only default and compile scoped artifacts are resolved + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-parent.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + @Test + public void testPomBasedArtifactWithFileQualifier() throws ResolutionException { + String name = "testPomBasedArtifactWithFileQualifier"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("file:target/settings/profiles/settings.xml") + .artifact("org.jboss.shrinkwrap.test:test-parent:pom:1.0.0").resolveAs(GenericArchive.class)); + + // only default and compile scoped artifacts are resolved + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-parent.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + @Test + public void testPomBasedArtifactLocatedInClassPath() throws ResolutionException { + String name = "pomBasedArtifactLocatedInClassPath"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("classpath:profiles/settings3.xml") + .includeDependenciesFromPom("classpath:poms/test-parent.xml").resolveAs(GenericArchive.class)); + + // only default and compile scoped artifacts are resolved + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-parent.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + // this test won't run on IDE since it uses a surefire configuration + @Test + public void testPomBasedArtifactLocatedInsideJar() throws ResolutionException { + String name = "pomBasedArtifactLocatedInsideJar"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("classpath:org/jboss/shrinkwrap/profiles/settings3.xml") + .includeDependenciesFromPom("classpath:org/jboss/shrinkwrap/poms/test-parent.xml") + .resolveAs(GenericArchive.class)); + + // only default and compile scoped artifacts are resolved + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-parent.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependenciesUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependenciesUnitTestCase.java index 2f12cd5c..f5b08da8 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependenciesUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependenciesUnitTestCase.java @@ -35,154 +35,142 @@ * @author Karel Piwko * @version $Revision: $ */ -public class DependenciesUnitTestCase -{ - @BeforeClass - public static void setRemoteRepository() - { - System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings.xml"); - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); - } - - @AfterClass - public static void clearRemoteRepository() - { - System.clearProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION); - System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); - - } - - // -------------------------------------------------------------------------------------|| - // Tests - // ------------------------------------------------------------------------------|| - // -------------------------------------------------------------------------------------|| - - /** - * Tests that artifact is cannot be packaged, but is is resolved right. This - * test is not executed but shows that some jars cannot be packaged - */ - // @Test(expected = - // org.jboss.shrinkwrap.api.importer.ArchiveImportException.class) - // @Ignore - public void testSimpleResolutionWrongArtifact() throws ResolutionException - { - String name = "simpleResolutionWrongArtifact"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .artifact("org.apache.maven.plugins:maven-compiler-plugin:2.3.2").resolveAs(GenericArchive.class)); - - // it will fail here - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests a resolution of an artifact from central - * - * @throws ResolutionException - */ - @Test - public void testSimpleResolution() throws ResolutionException - { - String name = "simpleResolution"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests a resolution of an artifact from central with custom settings - * - * @throws ResolutionException - */ - @Test - public void testSimpleResolutionWithCustomSettings() throws ResolutionException - { - String name = "simpleResolutionWithCustomSettings"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests passing invalid path to a settings XML - * - * @throws ResolutionException - */ - @Test(expected = IllegalArgumentException.class) - public void testInvalidSettingsPath() throws ResolutionException - { - - // this should fail - ShrinkWrap.create(WebArchive.class, "testSimpleResolutionWithCustomSettings.war") - .addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("src/test/invalid/custom-settings.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAs(GenericArchive.class)); - - } - - /** - * Tests a resolution of two artifacts from central - * - * @throws ResolutionException - */ - @Test - public void testMultipleResolution() throws ResolutionException - { - String name = "multipleResolution"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .artifact("org.jboss.shrinkwrap.test:test-deps-g:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c+g.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests a resolution of two artifacts from central using single call - * - * @throws ResolutionException - */ - @Test - public void testMultipleResolutionSingleCall() throws ResolutionException - { - String name = "multipleResolutionSingleCall"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers - .use(MavenDependencyResolver.class) - .artifacts("org.jboss.shrinkwrap.test:test-deps-c:1.0.0", - "org.jboss.shrinkwrap.test:test-deps-g:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c+g.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } +public class DependenciesUnitTestCase { + @BeforeClass + public static void setRemoteRepository() { + System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings.xml"); + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); + } + + @AfterClass + public static void clearRemoteRepository() { + System.clearProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION); + System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); + + } + + // -------------------------------------------------------------------------------------|| + // Tests + // ------------------------------------------------------------------------------|| + // -------------------------------------------------------------------------------------|| + + /** + * Tests that artifact is cannot be packaged, but is is resolved right. This test is not executed but shows that some jars + * cannot be packaged + */ + // @Test(expected = + // org.jboss.shrinkwrap.api.importer.ArchiveImportException.class) + // @Ignore + public void testSimpleResolutionWrongArtifact() throws ResolutionException { + String name = "simpleResolutionWrongArtifact"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class) + .artifact("org.apache.maven.plugins:maven-compiler-plugin:2.3.2").resolveAs(GenericArchive.class)); + + // it will fail here + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests a resolution of an artifact from central + * + * @throws ResolutionException + */ + @Test + public void testSimpleResolution() throws ResolutionException { + String name = "simpleResolution"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") + .resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests a resolution of an artifact from central with custom settings + * + * @throws ResolutionException + */ + @Test + public void testSimpleResolutionWithCustomSettings() throws ResolutionException { + String name = "simpleResolutionWithCustomSettings"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests passing invalid path to a settings XML + * + * @throws ResolutionException + */ + @Test(expected = IllegalArgumentException.class) + public void testInvalidSettingsPath() throws ResolutionException { + + // this should fail + ShrinkWrap.create(WebArchive.class, "testSimpleResolutionWithCustomSettings.war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("src/test/invalid/custom-settings.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); + + } + + /** + * Tests a resolution of two artifacts from central + * + * @throws ResolutionException + */ + @Test + public void testMultipleResolution() throws ResolutionException { + String name = "multipleResolution"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") + .artifact("org.jboss.shrinkwrap.test:test-deps-g:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c+g.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests a resolution of two artifacts from central using single call + * + * @throws ResolutionException + */ + @Test + public void testMultipleResolutionSingleCall() throws ResolutionException { + String name = "multipleResolutionSingleCall"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") + .addAsLibraries( + DependencyResolvers + .use(MavenDependencyResolver.class) + .artifacts("org.jboss.shrinkwrap.test:test-deps-c:1.0.0", + "org.jboss.shrinkwrap.test:test-deps-g:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c+g.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependencyTreeDescription.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependencyTreeDescription.java index 27424c57..6c794cc2 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependencyTreeDescription.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DependencyTreeDescription.java @@ -35,401 +35,335 @@ import org.jboss.shrinkwrap.resolver.api.ResolutionException; /** - * A validation utility for verifying Artifact resolution. It checks archive's content - * against previously generated dependency tree. - * + * A validation utility for verifying Artifact resolution. It checks archive's content against previously generated dependency + * tree. + * * @author Karel Piwko - * + * */ -public class DependencyTreeDescription -{ - private static final Logger log = Logger.getLogger(DependencyTreeDescription.class.getName()); - - private Map artifacts; - - private Set allowedScopes; - - /** - * Creates a description from the file - * @param file A file with dependency:tree output - * @param scopes A list of allowed scopes - * @throws ResolutionException - */ - public DependencyTreeDescription(File file, String... scopes) throws ResolutionException - { - this.allowedScopes = new HashSet(Arrays.asList(scopes)); - this.artifacts = load(file); - } - - /** - * Checks that files from dependency tree are present in the archive - * @param archive The archive to be checked - * @return The current dependency tree to allow chaining - */ - public DependencyTreeDescription validateArchive(Archive archive) - { - return validateArchive(archive, new Filter() - { - - public boolean include(ArchivePath object) - { - return true; - } - }); - } - - /** - * Checks that files from dependency tree are present in the archive - * @param archive The archive to be checked - * @param filter The filter for archive content which will be checked - * @return The current dependency tree to allow chaining - */ - public DependencyTreeDescription validateArchive(Archive archive, Filter filter) - { - for (ArchivePath path : archive.getContent(filter).keySet()) - { - String pathString = path.get(); - - for (ArtifactHolder artifact : artifacts.keySet()) - { - if (pathString.endsWith(artifact.filename())) - { - artifacts.put(artifact, Boolean.TRUE); +public class DependencyTreeDescription { + private static final Logger log = Logger.getLogger(DependencyTreeDescription.class.getName()); + + private Map artifacts; + + private Set allowedScopes; + + /** + * Creates a description from the file + * + * @param file A file with dependency:tree output + * @param scopes A list of allowed scopes + * @throws ResolutionException + */ + public DependencyTreeDescription(File file, String... scopes) throws ResolutionException { + this.allowedScopes = new HashSet(Arrays.asList(scopes)); + this.artifacts = load(file); + } + + /** + * Checks that files from dependency tree are present in the archive + * + * @param archive The archive to be checked + * @return The current dependency tree to allow chaining + */ + public DependencyTreeDescription validateArchive(Archive archive) { + return validateArchive(archive, new Filter() { + + public boolean include(ArchivePath object) { + return true; } - } - } - return this; - } - - /** - * Checks that files from dependency tree are present in directory - * @param archive The archive to be checked - * @param filter The filter for archive content which will be checked - * @return The current dependency tree to allow chaining - */ - public DependencyTreeDescription validateDirectory(File directory) - { - if (!directory.isDirectory()) - { - throw new AssertionError(directory.getAbsolutePath() + " is not a directory"); - } - - return validateFiles(directory.listFiles()); - } - - public DependencyTreeDescription validateFiles(File...files) - { - for (File file : files) - { - String pathString = file.getAbsolutePath(); - - for (ArtifactHolder artifact : artifacts.keySet()) - { - if (pathString.endsWith(artifact.filename())) - { - artifacts.put(artifact, Boolean.TRUE); + }); + } + + /** + * Checks that files from dependency tree are present in the archive + * + * @param archive The archive to be checked + * @param filter The filter for archive content which will be checked + * @return The current dependency tree to allow chaining + */ + public DependencyTreeDescription validateArchive(Archive archive, Filter filter) { + for (ArchivePath path : archive.getContent(filter).keySet()) { + String pathString = path.get(); + + for (ArtifactHolder artifact : artifacts.keySet()) { + if (pathString.endsWith(artifact.filename())) { + artifacts.put(artifact, Boolean.TRUE); + } } - } - } - return this; - } - - - - /** - * Verifies that all artifacts present in dependency tree were found during validation - * @throws AssertionError If not all artifacts were found. - */ - public void results() throws AssertionError - { - boolean allFound = true; - StringBuilder sb = new StringBuilder(); - for (Entry entry : artifacts.entrySet()) - { - boolean current = entry.getValue().booleanValue(); - if (current == false) - { - sb.append("Missing artifact: ").append(entry.getKey().filename()) - .append(" in the archive!").append("\n"); - allFound = false; - } - } - - if (allFound != true) - { - throw new AssertionError(sb.toString()); - } - - } - - private Map load(File file) throws ResolutionException - { - Map artifacts = new HashMap(); - - try - { - BufferedReader input = new BufferedReader(new FileReader(file)); - - String line = null; - while ((line = input.readLine()) != null) - { - ArtifactHolder holder = new ArtifactHolder(line); - if (!"jar".equals(holder.extension)) - { - log.info("Removing non-JAR artifact " + holder.toString() + " from dependencies, it's dependencies are fetched"); + } + return this; + } + + /** + * Checks that files from dependency tree are present in directory + * + * @param archive The archive to be checked + * @param filter The filter for archive content which will be checked + * @return The current dependency tree to allow chaining + */ + public DependencyTreeDescription validateDirectory(File directory) { + if (!directory.isDirectory()) { + throw new AssertionError(directory.getAbsolutePath() + " is not a directory"); + } + + return validateFiles(directory.listFiles()); + } + + public DependencyTreeDescription validateFiles(File... files) { + for (File file : files) { + String pathString = file.getAbsolutePath(); + + for (ArtifactHolder artifact : artifacts.keySet()) { + if (pathString.endsWith(artifact.filename())) { + artifacts.put(artifact, Boolean.TRUE); + } } - else if (holder.root) - { - log.fine("Root of the tree (" + holder.toString() + ")should not be included in the artifact itself"); + } + return this; + } + + /** + * Verifies that all artifacts present in dependency tree were found during validation + * + * @throws AssertionError If not all artifacts were found. + */ + public void results() throws AssertionError { + boolean allFound = true; + StringBuilder sb = new StringBuilder(); + for (Entry entry : artifacts.entrySet()) { + boolean current = entry.getValue().booleanValue(); + if (current == false) { + sb.append("Missing artifact: ").append(entry.getKey().filename()).append(" in the archive!").append("\n"); + allFound = false; } - // add artifact if in allowed scope - else if (allowedScopes.isEmpty() || (!allowedScopes.isEmpty() && allowedScopes.contains(holder.scope))) - { - artifacts.put(new ArtifactHolder(line), Boolean.FALSE); + } + + if (allFound != true) { + throw new AssertionError(sb.toString()); + } + + } + + private Map load(File file) throws ResolutionException { + Map artifacts = new HashMap(); + + try { + BufferedReader input = new BufferedReader(new FileReader(file)); + + String line = null; + while ((line = input.readLine()) != null) { + ArtifactHolder holder = new ArtifactHolder(line); + if (!"jar".equals(holder.extension)) { + log.info("Removing non-JAR artifact " + holder.toString() + + " from dependencies, it's dependencies are fetched"); + } else if (holder.root) { + log.fine("Root of the tree (" + holder.toString() + ")should not be included in the artifact itself"); + } + // add artifact if in allowed scope + else if (allowedScopes.isEmpty() || (!allowedScopes.isEmpty() && allowedScopes.contains(holder.scope))) { + artifacts.put(new ArtifactHolder(line), Boolean.FALSE); + } } - } - } - catch (IOException e) - { - throw new ResolutionException("Unable to load dependency tree to verify", e); - } - - return artifacts; - } + } catch (IOException e) { + throw new ResolutionException("Unable to load dependency tree to verify", e); + } + + return artifacts; + } } /** * A holder for a line generated from Maven dependency tree plugin + * * @author Karel Piwko - * + * */ -class ArtifactHolder -{ - - final String groupId; - final String artifactId; - final String extension; - final String classifier; - final String version; - final String scope; - - final boolean root; - - /** - * Creates an artifact holder from the input lien - * @param dependencyCoords - */ - ArtifactHolder(String dependencyCoords) - { - int index = 0; - while (index < dependencyCoords.length()) - { - char c = dependencyCoords.charAt(index); - if (c == '\\' || c == '|' || c == ' ' || c == '+' || c == '-') - { - index++; - } - else - { - break; - } - } - - for (int testIndex = index, i = 0; i < 4; i++) - { - testIndex = dependencyCoords.substring(testIndex).indexOf(":"); - if (testIndex == -1) - { - throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); - } - } - - StringTokenizer st = new StringTokenizer(dependencyCoords.substring(index), ":"); - - this.groupId = st.nextToken(); - this.artifactId = st.nextToken(); - this.extension = st.nextToken(); - - // this is the root artifact - if (index == 0) - { - this.root = true; - - if (st.countTokens() == 1) - { - this.classifier = ""; - this.version = st.nextToken(); - } - else if (st.countTokens() == 2) - { - this.classifier = st.nextToken(); - this.version = st.nextToken(); - } - else - { - throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); - } - - this.scope = ""; - } - // otherwise - else - { - this.root = false; - - if (st.countTokens() == 2) - { - this.classifier = ""; - this.version = st.nextToken(); - this.scope = extractScope(st.nextToken()); - } - else if (st.countTokens() == 3) - { - this.classifier = st.nextToken(); - this.version = st.nextToken(); - this.scope = extractScope(st.nextToken()); - } - else - { - throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); - } - } - } - - public String filename() - { - StringBuilder sb = new StringBuilder(); - sb.append(artifactId).append("-").append(version); - if (classifier.length() != 0) - { - sb.append("-").append(classifier); - } - sb.append(".").append(extension); - - return sb.toString(); - } - - public String toString() - { - StringBuilder sb = new StringBuilder(); - - sb.append("groupId=").append(groupId).append(", "); - sb.append("artifactId=").append(artifactId).append(", "); - sb.append("type=").append(extension).append(", "); - sb.append("version=").append(version); - - if (scope != "") - { - sb.append(", scope=").append(scope); - } - - if (classifier != "") - { - sb.append(", classifier=").append(classifier); - } - - return sb.toString(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); - result = prime * result + ((classifier == null) ? 0 : classifier.hashCode()); - result = prime * result + ((extension == null) ? 0 : extension.hashCode()); - result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); - result = prime * result + (root ? 1231 : 1237); - result = prime * result + ((scope == null) ? 0 : scope.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ArtifactHolder other = (ArtifactHolder) obj; - if (artifactId == null) - { - if (other.artifactId != null) +class ArtifactHolder { + + final String groupId; + final String artifactId; + final String extension; + final String classifier; + final String version; + final String scope; + + final boolean root; + + /** + * Creates an artifact holder from the input lien + * + * @param dependencyCoords + */ + ArtifactHolder(String dependencyCoords) { + int index = 0; + while (index < dependencyCoords.length()) { + char c = dependencyCoords.charAt(index); + if (c == '\\' || c == '|' || c == ' ' || c == '+' || c == '-') { + index++; + } else { + break; + } + } + + for (int testIndex = index, i = 0; i < 4; i++) { + testIndex = dependencyCoords.substring(testIndex).indexOf(":"); + if (testIndex == -1) { + throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); + } + } + + StringTokenizer st = new StringTokenizer(dependencyCoords.substring(index), ":"); + + this.groupId = st.nextToken(); + this.artifactId = st.nextToken(); + this.extension = st.nextToken(); + + // this is the root artifact + if (index == 0) { + this.root = true; + + if (st.countTokens() == 1) { + this.classifier = ""; + this.version = st.nextToken(); + } else if (st.countTokens() == 2) { + this.classifier = st.nextToken(); + this.version = st.nextToken(); + } else { + throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); + } + + this.scope = ""; + } + // otherwise + else { + this.root = false; + + if (st.countTokens() == 2) { + this.classifier = ""; + this.version = st.nextToken(); + this.scope = extractScope(st.nextToken()); + } else if (st.countTokens() == 3) { + this.classifier = st.nextToken(); + this.version = st.nextToken(); + this.scope = extractScope(st.nextToken()); + } else { + throw new IllegalArgumentException("Invalid format of the dependency coordinates for " + dependencyCoords); + } + } + } + + public String filename() { + StringBuilder sb = new StringBuilder(); + sb.append(artifactId).append("-").append(version); + if (classifier.length() != 0) { + sb.append("-").append(classifier); + } + sb.append(".").append(extension); + + return sb.toString(); + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append("groupId=").append(groupId).append(", "); + sb.append("artifactId=").append(artifactId).append(", "); + sb.append("type=").append(extension).append(", "); + sb.append("version=").append(version); + + if (scope != "") { + sb.append(", scope=").append(scope); + } + + if (classifier != "") { + sb.append(", classifier=").append(classifier); + } + + return sb.toString(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((artifactId == null) ? 0 : artifactId.hashCode()); + result = prime * result + ((classifier == null) ? 0 : classifier.hashCode()); + result = prime * result + ((extension == null) ? 0 : extension.hashCode()); + result = prime * result + ((groupId == null) ? 0 : groupId.hashCode()); + result = prime * result + (root ? 1231 : 1237); + result = prime * result + ((scope == null) ? 0 : scope.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ArtifactHolder other = (ArtifactHolder) obj; + if (artifactId == null) { + if (other.artifactId != null) + return false; + } else if (!artifactId.equals(other.artifactId)) return false; - } - else if (!artifactId.equals(other.artifactId)) - return false; - if (classifier == null) - { - if (other.classifier != null) + if (classifier == null) { + if (other.classifier != null) + return false; + } else if (!classifier.equals(other.classifier)) return false; - } - else if (!classifier.equals(other.classifier)) - return false; - if (extension == null) - { - if (other.extension != null) + if (extension == null) { + if (other.extension != null) + return false; + } else if (!extension.equals(other.extension)) return false; - } - else if (!extension.equals(other.extension)) - return false; - if (groupId == null) - { - if (other.groupId != null) + if (groupId == null) { + if (other.groupId != null) + return false; + } else if (!groupId.equals(other.groupId)) return false; - } - else if (!groupId.equals(other.groupId)) - return false; - if (root != other.root) - return false; - if (scope == null) - { - if (other.scope != null) + if (root != other.root) return false; - } - else if (!scope.equals(other.scope)) - return false; - if (version == null) - { - if (other.version != null) + if (scope == null) { + if (other.scope != null) + return false; + } else if (!scope.equals(other.scope)) return false; - } - else if (!version.equals(other.version)) - return false; - return true; - } - - private String extractScope(String scope) - { - int lparen = scope.indexOf("("); - int rparen = scope.indexOf(")"); - int space = scope.indexOf(" "); - - if (lparen == -1 && rparen == -1 && space == -1) - { - return scope; - } - else if (lparen != -1 && rparen != -1 && space != -1) - { - return scope.substring(0, space); - } - - throw new IllegalArgumentException("Invalid format of the dependency coordinates for artifact scope: " + scope); - - } + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } + + private String extractScope(String scope) { + int lparen = scope.indexOf("("); + int rparen = scope.indexOf(")"); + int space = scope.indexOf(" "); + + if (lparen == -1 && rparen == -1 && space == -1) { + return scope; + } else if (lparen != -1 && rparen != -1 && space != -1) { + return scope.substring(0, space); + } + + throw new IllegalArgumentException("Invalid format of the dependency coordinates for artifact scope: " + scope); + + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DisabledCentralRepositoryTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DisabledCentralRepositoryTestCase.java index 8a3fe32d..731adfa7 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DisabledCentralRepositoryTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/DisabledCentralRepositoryTestCase.java @@ -15,25 +15,23 @@ */ public class DisabledCentralRepositoryTestCase { - /** - * Tests the disabling of the Maven central repository - */ - @Test - public void shouldHaveCentralMavenRepositoryDisabled() throws Exception - { - String name = "disabledCentralRepoArchive.war"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name) - .addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class) - .useCentralRepo(false) - .includeDependenciesFromPom("target/poms/test-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0") - .resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/test-child.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name), true); - } + /** + * Tests the disabling of the Maven central repository + */ + @Test + public void shouldHaveCentralMavenRepositoryDisabled() throws Exception { + String name = "disabledCentralRepoArchive.war"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name).addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).useCentralRepo(false) + .includeDependenciesFromPom("target/poms/test-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name), true); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ExclusionsUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ExclusionsUnitTestCase.java index 260a67bf..7fa3dd92 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ExclusionsUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ExclusionsUnitTestCase.java @@ -37,150 +37,140 @@ * @author Karel Piwko * */ -public class ExclusionsUnitTestCase -{ - private static final Logger log = Logger.getLogger(ExclusionsUnitTestCase.class.getName()); - - @BeforeClass - public static void setRemoteRepository() - { - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); - } - - @AfterClass - public static void clearRemoteRepository() - { - System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); - } - - /** - * Tests exclusion of the artifacts - * - * @throws ResolutionException - */ - @Test - public void testExclusion() throws ResolutionException - { - log.fine("Started exclusion"); - String name = "exclusion"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:jar:1.0.0").scope("test") - .exclusion("org.jboss.shrinkwrap.test:test-deps-f") - .resolveAs(GenericArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" - + name + ".tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests exclusion of the artifacts - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testExclusionDeprecated() throws ResolutionException - { - String name = "exclusion"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:jar:1.0.0").scope("test") - .exclusion("org.jboss.shrinkwrap.test:test-deps-f") - .resolveAs(GenericArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" - + name + ".tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests exclusion of the artifacts - * - * @throws ResolutionException - */ - @Test - public void testExclusions() throws ResolutionException - { - String name = "exclusions"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") - .exclusions("org.jboss.shrinkwrap.test:test-deps-f", "org.jboss.shrinkwrap.test:test-deps-g") - .resolveAs(GenericArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" - + name + ".tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests exclusion of the artifacts - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testExclusionsDeprecated() throws ResolutionException - { - String name = "exclusions"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") - .exclusions("org.jboss.shrinkwrap.test:test-deps-f", "org.jboss.shrinkwrap.test:test-deps-g") - .resolveAs(GenericArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" - + name + ".tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests exclusion of all transitive artifacts - */ - @Test - public void testUniversalExclusion() - { - - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test").exclusion("*") - .resolveAsFiles(new ScopeFilter("test")); - - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-dependency-test-1.0.0.jar", "test-dependency-test-1.0.0.jar", - files[0].getName()); - } - - /** - * Tests exclusion of all transitive artifacts - */ - @Test - @Deprecated - public void testUniversalExclusionDeprecated() - { - - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test").exclusion("*") - .resolveAsFiles(new ScopeFilter("test")); - - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-dependency-test-1.0.0.jar", "test-dependency-test-1.0.0.jar", - files[0].getName()); - } +public class ExclusionsUnitTestCase { + private static final Logger log = Logger.getLogger(ExclusionsUnitTestCase.class.getName()); + + @BeforeClass + public static void setRemoteRepository() { + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); + } + + @AfterClass + public static void clearRemoteRepository() { + System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); + } + + /** + * Tests exclusion of the artifacts + * + * @throws ResolutionException + */ + @Test + public void testExclusion() throws ResolutionException { + log.fine("Started exclusion"); + String name = "exclusion"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:jar:1.0.0").scope("test") + .exclusion("org.jboss.shrinkwrap.test:test-deps-f") + .resolveAs(GenericArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name + + ".tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests exclusion of the artifacts + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testExclusionDeprecated() throws ResolutionException { + String name = "exclusion"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:jar:1.0.0").scope("test") + .exclusion("org.jboss.shrinkwrap.test:test-deps-f") + .resolveAs(GenericArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name + + ".tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests exclusion of the artifacts + * + * @throws ResolutionException + */ + @Test + public void testExclusions() throws ResolutionException { + String name = "exclusions"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .exclusions("org.jboss.shrinkwrap.test:test-deps-f", "org.jboss.shrinkwrap.test:test-deps-g") + .resolveAs(GenericArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name + + ".tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests exclusion of the artifacts + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testExclusionsDeprecated() throws ResolutionException { + String name = "exclusions"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .exclusions("org.jboss.shrinkwrap.test:test-deps-f", "org.jboss.shrinkwrap.test:test-deps-g") + .resolveAs(GenericArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name + + ".tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests exclusion of all transitive artifacts + */ + @Test + public void testUniversalExclusion() { + + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .loadMetadataFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test").exclusion("*") + .resolveAsFiles(new ScopeFilter("test")); + + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-dependency-test-1.0.0.jar", "test-dependency-test-1.0.0.jar", + files[0].getName()); + } + + /** + * Tests exclusion of all transitive artifacts + */ + @Test + @Deprecated + public void testUniversalExclusionDeprecated() { + + File[] files = DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test").exclusion("*") + .resolveAsFiles(new ScopeFilter("test")); + + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-dependency-test-1.0.0.jar", "test-dependency-test-1.0.0.jar", + files[0].getName()); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolutionFilterUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolutionFilterUnitTestCase.java index 8860a18a..e08dec28 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolutionFilterUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MavenResolutionFilterUnitTestCase.java @@ -43,466 +43,412 @@ * @author Karel Piwko * */ -public class MavenResolutionFilterUnitTestCase -{ - @BeforeClass - public static void setRemoteRepository() - { - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); - } - - /** - * Tests that only directly defined artifacts are added to dependencies - * - * @throws ResolutionException - */ - @Test - public void testStrictFilter() throws ResolutionException - { - String name = "strictFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0") - .resolveAs(GenericArchive.class, new StrictFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is only one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-child:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-child-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests that only directly defined artifacts are added to dependencies - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testStrictFilterDeprecated() throws ResolutionException - { - String name = "strictFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0") - .resolveAs(GenericArchive.class, new StrictFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is only one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-child:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-child-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests that only directly defined artifacts are added to dependencies, the - * artifact version is taken from a POM file - * - * @throws ResolutionException - */ - @Test - public void testStrictFilterInferredVersion() throws ResolutionException - { - String name = "strictFilterInferredVersion"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c") - .resolveAs(GenericArchive.class, new StrictFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is only one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-deps-c:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-c-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests that only directly defined artifacts are added to dependencies, the - * artifact version is taken from a POM file - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testStrictFilterInferredVersionDeprecated() throws ResolutionException - { - String name = "strictFilterInferredVersion"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c") - .resolveAs(GenericArchive.class, new StrictFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is only one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-deps-c:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-c-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests loading of a POM file with parent not available on local file system - * - * @throws ResolutionException - */ - @Test - public void testDefaultScopeFilter() throws ResolutionException - { - String name = "defaultScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-remote-child:1.0.0") - .resolveAs(GenericArchive.class, new ScopeFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-remote-child:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-remote-child-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent not available on local file system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testDefaultScopeFilterDeprecated() throws ResolutionException - { - String name = "defaultScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-remote-child:1.0.0") - .resolveAs(GenericArchive.class, new ScopeFilter())); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-remote-child:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-remote-child-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope - * - * @throws ResolutionException - */ - @Test - public void testRuntimeScopeFilter() throws ResolutionException - { - String name = "runtimeScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .resolveAs(GenericArchive.class, new ScopeFilter("runtime"))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-deps-b:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-b-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testRuntimeScopeFilterDeprecated() throws ResolutionException - { - String name = "runtimeScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .resolveAs(GenericArchive.class, new ScopeFilter("runtime"))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as test-deps-b:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-b-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts - * - * @throws ResolutionException - */ - @Test - public void testCombinedScopeFilter() throws ResolutionException - { - String name = "testCombinedScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") - .addAsLibraries( - DependencyResolvers - .use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0") - .scope("test") +public class MavenResolutionFilterUnitTestCase { + + @BeforeClass + public static void setRemoteRepository() { + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); + } + + /** + * Tests that only directly defined artifacts are added to dependencies + * + * @throws ResolutionException + */ + @Test + public void testStrictFilter() throws ResolutionException { + String name = "strictFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0") + .resolveAs(GenericArchive.class, new StrictFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is only one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-child:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-child-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests that only directly defined artifacts are added to dependencies + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testStrictFilterDeprecated() throws ResolutionException { + String name = "strictFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0") + .resolveAs(GenericArchive.class, new StrictFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is only one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-child:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-child-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests that only directly defined artifacts are added to dependencies, the artifact version is taken from a POM file + * + * @throws ResolutionException + */ + @Test + public void testStrictFilterInferredVersion() throws ResolutionException { + String name = "strictFilterInferredVersion"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class, new StrictFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is only one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-deps-c:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-c-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests that only directly defined artifacts are added to dependencies, the artifact version is taken from a POM file + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testStrictFilterInferredVersionDeprecated() throws ResolutionException { + String name = "strictFilterInferredVersion"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class, new StrictFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is only one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-deps-c:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-c-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests loading of a POM file with parent not available on local file system + * + * @throws ResolutionException + */ + @Test + public void testDefaultScopeFilter() throws ResolutionException { + String name = "defaultScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-remote-child:1.0.0") + .resolveAs(GenericArchive.class, new ScopeFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-remote-child:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-remote-child-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent not available on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testDefaultScopeFilterDeprecated() throws ResolutionException { + String name = "defaultScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-remote-child:1.0.0") + .resolveAs(GenericArchive.class, new ScopeFilter())); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-remote-child:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-remote-child-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope + * + * @throws ResolutionException + */ + @Test + public void testRuntimeScopeFilter() throws ResolutionException { + String name = "runtimeScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .resolveAs(GenericArchive.class, - new CombinedFilter(new ScopeFilter("", "test"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There are two jars in the package", 2, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testCombinedScopeFilterDeprecated() throws ResolutionException - { - String name = "testCombinedScopeFilter"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") - .addAsLibraries( - DependencyResolvers - .use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0") - .scope("test") + .resolveAs(GenericArchive.class, new ScopeFilter("runtime"))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-deps-b:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-b-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testRuntimeScopeFilterDeprecated() throws ResolutionException { + String name = "runtimeScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .resolveAs(GenericArchive.class, - new CombinedFilter(new ScopeFilter("", "test"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There are two jars in the package", 2, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts. Uses artifacts() method - * - * @throws ResolutionException - */ - @Test - public void testCombinedScopeFilter2() throws ResolutionException - { - String name = "testCombinedScopeFilter2"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers - .use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-parent.xml") - .artifacts("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0", - "org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("test") - .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("test"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There are two jars in the package", 2, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts. Uses artifacts() method - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testCombinedScopeFilter2Deprecated() throws ResolutionException - { - String name = "testCombinedScopeFilter2"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers - .use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-parent.xml") - .artifacts("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0", - "org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("test") - .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("test"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There are two jars in the package", 2, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts - * - * @throws ResolutionException - */ - @Test - public void testCombinedScopeFilter3() throws ResolutionException - { - String name = "testCombinedScopeFilter3"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") - .addAsLibraries( - DependencyResolvers + .resolveAs(GenericArchive.class, new ScopeFilter("runtime"))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as test-deps-b:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-deps-b-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts + * + * @throws ResolutionException + */ + @Test + public void testCombinedScopeFilter() throws ResolutionException { + String name = "testCombinedScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("", "test"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There are two jars in the package", 2, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testCombinedScopeFilterDeprecated() throws ResolutionException { + String name = "testCombinedScopeFilter"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("", "test"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There are two jars in the package", 2, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts. Uses artifacts() method + * + * @throws ResolutionException + */ + @Test + public void testCombinedScopeFilter2() throws ResolutionException { + String name = "testCombinedScopeFilter2"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers .use(MavenDependencyResolver.class) .loadMetadataFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0") - .scope("test") - .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .scope("provided") - .resolveAs(GenericArchive.class, - new CombinedFilter(new ScopeFilter("provided"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrap.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests limiting of the scope and strict artifacts - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testCombinedScopeFilter3Deprecated() throws ResolutionException - { - String name = "testCombinedScopeFilter3"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war") - .addAsLibraries( - DependencyResolvers + .artifacts("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0", + "org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("test") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("test"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There are two jars in the package", 2, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts. Uses artifacts() method + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testCombinedScopeFilter2Deprecated() throws ResolutionException { + String name = "testCombinedScopeFilter2"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers .use(MavenDependencyResolver.class) .loadReposFromPom("target/poms/test-parent.xml") - .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0") - .scope("test") - .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0") - .scope("provided") - .resolveAs(GenericArchive.class, - new CombinedFilter(new ScopeFilter("provided"), new StrictFilter()))); - - Map map = war.getContent(JAR_FILTER); - - Assert.assertEquals("There is one jar in the package", 1, map.size()); - Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrap.test:test-dependency:1.0.0", - map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests resolution of dependencies for a POM file with parent on local file - * system - * - * @throws ResolutionException - */ - @Test - public void testPomBasedDependenciesWithScope() throws ResolutionException - { - String name = "pomBasedDependenciesWithScope"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .includeDependenciesFromPom("target/poms/test-child.xml") - .resolveAs(JavaArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests resolution of dependencies for a POM file with parent on local file - * system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testPomBasedDependenciesWithScopeDeprecated() throws ResolutionException - { - String name = "pomBasedDependenciesWithScope"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadDependenciesFromPom("target/poms/test-child.xml") - .resolveAs(JavaArchive.class, new ScopeFilter("test"))); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree"), "test"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - // filter to retrieve jar files only - private static final Filter JAR_FILTER = new Filter() - { - public boolean include(ArchivePath object) - { - if (object.get().endsWith(".jar")) - { - return true; - } - - return false; - } - }; + .artifacts("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0", + "org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("test") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("test"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There are two jars in the package", 2, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency-test:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-test-1.0.0.jar"))); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrapt.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts + * + * @throws ResolutionException + */ + @Test + public void testCombinedScopeFilter3() throws ResolutionException { + String name = "testCombinedScopeFilter3"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("provided") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("provided"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrap.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests limiting of the scope and strict artifacts + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testCombinedScopeFilter3Deprecated() throws ResolutionException { + String name = "testCombinedScopeFilter3"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-parent.xml") + .artifact("org.jboss.shrinkwrap.test:test-dependency-test:1.0.0").scope("test") + .artifact("org.jboss.shrinkwrap.test:test-dependency:1.0.0").scope("provided") + .resolveAs(GenericArchive.class, new CombinedFilter(new ScopeFilter("provided"), new StrictFilter()))); + + Map map = war.getContent(JAR_FILTER); + + Assert.assertEquals("There is one jar in the package", 1, map.size()); + Assert.assertTrue("The artifact is packaged as org.jboss.shrinkwrap.test:test-dependency:1.0.0", + map.containsKey(ArchivePaths.create("WEB-INF/lib/test-dependency-1.0.0.jar"))); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests resolution of dependencies for a POM file with parent on local file system + * + * @throws ResolutionException + */ + @Test + public void testPomBasedDependenciesWithScope() throws ResolutionException { + String name = "pomBasedDependenciesWithScope"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).includeDependenciesFromPom("target/poms/test-child.xml") + .resolveAs(JavaArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests resolution of dependencies for a POM file with parent on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testPomBasedDependenciesWithScopeDeprecated() throws ResolutionException { + String name = "pomBasedDependenciesWithScope"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadDependenciesFromPom("target/poms/test-child.xml") + .resolveAs(JavaArchive.class, new ScopeFilter("test"))); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree"), "test"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + // filter to retrieve jar files only + private static final Filter JAR_FILTER = new Filter() { + public boolean include(ArchivePath object) { + if (object.get().endsWith(".jar")) { + return true; + } + + return false; + } + }; } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MirrorTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MirrorTestCase.java index b02758ea..1d4cac38 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MirrorTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MirrorTestCase.java @@ -16,26 +16,21 @@ * @author Karel Piwko * */ -public class MirrorTestCase -{ +public class MirrorTestCase { - /** - * Tests a resolution of an artifact from JBoss repository specified in - * settings.xml within activeProfiles mirrored - * - * @throws ResolutionException - */ - @Test - public void enabledMirror() throws ResolutionException - { - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings-mirror.xml") - .useCentralRepo(false) - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAsFiles(new StrictFilter()); + /** + * Tests a resolution of an artifact from JBoss repository specified in settings.xml within activeProfiles mirrored + * + * @throws ResolutionException + */ + @Test + public void enabledMirror() throws ResolutionException { + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings-mirror.xml").useCentralRepo(false) + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAsFiles(new StrictFilter()); - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); - } + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MiscUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MiscUnitTestCase.java index 04b5f50c..edb9782f 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MiscUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/MiscUnitTestCase.java @@ -31,40 +31,34 @@ * @author Karel Piwko * */ -public class MiscUnitTestCase -{ - @BeforeClass - public static void setRemoteRepository() - { - System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings.xml"); - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); - } +public class MiscUnitTestCase { + @BeforeClass + public static void setRemoteRepository() { + System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings.xml"); + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); + } - @AfterClass - public static void clearRemoteRepository() - { - System.clearProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION); - System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); - } + @AfterClass + public static void clearRemoteRepository() { + System.clearProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION); + System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); + } - /** - * Tests resolution of dependencies for a POM file with parent on local file - * system - * - * @throws ResolutionException - */ - @Test - public void testFilesResolution() throws ResolutionException - { - String name = "customDependencies"; + /** + * Tests resolution of dependencies for a POM file with parent on local file system + * + * @throws ResolutionException + */ + @Test + public void testFilesResolution() throws ResolutionException { + String name = "customDependencies"; - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .artifact("org.jboss.shrinkwrap.test:test-deps-a:1.0.0") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAsFiles(); + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .artifact("org.jboss.shrinkwrap.test:test-deps-a:1.0.0") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAsFiles(); - DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name - + ".tree")); - desc.validateFiles(files).results(); - } + DependencyTreeDescription desc = new DependencyTreeDescription(new File("src/test/resources/dependency-trees/" + name + + ".tree")); + desc.validateFiles(files).results(); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/OfflineRepositoryTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/OfflineRepositoryTestCase.java index 6f750188..dc806ad0 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/OfflineRepositoryTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/OfflineRepositoryTestCase.java @@ -48,216 +48,180 @@ * * @author Karel Piwko */ -public class OfflineRepositoryTestCase -{ - private static final Logger log = Logger.getLogger(OfflineRepositoryTestCase.class.getName()); - - private static final int HTTP_TEST_PORT = 12345; - - /** - * Cleanup, remove the repositories from previous tests - */ - @Before - public void cleanup() throws Exception - { - FileUtil.removeDirectory(new File("target/jetty-repository")); - FileUtil.removeDirectory(new File("target/offline-repository")); - } - - /** - * Goes offline from settings.xml - * - * @throws Exception - */ - @Test - public void searchJunitOnOffineSettingsTest() throws Exception - { - try - { - DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings-offline.xml").artifact("junit:junit:3.8.2") - .resolveAsFiles(); - } - catch (ResolutionException e) - { - Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); - } - } - - /** - * Goes offline if specified by user - * - * @throws Exception - */ - @Test - public void searchJunitOnOffineProgrammaticTest() throws Exception - { - - try - { - DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") - .goOffline().artifact("junit:junit:3.8.2").resolveAsFiles(); - Assert.fail("Artifact junit:junit:3.8.2 is not present in local repository"); - } - catch (ResolutionException e) - { - Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); - } - } - - /** - * Goes offline if specified by system property - * - * @throws Exception - */ - @Test - public void searchJunitOnOffinePropertyTest() throws Exception - { - System.setProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE, "true"); - - try - { - DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") - .artifact("junit:junit:3.8.2").resolveAsFiles(); - Assert.fail("Artifact junit:junit:3.8.2 is not present in local repository"); - } - catch (ResolutionException e) - { - Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); - } - - System.clearProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE); - } - - @Test - public void searchWithRemoteOffAndOn() throws Exception - { - // offline - try - { - DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings-jetty.xml").goOffline() - .artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); - Assert.fail("Artifact org.jboss.shrinkwrap.test:test-deps-i:1.0.0 is not present in local repository"); - - } - catch (ResolutionException e) - { - Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); - } - - // online - Server server = startHttpServer(); - File[] file = DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings-jetty.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); - shutdownHttpServer(server); - Assert.assertEquals("One file was retrieved", 1, file.length); - - // offline with artifact in local repository - file = DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings-jetty.xml").goOffline() - .artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); - - Assert.assertEquals("One file was retrieved", 1, file.length); - } - - private Server startHttpServer() - { - // Start an Embedded HTTP Server - final Handler handler = new StaticFileHandler(); - final Server httpServer = new Server(HTTP_TEST_PORT); - httpServer.setHandler(handler); - try - { - httpServer.start(); - log.info("HTTP Server Started: " + httpServer); - return httpServer; - } - catch (final Exception e) - { - throw new RuntimeException("Could not start server"); - } - } - - private void shutdownHttpServer(Server httpServer) - { - if (httpServer != null) - { - try - { - httpServer.stop(); - } - catch (final Exception e) - { - // Swallow - log.severe("Could not stop HTTP Server cleanly, " + e.getMessage()); - } - log.info("HTTP Server Stopped: " + httpServer); - } - } - - /** - * Jetty Handler to serve a static character file from the web root - */ - private static class StaticFileHandler extends AbstractHandler implements Handler - { - /* - * (non-Javadoc) - * - * @see org.mortbay.jetty.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, int) - */ - @Override - public void handle(final String target, final HttpServletRequest request, final HttpServletResponse response, - final int dispatch) throws IOException, ServletException - { - // Set content type and status before we write anything to the stream - response.setContentType("text/xml"); - response.setStatus(HttpServletResponse.SC_OK); - - // Obtain the requested file relative to the webroot - final URL root = getCodebaseLocation(); - final URL fileUrl = new URL(root.toExternalForm() + target); - URI uri = null; - try - { - uri = fileUrl.toURI(); - } - catch (final URISyntaxException urise) - { - throw new RuntimeException(urise); - } - final File file = new File(uri); - - // File not found, so 404 - if (!file.exists()) - { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - log.warning("Requested file is not found: " + file); - return; - } - - // Write out each line - final BufferedReader reader = new BufferedReader(new FileReader(file)); - final PrintWriter writer = response.getWriter(); - String line = null; - while ((line = reader.readLine()) != null) - { - writer.println(line); - } - - // Close 'er up - writer.flush(); - reader.close(); - writer.close(); - } - - private URL getCodebaseLocation() throws MalformedURLException - { - return new File("target/repository").toURI().toURL(); - } - - } +public class OfflineRepositoryTestCase { + private static final Logger log = Logger.getLogger(OfflineRepositoryTestCase.class.getName()); + + private static final int HTTP_TEST_PORT = 12345; + + /** + * Cleanup, remove the repositories from previous tests + */ + @Before + public void cleanup() throws Exception { + FileUtil.removeDirectory(new File("target/jetty-repository")); + FileUtil.removeDirectory(new File("target/offline-repository")); + } + + /** + * Goes offline from settings.xml + * + * @throws Exception + */ + @Test + public void searchJunitOnOffineSettingsTest() throws Exception { + try { + DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings-offline.xml").artifact("junit:junit:3.8.2") + .resolveAsFiles(); + } catch (ResolutionException e) { + Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); + } + } + + /** + * Goes offline if specified by user + * + * @throws Exception + */ + @Test + public void searchJunitOnOffineProgrammaticTest() throws Exception { + + try { + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") + .goOffline().artifact("junit:junit:3.8.2").resolveAsFiles(); + Assert.fail("Artifact junit:junit:3.8.2 is not present in local repository"); + } catch (ResolutionException e) { + Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); + } + } + + /** + * Goes offline if specified by system property + * + * @throws Exception + */ + @Test + public void searchJunitOnOffinePropertyTest() throws Exception { + System.setProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE, "true"); + + try { + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings.xml") + .artifact("junit:junit:3.8.2").resolveAsFiles(); + Assert.fail("Artifact junit:junit:3.8.2 is not present in local repository"); + } catch (ResolutionException e) { + Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); + } + + System.clearProperty(MavenSettingsBuilder.ALT_MAVEN_OFFLINE); + } + + @Test + public void searchWithRemoteOffAndOn() throws Exception { + // offline + try { + DependencyResolvers.use(MavenDependencyResolver.class).configureFrom("target/settings/profiles/settings-jetty.xml") + .goOffline().artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); + Assert.fail("Artifact org.jboss.shrinkwrap.test:test-deps-i:1.0.0 is not present in local repository"); + + } catch (ResolutionException e) { + Assert.assertTrue("Unable to resolve an artifact", e.getMessage().startsWith("Unable to resolve an artifact")); + } + + // online + Server server = startHttpServer(); + File[] file = DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings-jetty.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); + shutdownHttpServer(server); + Assert.assertEquals("One file was retrieved", 1, file.length); + + // offline with artifact in local repository + file = DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings-jetty.xml").goOffline() + .artifact("org.jboss.shrinkwrap.test:test-deps-i:1.0.0").resolveAsFiles(); + + Assert.assertEquals("One file was retrieved", 1, file.length); + } + + private Server startHttpServer() { + // Start an Embedded HTTP Server + final Handler handler = new StaticFileHandler(); + final Server httpServer = new Server(HTTP_TEST_PORT); + httpServer.setHandler(handler); + try { + httpServer.start(); + log.info("HTTP Server Started: " + httpServer); + return httpServer; + } catch (final Exception e) { + throw new RuntimeException("Could not start server"); + } + } + + private void shutdownHttpServer(Server httpServer) { + if (httpServer != null) { + try { + httpServer.stop(); + } catch (final Exception e) { + // Swallow + log.severe("Could not stop HTTP Server cleanly, " + e.getMessage()); + } + log.info("HTTP Server Stopped: " + httpServer); + } + } + + /** + * Jetty Handler to serve a static character file from the web root + */ + private static class StaticFileHandler extends AbstractHandler implements Handler { + /* + * (non-Javadoc) + * + * @see org.mortbay.jetty.Handler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, int) + */ + @Override + public void handle(final String target, final HttpServletRequest request, final HttpServletResponse response, + final int dispatch) throws IOException, ServletException { + // Set content type and status before we write anything to the stream + response.setContentType("text/xml"); + response.setStatus(HttpServletResponse.SC_OK); + + // Obtain the requested file relative to the webroot + final URL root = getCodebaseLocation(); + final URL fileUrl = new URL(root.toExternalForm() + target); + URI uri = null; + try { + uri = fileUrl.toURI(); + } catch (final URISyntaxException urise) { + throw new RuntimeException(urise); + } + final File file = new File(uri); + + // File not found, so 404 + if (!file.exists()) { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + log.warning("Requested file is not found: " + file); + return; + } + + // Write out each line + final BufferedReader reader = new BufferedReader(new FileReader(file)); + final PrintWriter writer = response.getWriter(); + String line = null; + while ((line = reader.readLine()) != null) { + writer.println(line); + } + + // Close 'er up + writer.flush(); + reader.close(); + writer.close(); + } + + private URL getCodebaseLocation() throws MalformedURLException { + return new File("target/repository").toURI().toURL(); + } + + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/PomDependenciesUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/PomDependenciesUnitTestCase.java index b3ea3c35..2e7958a0 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/PomDependenciesUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/PomDependenciesUnitTestCase.java @@ -34,295 +34,266 @@ * @author Karel Piwko * */ -public class PomDependenciesUnitTestCase -{ - @BeforeClass - public static void setRemoteRepository() - { - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); - } - - @AfterClass - public static void clearRemoteRepository() - { - System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); - } - - /** - * Tests loading of a POM file with parent not available on local file system - * - * @throws ResolutionException - */ - @Test - public void testParentPomRepositories() throws ResolutionException - { - String name = "parentPomRepositories"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests loading of a POM file with parent not available on local file system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testParentPomRepositoriesDeprecated() throws ResolutionException - { - String name = "parentPomRepositories"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree"), "compile"); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests loading of a POM file with parent available on local file system - * - * @throws ResolutionException - */ - @Test - public void testParentPomRemoteRepositories() throws ResolutionException - { - String name = "parentPomRemoteRepositories"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent available on local file system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testParentPomRemoteRepositoriesDeprecated() throws ResolutionException - { - String name = "parentPomRemoteRepositories"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent available on local file system - * Uses POM to get artifact version - * - * @throws ResolutionException - */ - @Test - public void testArtifactVersionRetrievalFromPom() throws ResolutionException - { - String name = "artifactVersionRetrievalFromPom"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent available on local file system - * Uses POM to get artifact version - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testArtifactVersionRetrievalFromPomDeprecated() throws ResolutionException - { - String name = "artifactVersionRetrievalFromPom"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent available on local file system. - * However, the artifact version is not used from there, but specified - * manually - * - * @throws ResolutionException - */ - @Test - public void testArtifactVersionRetrievalFromPomOverride() throws ResolutionException - { - String name = "artifactVersionRetrievalFromPomOverride"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:2.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c-2.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests loading of a POM file with parent available on local file system. - * However, the artifact version is not used from there, but specified - * manually - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testArtifactVersionRetrievalFromPomOverrideDeprecated() throws ResolutionException - { - String name = "artifactVersionRetrievalFromPomOverride"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadReposFromPom("target/poms/test-remote-child.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:2.0.0").resolveAs(GenericArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-deps-c-2.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests resolution of dependencies for a POM file with parent on local file - * system - * - * @throws ResolutionException - */ - @Test - public void testPomBasedDependencies() throws ResolutionException - { - String name = "pomBasedDependencies"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .includeDependenciesFromPom("target/poms/test-child.xml").resolveAs(JavaArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests resolution of dependencies for a POM file with parent on local file - * system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testPomBasedDependenciesDeprecated() throws ResolutionException - { - String name = "pomBasedDependencies"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadDependenciesFromPom("target/poms/test-child.xml").resolveAs(JavaArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-child.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - - } - - /** - * Tests resolution of dependencies for a POM file without parent on local - * file system - * - * @throws ResolutionException - */ - @Test - public void testPomRemoteBasedDependencies() throws ResolutionException - { - String name = "pomRemoteBasedDependencies"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .includeDependenciesFromPom("target/poms/test-remote-child.xml").resolveAs(JavaArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-remote-child.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } - - /** - * Tests resolution of dependencies for a POM file without parent on local - * file system - * - * @throws ResolutionException - */ - @Test - @Deprecated - public void testPomRemoteBasedDependenciesDeprecated() throws ResolutionException - { - String name = "pomRemoteBasedDependencies"; - - WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( - DependencyResolvers.use(MavenDependencyResolver.class) - .loadDependenciesFromPom("target/poms/test-remote-child.xml").resolveAs(JavaArchive.class)); - - DependencyTreeDescription desc = new DependencyTreeDescription(new File( - "src/test/resources/dependency-trees/test-remote-child.tree")); - desc.validateArchive(war).results(); - - war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } +public class PomDependenciesUnitTestCase { + @BeforeClass + public static void setRemoteRepository() { + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/the-other-repository"); + } + + @AfterClass + public static void clearRemoteRepository() { + System.clearProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION); + } + + /** + * Tests loading of a POM file with parent not available on local file system + * + * @throws ResolutionException + */ + @Test + public void testParentPomRepositories() throws ResolutionException { + String name = "parentPomRepositories"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests loading of a POM file with parent not available on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testParentPomRepositoriesDeprecated() throws ResolutionException { + String name = "parentPomRepositories"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-child:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree"), "compile"); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests loading of a POM file with parent available on local file system + * + * @throws ResolutionException + */ + @Test + public void testParentPomRemoteRepositories() throws ResolutionException { + String name = "parentPomRemoteRepositories"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent available on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testParentPomRemoteRepositoriesDeprecated() throws ResolutionException { + String name = "parentPomRemoteRepositories"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent available on local file system Uses POM to get artifact version + * + * @throws ResolutionException + */ + @Test + public void testArtifactVersionRetrievalFromPom() throws ResolutionException { + String name = "artifactVersionRetrievalFromPom"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent available on local file system Uses POM to get artifact version + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testArtifactVersionRetrievalFromPomDeprecated() throws ResolutionException { + String name = "artifactVersionRetrievalFromPom"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent available on local file system. However, the artifact version is not used from + * there, but specified manually + * + * @throws ResolutionException + */ + @Test + public void testArtifactVersionRetrievalFromPomOverride() throws ResolutionException { + String name = "artifactVersionRetrievalFromPomOverride"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:2.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c-2.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests loading of a POM file with parent available on local file system. However, the artifact version is not used from + * there, but specified manually + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testArtifactVersionRetrievalFromPomOverrideDeprecated() throws ResolutionException { + String name = "artifactVersionRetrievalFromPomOverride"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadReposFromPom("target/poms/test-remote-child.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:2.0.0").resolveAs(GenericArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-deps-c-2.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests resolution of dependencies for a POM file with parent on local file system + * + * @throws ResolutionException + */ + @Test + public void testPomBasedDependencies() throws ResolutionException { + String name = "pomBasedDependencies"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).includeDependenciesFromPom("target/poms/test-child.xml") + .resolveAs(JavaArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests resolution of dependencies for a POM file with parent on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testPomBasedDependenciesDeprecated() throws ResolutionException { + String name = "pomBasedDependencies"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class).loadDependenciesFromPom("target/poms/test-child.xml") + .resolveAs(JavaArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-child.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + + } + + /** + * Tests resolution of dependencies for a POM file without parent on local file system + * + * @throws ResolutionException + */ + @Test + public void testPomRemoteBasedDependencies() throws ResolutionException { + String name = "pomRemoteBasedDependencies"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class) + .includeDependenciesFromPom("target/poms/test-remote-child.xml").resolveAs(JavaArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-remote-child.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } + + /** + * Tests resolution of dependencies for a POM file without parent on local file system + * + * @throws ResolutionException + */ + @Test + @Deprecated + public void testPomRemoteBasedDependenciesDeprecated() throws ResolutionException { + String name = "pomRemoteBasedDependencies"; + + WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war").addAsLibraries( + DependencyResolvers.use(MavenDependencyResolver.class) + .loadDependenciesFromPom("target/poms/test-remote-child.xml").resolveAs(JavaArchive.class)); + + DependencyTreeDescription desc = new DependencyTreeDescription(new File( + "src/test/resources/dependency-trees/test-remote-child.tree")); + desc.validateArchive(war).results(); + + war.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ProfilesUnitTestCase.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ProfilesUnitTestCase.java index b74e75a9..8e02354a 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ProfilesUnitTestCase.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/impl/maven/ProfilesUnitTestCase.java @@ -32,63 +32,53 @@ * @author Karel Piwko * */ -public class ProfilesUnitTestCase -{ - /** - * Tests a resolution of an artifact from JBoss repository specified in - * settings.xml as active profile - * - * @throws ResolutionException - */ - @Test - public void testSettingsProfiles() throws ResolutionException - { - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAsFiles(new StrictFilter()); +public class ProfilesUnitTestCase { + /** + * Tests a resolution of an artifact from JBoss repository specified in settings.xml as active profile + * + * @throws ResolutionException + */ + @Test + public void testSettingsProfiles() throws ResolutionException { + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings.xml").artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") + .resolveAsFiles(new StrictFilter()); - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); - } + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); + } - /** - * Tests a resolution of an artifact from JBoss repository specified in - * settings.xml within activeProfiles - * - * @throws ResolutionException - */ - @Test - public void testSettingsProfiles2() throws ResolutionException - { - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .configureFrom("target/settings/profiles/settings2.xml") - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAsFiles(new StrictFilter()); + /** + * Tests a resolution of an artifact from JBoss repository specified in settings.xml within activeProfiles + * + * @throws ResolutionException + */ + @Test + public void testSettingsProfiles2() throws ResolutionException { + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .configureFrom("target/settings/profiles/settings2.xml") + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAsFiles(new StrictFilter()); - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); - } + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); + } - /** - * Tests a resolution of an artifact from JBoss repository specified in - * settings.xml within activeProfiles. The path to do file is defined via - * system property. - * - * @throws ResolutionException - */ - @Test - public void testSystemPropertiesSettingsProfiles() throws ResolutionException - { - System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings3.xml"); - System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/prop-profiles"); + /** + * Tests a resolution of an artifact from JBoss repository specified in settings.xml within activeProfiles. The path to do + * file is defined via system property. + * + * @throws ResolutionException + */ + @Test + public void testSystemPropertiesSettingsProfiles() throws ResolutionException { + System.setProperty(MavenSettingsBuilder.ALT_USER_SETTINGS_XML_LOCATION, "target/settings/profiles/settings3.xml"); + System.setProperty(MavenSettingsBuilder.ALT_LOCAL_REPOSITORY_LOCATION, "target/prop-profiles"); - File[] files = DependencyResolvers.use(MavenDependencyResolver.class) - .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0") - .resolveAsFiles(new StrictFilter()); + File[] files = DependencyResolvers.use(MavenDependencyResolver.class) + .artifact("org.jboss.shrinkwrap.test:test-deps-c:1.0.0").resolveAsFiles(new StrictFilter()); - Assert.assertEquals("There is only one jar in the package", 1, files.length); - Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); - } + Assert.assertEquals("There is only one jar in the package", 1, files.length); + Assert.assertEquals("The file is packaged as test-deps-c-1.0.0.jar", "test-deps-c-1.0.0.jar", files[0].getName()); + } } diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/FileUtil.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/FileUtil.java index e60d0085..8c62f8a1 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/FileUtil.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/FileUtil.java @@ -25,44 +25,35 @@ * @author Karel Piwko * */ -public class FileUtil -{ - - /** - * Deletes a directory from file system. It simply ignores non-existing directories - * - * @param directory the directory to be deleted - * @throws IOException if the directory cannot be deleted - */ - public static void removeDirectory(File directory) throws IOException - { - - if (directory == null || !directory.exists() || !directory.canWrite() || !directory.canExecute()) - { - return; - } - - for (File entry : directory.listFiles()) - { - - if (entry.isDirectory()) - { - removeDirectory(entry); - } - else - { - if (!entry.delete()) - { - throw new IOException("Could not delete directory " + directory.getAbsolutePath()); +public class FileUtil { + + /** + * Deletes a directory from file system. It simply ignores non-existing directories + * + * @param directory the directory to be deleted + * @throws IOException if the directory cannot be deleted + */ + public static void removeDirectory(File directory) throws IOException { + + if (directory == null || !directory.exists() || !directory.canWrite() || !directory.canExecute()) { + return; + } + + for (File entry : directory.listFiles()) { + + if (entry.isDirectory()) { + removeDirectory(entry); + } else { + if (!entry.delete()) { + throw new IOException("Could not delete directory " + directory.getAbsolutePath()); + } } - } - } + } - if (!directory.delete()) - { - throw new IOException("Could not delete directory " + directory.getAbsolutePath()); - } + if (!directory.delete()) { + throw new IOException("Could not delete directory " + directory.getAbsolutePath()); + } - } + } } \ No newline at end of file diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/JarGenerator.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/JarGenerator.java index b9df6b17..08514616 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/JarGenerator.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/JarGenerator.java @@ -45,51 +45,43 @@ * */ @RunWith(Parameterized.class) -public class JarGenerator -{ - private String name; - private Class[] content; +public class JarGenerator { + private String name; + private Class[] content; - @Parameters - public static Collection jars() - { - Object[][] data = new Object[][] { - { "test-managed-dependency", new Class[] { Object.class, List.class}}, - { "test-managed-dependency-2", new Class[] { List.class}}, - { "test-dependency", new Class[] { Arrays.class }}, - { "test-dependency-with-exclusion", new Class[] { Collections.class}}, - { "test-exclusion", new Class[] { ArrayList.class, LinkedList.class}}, - { "test-dependency-provided", new Class[] { List.class, Map.class}}, - { "test-dependency-test", new Class[] { ArrayList.class, HashMap.class}}, - { "test-parent", new Class[] { File.class }}, - { "test-child", new Class[] { InputStream.class }}, - { "test-remote-parent", new Class[] {OutputStream.class }}, - { "test-deps-a", new Class[] {System.class }}, - { "test-deps-b", new Class[] {Field.class }}, - { "test-deps-c", new Class[] {Integer.class }}, - { "test-deps-d", new Class[] {Float.class, Double.class }}, - { "test-deps-e", new Class[] {String.class, StringBuilder.class }}, - { "test-deps-f", new Class[] {Thread.class }}, - { "test-deps-g", new Class[] {Object.class, String.class }}, - { "test-deps-h", new Class[] {Character.class, Byte.class }}, - { "test-deps-i", new Class[] {System.class, PrintStream.class }}, - }; + @Parameters + public static Collection jars() { + Object[][] data = new Object[][] { { "test-managed-dependency", new Class[] { Object.class, List.class } }, + { "test-managed-dependency-2", new Class[] { List.class } }, + { "test-dependency", new Class[] { Arrays.class } }, + { "test-dependency-with-exclusion", new Class[] { Collections.class } }, + { "test-exclusion", new Class[] { ArrayList.class, LinkedList.class } }, + { "test-dependency-provided", new Class[] { List.class, Map.class } }, + { "test-dependency-test", new Class[] { ArrayList.class, HashMap.class } }, + { "test-parent", new Class[] { File.class } }, { "test-child", new Class[] { InputStream.class } }, + { "test-remote-parent", new Class[] { OutputStream.class } }, + { "test-deps-a", new Class[] { System.class } }, { "test-deps-b", new Class[] { Field.class } }, + { "test-deps-c", new Class[] { Integer.class } }, + { "test-deps-d", new Class[] { Float.class, Double.class } }, + { "test-deps-e", new Class[] { String.class, StringBuilder.class } }, + { "test-deps-f", new Class[] { Thread.class } }, + { "test-deps-g", new Class[] { Object.class, String.class } }, + { "test-deps-h", new Class[] { Character.class, Byte.class } }, + { "test-deps-i", new Class[] { System.class, PrintStream.class } }, }; - return Arrays.asList(data); - } + return Arrays.asList(data); + } - public JarGenerator(String name, Class[] content) - { - this.name = name; - this.content = content; - } + public JarGenerator(String name, Class[] content) { + this.name = name; + this.content = content; + } - @Test - public void createJars() - { - JavaArchive archive = ShrinkWrap.create(JavaArchive.class, name).addClasses(content); + @Test + public void createJars() { + JavaArchive archive = ShrinkWrap.create(JavaArchive.class, name).addClasses(content); - archive.as(ZipExporter.class).exportTo(new File("target/" + name + ".jar"), true); - } + archive.as(ZipExporter.class).exportTo(new File("target/" + name + ".jar"), true); + } } \ No newline at end of file diff --git a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/WarGenerator.java b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/WarGenerator.java index f333f502..02c03d9f 100644 --- a/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/WarGenerator.java +++ b/impl-maven/src/test/java/org/jboss/shrinkwrap/resolver/util/WarGenerator.java @@ -36,37 +36,31 @@ * */ @RunWith(Parameterized.class) -public class WarGenerator -{ - private String name; - private Class[] classes; - private String[] directories; +public class WarGenerator { + private String name; + private Class[] classes; + private String[] directories; - @Parameters - public static Collection jars() - { - Object[][] data = new Object[][] { - { "test-war", new Class[] { Object.class, List.class }, new String[] {"html", "jsp"} }, - { "test-war-classifier", new Class[] { Arrays.class }, new String[] {"xhtml", "rf" }} - }; + @Parameters + public static Collection jars() { + Object[][] data = new Object[][] { + { "test-war", new Class[] { Object.class, List.class }, new String[] { "html", "jsp" } }, + { "test-war-classifier", new Class[] { Arrays.class }, new String[] { "xhtml", "rf" } } }; - return Arrays.asList(data); - } + return Arrays.asList(data); + } - public WarGenerator(String name, Class[] classes, String[] directories) - { - this.name = name; - this.classes = classes; - this.directories = directories; - } + public WarGenerator(String name, Class[] classes, String[] directories) { + this.name = name; + this.classes = classes; + this.directories = directories; + } - @Test - public void createJars() - { - WebArchive archive = ShrinkWrap.create(WebArchive.class, name).addClasses(classes) - .addAsDirectories(directories); + @Test + public void createJars() { + WebArchive archive = ShrinkWrap.create(WebArchive.class, name).addClasses(classes).addAsDirectories(directories); - archive.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); - } + archive.as(ZipExporter.class).exportTo(new File("target/" + name + ".war"), true); + } } diff --git a/pom.xml b/pom.xml index 59303a98..39ffcaa0 100644 --- a/pom.xml +++ b/pom.xml @@ -1,283 +1,309 @@ - - + + - - - org.jboss - jboss-parent - 5 - + + + org.jboss + jboss-parent + 5 + - - 4.0.0 + + 4.0.0 - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-parent - 1.1.0-alpha-1-SNAPSHOT - pom - ShrinkWrap Resolver Aggregator - ShrinkWrap Resolver Aggregator + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-parent + 1.1.0-alpha-1-SNAPSHOT + pom + ShrinkWrap Resolver Aggregator + ShrinkWrap Resolver Aggregator - - - 4.8.2 - 3.0-beta-3 - 1.0.0-beta-5 - + + + 4.8.2 + 3.0-beta-3 + 1.0.0-beta-5 + - - - scm:git:git://github.com/shrinkwrap/resolver.git - scm:git:git@github.com:shrinkwrap/resolver.git - https://github.com/shrinkwrap/resolver - + + + scm:git:git://github.com/shrinkwrap/resolver.git + scm:git:git@github.com:shrinkwrap/resolver.git + https://github.com/shrinkwrap/resolver + - - - jira - http://jira.jboss.com/jira/browse/SHRINKWRAP - + + + jira + http://jira.jboss.com/jira/browse/SHRINKWRAP + - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + + - - + + - - - - - maven-assembly-plugin - 2.2.1 - - shrinkwrap-${project.version} - - dist.xml - - - - - - org.apache.maven.plugins - maven-site-plugin - ${version.org.apache.maven.plugins_maven-site-plugin} - - - - - - + + + + + maven-assembly-plugin + 2.2.1 + + shrinkwrap-${project.version} + + dist.xml + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.6 + + code-style/checkstyle.xml + true + error + + + + checkstyle-report + process-sources + + check + + + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-build-resources + ${project.version} + + + + + + org.apache.maven.plugins + maven-site-plugin + ${version.org.apache.maven.plugins_maven-site-plugin} + + + + - - - maven-release-plugin - 2.0 - - true - - + - - - maven-compiler-plugin - true - - 1.5 - 1.5 - false - true - true - 1.6 - true - -Xmx512M - ${JAVA_HOME}/bin/javac - - + + + maven-release-plugin + 2.0 + + true + + - - - maven-surefire-plugin - - true - false - true - - **/*TestCase.java - **/*TestSuite.java - - always - - + + + maven-compiler-plugin + true + + 1.5 + 1.5 + false + true + true + 1.6 + true + -Xmx512M + ${JAVA_HOME}/bin/javac + + - - - maven-enforcer-plugin + + + maven-surefire-plugin + + true + false + true + + **/*TestCase.java + **/*TestSuite.java + + always + + + + + + maven-enforcer-plugin - - - enforce-maven-environment - - enforce - - - - - - - [2.2.0,) - - - - 1.6.0 - - - env.JAVA_HOME - "JAVA_HOME needs to be set to compile" - - - env.JAVA5_HOME - "JAVA5_HOME needs to be set to run some tests in the JRE5 runtime" - - - - + + + enforce-maven-environment + + enforce + + + + + + + [2.2.0,) + + + + 1.6.0 + + + env.JAVA_HOME + "JAVA_HOME needs to be set to compile" + + + env.JAVA5_HOME + "JAVA5_HOME needs to be set to run some tests in the JRE5 runtime" + + + + - - + + - - - + + + - - org.jboss.shrinkwrap - shrinkwrap-api - ${version.org.jboss.shrinkwrap} - - - org.jboss.shrinkwrap - shrinkwrap-spi - ${version.org.jboss.shrinkwrap} - test - - - org.jboss.shrinkwrap - shrinkwrap-impl-base - ${version.org.jboss.shrinkwrap} - test - + + org.jboss.shrinkwrap + shrinkwrap-api + ${version.org.jboss.shrinkwrap} + + + org.jboss.shrinkwrap + shrinkwrap-spi + ${version.org.jboss.shrinkwrap} + test + + + org.jboss.shrinkwrap + shrinkwrap-impl-base + ${version.org.jboss.shrinkwrap} + test + - - junit - junit - ${version.junit_junit} - test - + + junit + junit + ${version.junit_junit} + test + - - + + - - - api - api-maven - impl-maven - + + + build-resources + api + api-maven + impl-maven + - - - + + + - - - org.codehaus.mojo - cobertura-maven-plugin - 2.3 - - - html - xml - - - + + + org.codehaus.mojo + cobertura-maven-plugin + 2.3 + + + html + xml + + + - - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.1 - - true - target/site - - + + + org.codehaus.mojo + findbugs-maven-plugin + 2.3.1 + + true + target/site + + - - - org.apache.maven.plugins - maven-project-info-reports-plugin - - - - project-team - mailing-list - cim - issue-tracking - license - scm - - - - - - - - - - - jboss-public-repository - JBoss Repository - https://repository.jboss.org/nexus/content/groups/public - - true - never - - - true - never - - - + + + org.apache.maven.plugins + maven-project-info-reports-plugin + + + + project-team + mailing-list + cim + issue-tracking + license + scm + + + + - - - jboss-public-repository - JBoss Repository - https://repository.jboss.org/nexus/content/groups/public - - true - never - - - true - never - - - + + - + + + jboss-public-repository + JBoss Repository + https://repository.jboss.org/nexus/content/groups/public + + true + never + + + true + never + + + - + + + jboss-public-repository + JBoss Repository + https://repository.jboss.org/nexus/content/groups/public + + true + never + + + true + never + + + +
\ No newline at end of file